Jeff Sun
Jeff Sun

Reputation: 71

im.getcolors() returns None

I am using a simple code to compare an image to a desktop screenshot through the function getcolors() from PIL. When I open an image, it works:

im = Image.open('sprites\Bowser\BowserOriginal.png')
current_sprite = im.getcolors() 
print current_sprite

However, using both pyautogui.screenshot() and ImageGrab.grab() for the screenshot, my code returns none. I have tried using the RGB conversion as shown here: Cannot use im.getcolors.

Additionally, even when I save a screenshot to a .png, it STILL returns none.

i = pyautogui.screenshot('screenshot.png')
f = Image.open('screenshot.png')
im = f.convert('RGB')
search_image = im.getcolors()
print search_image

First time posting, help is much appreciated.

Upvotes: 7

Views: 6521

Answers (2)

Lotem Nadir
Lotem Nadir

Reputation: 472

Pretty old question but for those who sees this now:

Image.getcolors() takes as a parameter "maxcolors – Maximum number of colors." (from the docs here).

The maximum number of colors an image can have, equals to the number of pixels it contains. For example, an image of 50*60px will have maximum 3,000 colors.

To translate it into code, try this:

# Open the image.
img = Image.open("test.jpg")
# Set the maxcolors number to the image's pixels number.
colors = img.getcolors(img.size[0]*img.size[1])

Upvotes: 17

Sturm
Sturm

Reputation: 4285

If you'd check the docs, getcolors returns None if the number of colors in the image is greater than the default parameter, which is set to 256.

Upvotes: 7

Related Questions