Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how can i get no of red pixels and no of black pixels in PIL image

Tags:

from PIL import ImageGrab
pil_img=ImageGrab.grab([0,0,1000,1000])

Now I want to get no of red pixels and no of black pixels in two separate variables.So how should I proceed on pil_imgThe image look likes this

like image 923
Nimish Bansal Avatar asked Sep 13 '17 17:09

Nimish Bansal


2 Answers

It's much faster if you don't write a loop yourself over all the pixels.

import os.path
from collections import Counter

from PIL import Image

path_to_file = os.path.join('..', '..', 'img', '9BLW9.jpg')

# Count the number of occurrences per pixel value for the entire image
img = Image.open(path_to_file)
pixels = img.getdata()
print(Counter(pixels))

# Count the number of occurrences per pixel value for a subimage in the image
img = img.crop((100, 100, 200, 200))
pixels = img.getdata()
print(Counter(pixels))

With as a result:

Counter({(248, 8, 9): 1002251, (0, 0, 0): 735408, (248, 8, 11): 8700, (245, 9, 9): 7200, ...)
Counter({(0, 0, 0): 5992, (248, 8, 9): 1639, (3, 0, 0): 33, (0, 6, 0): 23, ...)

The fact that you have more than two pixel values is due to JPG artefacts. You could write some custom logic to see if a pixel resembles more black or red and count them as those as well.

like image 156
physicalattraction Avatar answered Oct 11 '22 13:10

physicalattraction


Use pil_img.getpixel((x, y)), or pil_img[x, y].

like image 29
J_H Avatar answered Oct 11 '22 12:10

J_H