Jason
Jason

Reputation: 894

Intelligently Determine Image Size in Python

I would like to use Python to intelligently choose dimensions (in inches) for pictures. Were I to do this manually, I would open the picture in some photo editing software and resize the image until it seemed 'good'.

Other answers I've seen on SO have pre-specified dimensions, but in this case that's what I want the program to determine. I'm terribly new to image processing, so I'm hesitant to be more specific. However, I think I want to choose a size such that DPI >= 300. All of these images will end up printed, which is why I'm focused on DPI as a metric. A horrible brute force way might be:

from PIL import Image
import numpy as np
import bisect

min_size = 1
max_size = 10
sizes = np.linspace(min_size, max_size)
for size in sizes:   
    im = Image.open(im_name)
    im.thumbnail((size, size), Image.ANTIALIAS) #assumes square images
    dpi_vals.append(im.info['dpi']))
best_size = sizes[bisect.bisect(dpi_vals, 300)]

This strikes me as very inefficient and I'm hoping someone with more experience has a smarter way.

Upvotes: 0

Views: 2292

Answers (2)

Jason
Jason

Reputation: 894

I guess I asked a bit prematurely. This hinges more on understanding resolution vs. DPI than it does on programming. Once I learned more, the answer becomes quite easy. Digital images have resolutions, while printed images have DPI. To choose the size of a digital image such that, if printed, that image will have 300 DPI is as simple as: pixels / 300. In the specific case of PIL, the following code works fine:

import PIL

im = Image.open(im_name)
print_ready_width = im.size[0] / 300

Then the image will have 300 DPI if printed at print_read_width.

Upvotes: 1

UmNyobe
UmNyobe

Reputation: 22910

Forget dpi. It is a very confusing term. Unless you scan\print (ie use a physical medium), this doesn't mean much.

A good digital dimension has the following :

  • The biggest factor of 2 possible. This is why most standard digital resolution (esp. in video have size multiple of 2^3, or 2^4). Digital filters and transformations take advantage of this for optimization
  • A simple factor between the source and target image (again mostly 2). cropping an image by a factor of 8 will almost always produce better results than cropping by 7. Most the time it will also be faster.
  • A kinda standard aspect ratio. square, 4:3, 16:9.
  • depending on the situation preservation of the aspect ratio of the source image.

This is why a lot of sites provide you a resizable rectangle\square box for some photos (like facebook profile picture), which will ensure the aspect ratio is the same as the one of the processed image, that the minimum\maximum dimensions are met, etc...

Upvotes: 1

Related Questions