Count pixels of color in JES (Jython)

775 views Asked by At

I am trying to pull the overall pixel count of the R, G, B, Black, & White values in a premade picture. This picture has 100 Red, 100 Green, 100 Blue, 100 Black, and 100 white.

I have started with my code, but for some reason it seems as if my code is only counting 1 pixel.. Jython has predefined 16 colors, so I am using the red, blue, green datatypes.

Here is what I have so far:

def main():
 file = pickAFile( )
 pic = makePicture( file )

  pxRed = 0
  pxGreen = 0
  pxBlue = 0
  numR = 0
  numG = 0
  numB = 0

 printNow("Now let's count some pixels...")

 for px in getPixels( pic ):
   r = getRed(px)
   g = getGreen(px)
   b = getBlue(px)
   If px is (255,0,0): #error here
     numR += 1
     printNow("You have " + numR + " red pixels")
 show(pic)

unsure why this is not working..

1

There are 1 answers

2
Igl3 On

You don't need to get the colors separately. You can go with the getColor(px)-function.

Furthermore there is no function printNow(str) in python. So as long as this function is not part of any package you use, you need to use print(str)

The function getColor returns an Object like Color(255,0,0) to compare this, you can't just compare against a Tuple but want to use the distance function from JES. Therefore you need to make a Color object for comparison like red = makeColor(255,0,0) and compare against this. The possible output from the distance function ranges from 0 (exact same color) to ~441.7 (black compared with white).

So try it like this:

red = makeColor(255,0,0)
green = makeColor(0,255,0)
blue = makeColor(0,0,255)

for px in getPixels( pic ):
   color = getColor(px)
   if distance(color, red) == 0:
       numR += 1
   elif distance(color, green) == 0:
       numG += 1
   elif distance(color, blue) == 0:
       numB += 1

print("You have " + numR + " red pixels")
print("You have " + numG + " green pixels")
print("You have " + numB + " blue pixels")

I guessed you need the number in total after counting. If you want to output the number while iterating, just put the print back in the loop.