简体   繁体   中英

Python giving AttributeError: 'PngImageFile' object has no attribute 'read' with Pillow

So I'm working on a small research project and a part of this involves me having to get the pixel coordinates of a image that correspond to a certain color. A sample image (named testpic.png) is shown here:

在此输入图像描述

What I am trying to do is determine the locations of all the dots which are the color turquoise. However, the following code (adapted from Find pixels with given RGB colors ) gives me the error: "AttributeError: 'PngImageFile' object has no attribute 'read'" and I'm not sure what's going on.

from PIL import Image
myImage = Image.open("testpic.png")

def find_turq_pixels(image_name):

    # Set the value you want for these variables
    r_min = 0
    r_max = 65
    g_min = 220
    g_max = 255
    b_min = 220
    b_max = 255

    turq_pixels = set()

    img = Image.open(image_name)
    rgb = img.convert('rgb')
    for x in range(img.size[0]):
        for y in range(img.size[1]):
            r, g, b = rgb.getpixel((x, y))
            if r >= r_min and r <= r_max and b >= b_min and b <= b_max and g >= g_min and g <= g_max:
                turq_pixels.add((x,y))

    return turq_pixels

print(find_turq_pixels(myImage))

I'm currently using Python 3.7, and if I installed everything correctly, python says "PIL.PILLOW_VERSION" is running 5.4.1. The python file and the image file are in the same folder as well in case that was causing an error. This is my first time using Python in years so apologies in advance if I'm being very stupid about this as I've already forgotten a ton about programming, but if anyone could help me fix this, it would be much greatly appreciated! Thanks :)

Just a couple of little errors...


Delete this line:

myImage = Image.open("testpic.png")

Change this line:

print(find_turq_pixels(myImage))

to

print(find_turq_pixels("testpic.png"))

Change this line:

rgb = img.convert('rgb')

to:

rgb = img.convert('RGB')

Then it all works.

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