简体   繁体   English

PIL像素RGBA Python

[英]PIL Pixel RGBA Python

I'm trying to get the RGBA value of each pixel of an image, the output seems to have more than 2 RGBA values.我正在尝试获取图像每个像素的 RGBA 值,output 似乎有超过 2 个 RGBA 值。

from PIL import Image

img = Image.open('image1.jpg', 'r')

img_data = list(img.getdata())

print(img_data)

image1.jpg:图片1.jpg:

图像1.jpg

Instead of [(0,0,0), (255,255,255)] I get [(0,0,0),(255,255,255),(254,254,254)]而不是[(0,0,0), (255,255,255)]我得到[(0,0,0),(255,255,255),(254,254,254)]

Because if you check RGB(254,254,254) in this website or any other is same as white color.因为如果您在本网站检查 RGB(254,254,254) 或任何其他颜色与白色相同。
this is why code gets confused between the black and white color border and give on more output这就是为什么代码在黑白边框之间混淆并给出更多 output

A JPG image never has transparency ("alpha") data: it is an opaque image format. JPG 图像从不具有透明度(“alpha”)数据:它是一种不透明的图像格式。 If you want the transparent channel information ("a" in "rgba", you will have to convert it first with:如果您想要透明通道信息(“rgba”中的“a”,则必须先将其转换为:

img = Image.open('image1.jpg', 'r').convert('rgba')

However, despite your wording, this is not what troubles you, and yes that the image should have just 2 colors and present 3 colors, with the "spurious" (254, 254, 254) showing up.然而,尽管你的措辞,这并不是你的困扰,是的,图像应该只有 2 个 colors 和 3 个 colors,并显示“虚假”(254、254、254)。

Again, this is due to the JPEG image format: it is a lossy format, meaning it does not preseve exact information on each pixel (it is not obliged to do so even if set at 100% quality): so, pixels at the boundaries of black and white will be of intermediate values, as the curves used for the internal data representation ramp up and down.同样,这是由于 JPEG 图像格式:它是一种有损格式,这意味着它不会保留每个像素的确切信息(即使设置为 100% 质量也没有义务这样做):因此,边界处的像素随着用于内部数据表示的曲线上升和下降,黑色和白色的值将是中间值。

If you can change your source file, use the "png" file format instead - it has a nice compression and will preserve the exact pixel values.如果您可以更改源文件,请改用“png”文件格式 - 它具有很好的压缩效果,并且会保留准确的像素值。 (converting your existing jpg files to png won't work: it will copy the (254,...) values) (将现有的 jpg 文件转换为 png 不起作用:它将复制 (254,...) 值)

Otherwise, after reading your image, apply a threshold filter - it will fix the values to just two levels.否则,在读取图像后,应用阈值过滤器 - 它会将值固定为两个级别。 Unfortunatelly, PIL offers no readymade, plain, threshold filter - but for this particular image, the "ModeFilter" will do:不幸的是,PIL 没有提供现成的、普通的、阈值过滤器——但是对于这个特定的图像,“ModeFilter”会做:

from PIL import Image, ImageFilter
img = Image.open('image1.jpg', 'r')
img = img.filter(ImageFilter.ModeFilter(5))
print(set(img.getdata()))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM