Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Python Pillow lib to set Color depth

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?

like image 979
alexis Avatar asked May 30 '14 09:05

alexis


1 Answers

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.

like image 168
Thomas Avatar answered Sep 19 '22 09:09

Thomas