简体   繁体   中英

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.

from PIL import Image

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

img_data = list(img.getdata())

print(img_data)

image1.jpg:

图像1.jpg

Instead of [(0,0,0), (255,255,255)] I get [(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.
this is why code gets confused between the black and white color border and give on more output

A JPG image never has transparency ("alpha") data: it is an opaque image format. If you want the transparent channel information ("a" in "rgba", you will have to convert it first with:

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.

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.

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. (converting your existing jpg files to png won't work: it will copy the (254,...) values)

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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