Counting pixels in image

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Thekid
    New Member
    • Feb 2007
    • 145

    Counting pixels in image

    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.

    Code:
    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.
  • bvdet
    Recognized Expert Specialist
    • Oct 2006
    • 2851

    #2
    Let us assume a pixel is red if each RGB value is in excess of 200.
    Code:
    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)])

    Comment

    • kudos
      Recognized Expert New Member
      • Jul 2006
      • 127

      #3
      I would do it this way:
      Code:
      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)))[0] == 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

      Comment

      • bvdet
        Recognized Expert Specialist
        • Oct 2006
        • 2851

        #4
        That's cool kudos. Thanks for sharing.

        Comment

        • bvdet
          Recognized Expert Specialist
          • Oct 2006
          • 2851

          #5
          I did a red count on my avatar.
          Code:
          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)
          >>>

          Comment

          Working...