443,907 Members | 2,039 Online Need help? Post your question and get tips & solutions from a community of 443,907 IT Pros & Developers. It's quick & easy.

# Counting pixels in image

 100+ P: 145 Hi, I know I need to use PIL, but how would I count all of the red pixels in a given image? The image is simply a vertical red line on a black background. Expand|Select|Wrap|Line Numbers import PIL   im = image.open("mypic.jpg") im.getdata()   Something like that maybe but not sure how to get it to count the red pixels. Dec 8 '08 #1
4 Replies

 Expert Mod 2.5K+ P: 2,851 Let us assume a pixel is red if each RGB value is in excess of 200. Expand|Select|Wrap|Line Numbers from PIL import Image import operator   img = Image.open('your_image')   # Count the pixels having RGB values in defined range   upper = (255,255,255) lower = (200,200,200)   print len([pixel for pixel in img.getdata() \            if False not in map(operator.lt,lower,pixel) \            and False not in map(operator.gt,upper,pixel)]) Dec 8 '08 #2

 Expert 100+ P: 126 I would do it this way: Expand|Select|Wrap|Line Numbers from PIL import Image im  = Image.new("RGBA",(512,512))   # create a funny picture... (with some red)   for i in range(512):  for j in range(512):   im.putpixel((j,i),(j^i)%256)   # calculate the number of "reds" cnr = 0 for i in range(512):  for j in range(512):   if((im.getpixel((j,i))) == 255):    cnr+=1   print "nr of red pixels : " + str(cnr) print "presentage of red pixels : " + str((cnr / (512.0*512.0))*100.0) + "%"   im.save("pattern.png")  # look at it, it looks funny   Dec 9 '08 #3

 Expert Mod 2.5K+ P: 2,851 That's cool kudos. Thanks for sharing. Dec 9 '08 #4

 Expert Mod 2.5K+ P: 2,851 I did a red count on my avatar. Expand|Select|Wrap|Line Numbers from PIL import Image import operator   img = Image.open('image.png')   upper = (256,40,40) lower = (190,0,0)   print '\n'.join([str(pixel) for pixel in img.getdata() \                  if False not in map(operator.lt,lower,pixel) \                  and False not in map(operator.gt,upper,pixel)])   # Output: >>> (210, 13, 7) (202, 21, 7) (201, 9, 9) (198, 11, 11) (196, 26, 6) (198, 15, 15) >>>  Dec 11 '08 #5 