[英]Using Python Pillow lib to set Color depth
I am using the Python Pillow lib to change an image before sending it to device. 我使用Python Pillow lib在将图像发送到设备之前更改图像。 I need to change the image to make sure it meets the following requirements
我需要更改图像以确保它符合以下要求
I can do all of them with the exception of Color Depth to 4 bits. 除了Color Depth到4位,我可以做所有这些。 Can anyone point me in the right direction on how to achieve this?
任何人都可以指出我如何实现这一目标的正确方向?
So far, I haven't been able to save 4-bit images with Pillow. 到目前为止,我还没能用Pillow保存4位图像。 You can use Pillow to reduce the number of gray levels in an image with:
您可以使用Pillow来减少图像中的灰度级数:
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, ie it contains values in the range 0-255 (im.mode == 'L'), im1 now only contains 16 different values (0, 17, 34, ..., 255). 假设test.png是一个8位灰度图像,即它包含0-255范围内的值(im.mode =='L'),im1现在只包含16个不同的值(0,17,34,... ,255)。 This is what ufp.image.changeColorDepth does, too.
这也是ufp.image.changeColorDepth所做的。 However, you still have a 8-bit image.
但是,您仍然有一个8位图像。 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). 最终得到的图像只包含16个不同的值(0,1,2,...,15)。 So these values would all fit in an uint4-type.
所以这些值都适合uint4类型。 However, if you save such an image with Pillow
但是,如果用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). png的颜色深度仍为8bit(如果打开图像,则只能看到真正的深灰色像素)。 You can use PyPng to save a real 4-bit png:
你可以使用PyPng保存一个真正的4位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. 不幸的是,PyPng似乎需要更长的时间来保存图像。
using changeColorDepth function in ufp.image module. 在ufp.image模块中使用changeColorDepth函数。
import ufp.image
import PIL
im = PIL.Image.open('test.png')
im = im.convert('L') # change to grayscale image
im.thumbnail((298, 144)) # resize to 294x144
ufp.image.changeColorDepth(im, 16) # change 4bits depth(this function change original PIL.Image object)
#if you will need better convert. using ufp.image.quantizeByImprovedGrayScale function. this function quantized image.
im.save('changed.png')
see example : image quantize by Improved Gray Scale. 参见示例: 图像通过改进的灰度等级量化。 [Python]
[蟒蛇]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.