By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
443,907 Members | 2,039 Online
Bytes IT Community
+ Ask a Question
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

Thekid
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
  1. import PIL
  2.  
  3. im = image.open("mypic.jpg")
  4. im.getdata()
  5.  
Something like that maybe but not sure how to get it to count the red pixels.
Dec 8 '08 #1
Share this Question
Share on Google+
4 Replies


bvdet
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
  1. from PIL import Image
  2. import operator
  3.  
  4. img = Image.open('your_image')
  5.  
  6. # Count the pixels having RGB values in defined range
  7.  
  8. upper = (255,255,255)
  9. lower = (200,200,200)
  10.  
  11. print len([pixel for pixel in img.getdata() \
  12.            if False not in map(operator.lt,lower,pixel) \
  13.            and False not in map(operator.gt,upper,pixel)])
Dec 8 '08 #2

kudos
Expert 100+
P: 126
I would do it this way:
Expand|Select|Wrap|Line Numbers
  1. from PIL import Image
  2. im  = Image.new("RGBA",(512,512))
  3.  
  4. # create a funny picture... (with some red)
  5.  
  6. for i in range(512):
  7.  for j in range(512):
  8.   im.putpixel((j,i),(j^i)%256)
  9.  
  10. # calculate the number of "reds"
  11. cnr = 0
  12. for i in range(512):
  13.  for j in range(512):
  14.   if((im.getpixel((j,i)))[0] == 255):
  15.    cnr+=1
  16.  
  17. print "nr of red pixels : " + str(cnr)
  18. print "presentage of red pixels : " + str((cnr / (512.0*512.0))*100.0) + "%"
  19.  
  20. im.save("pattern.png")  # look at it, it looks funny
  21.  
Dec 9 '08 #3

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

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

Post your reply

Sign in to post your reply or Sign up for a free account.