简体   繁体   中英

Analyzing pixel RGB values with PIL

I'm working on a project where I need to find the RGB values of each pixel in a picture. How could I do this using PIL? I know that Pillow is better, but since I only need to do this one thing I thought I could just use PIL. If this won't work as well please tell me.

from PIL import Image
img = Image.open("filename.png")
pixels = img.load()

#get the B value of the pixel at x=23, y=42
print pixels[23, 42][2]

The previous answer is a good solution but just suggesting another way which is one line:

from scipy import misc;

imgData = misc.imread('./image.png');

You can then easily get the colors at every pixels you need.

Kevin got it pretty much spot on, you can also use getdata() to return a list of tuples.

I may have got this totally wrong, but load() might work better if you need particular pixels, and getdata() if you need all of them. Also, it's a good idea to convert to RGB if it's just a normal image, I've had errors before by not doing that.

image = Image.open('filename').convert('RGB')
width, height = image.size

#Get pixels in a list of tuples
pixels = image_input.getdata()

#If you need a flat list containing all the colours
bytes = [j for i in pixels for j in i]

If you needed to do stuff to the pixels and rebuild the image after, that's where the image size comes in useful.

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