Intelligently Determine Image Size in Python
<p>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'.  </p>

<p>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 <em>think</em> 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:</p>

<pre><code>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)]
</code></pre>

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

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

<p>A good <strong>digital</strong> dimension has the following :</p>

<ul>
<li>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</li>
<li>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.</li>
<li>A kinda standard aspect ratio. square, 4:3, 16:9.</li>
<li>depending on the situation preservation of the aspect ratio of the source image.</li>
</ul>

<p>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...</p>

python image-processing python-imaging-library