Using Python Pillow lib to set Color depth

10,901

So far, I haven't been able to save 4-bit images with Pillow. You can use Pillow to reduce the number of gray levels in an image with:

import PIL.Image as Image
im = Image.open('test.png')
im1 = im.point(lambda x: int(x/17)*17)

Assuming test.png is a 8-bit graylevel image, i.e. it contains values in the range 0-255 (im.mode == 'L'), im1 now only contains 16 different values (0, 17, 34, ..., 255). This is what ufp.image.changeColorDepth does, too. However, you still have a 8-bit image. So instead of the above, you can do

im2 = im.point(lambda x: int(x/17))

and you end up with an image that only contains 16 different values (0, 1, 2, ..., 15). So these values would all fit in an uint4-type. However, if you save such an image with Pillow

im2.save('test.png')

the png will still have a color-depth of 8bit (and if you open the image, you see only really dark gray pixels). You can use PyPng to save a real 4-bit png:

import png
import numpy as np
png.fromarray(np.asarray(im2, np.uint8),'L;4').save('test4bit_pypng.png')

Unfortunately, PyPng seems to take much longer to save the images.

Share:
10,901
alexis
Author by

alexis

A network engineer (cisco) that codes on the side.

Updated on June 06, 2022

Comments

  • alexis
    alexis almost 2 years

    I am using the Python Pillow lib to change an image before sending it to device. I need to change the image to make sure it meets the following requirements

    • Resolution (width x height) = 298 x 144
    • Grayscale
    • Color Depth (bits) = 4
    • Format = .png

    I can do all of them with the exception of Color Depth to 4 bits. Can anyone point me in the right direction on how to achieve this?

  • Hardik Gajjar
    Hardik Gajjar about 8 years
    ImportError: No module named ufp.image getting this error please help
  • Dr. Goulu
    Dr. Goulu about 8 years
    the ufp.image code is here : github.com/Thestars3/pyufp/blob/master/ufp/image.py . Function changeColorDepth uses PIL only in a similar way than @Thomas code below