Convert pixels to cm using Python

1.4k Views Asked by At

I would like to know what am I doing wrong with this code :

if self.digital:
   im = Image.open(os.path.join(folder, filename))
   width, height = im.size
   image_info["width"] = round(width / 37.79527559055, 0)

I would like to use this code to convert the pixel size of a picture into centimeters, but I don't understand why it returns me this issue :

Python311\Lib\site-packages\PIL\Image.py:3167: DecompressionBombWarning: Image size (130437549 pixels) exceeds limit of 89478485 pixels, could be decompression bomb DOS attack.

I don't want to use DPI, in my script 1cm = 37.79527559055 pixels.

I'm going to use a temporary list to write pixels value in then convert but I would like to know if there is a faster way or not, and why exactly is it making a zip bomb.

Thanks !

1

There are 1 best solutions below

5
GIZ On

The issue is that the image you are trying to open is too large and its decompression would consume a lot of memory, which can be a potential security risk (known as "Decompression bomb"). To avoid this, you can increase the maximum size limit of the image in PIL by modifying the Image.MAX_IMAGE_PIXELS attribute:

Image.MAX_IMAGE_PIXELS = None # No Limit

It is important to consider the memory usage and performance of your script when using large images.

Regarding the conversion of pixels to centimeters, using a fixed number of pixels per centimeter is not the recommended approach as it depends on the display resolution and the physical size of the display. Instead, you should use the DPI (dots per inch) information embedded in the image file to perform the conversion. You can retrieve the DPI information using the 'info' attribute of the Image object and then use it to calculate the size in centimeters.

Here is an example of how you could do the conversion with DPI information:

from PIL import Image

im = Image.open(os.path.join(folder, filename))
width, height = im.size
dpi = im.info.get("dpi", (72, 72))
width_cm = width / dpi[0] * 2.54
height_cm = height / dpi[1] * 2.54

image_info["width_cm"] = width_cm
image_info["height_cm"] = height_cm

You can resize the image to a smaller size before processing it. You can use the Image.thumbnail() method provided by PIL to resize the image.