pythonjythonjes

Code ignoring my if statement? Unsure why this code isn't working


So I am trying to invert the black and white colours in a QR Code.
My code works for images that are already strictly white and black: RBG values 0,0,0 and 255,255,255.
But it is failing to work for another image that has slightly off white and black: 21,21,21 and 243,243,243.
Running my code on the slightly off image will turn the entire thing strictly white.
My code takes the value of each channel and if any one of them exceeds 140, it will be turned white. Why is a slightly off black, 21,21,21 being turned white?

def invert(smallPicture):

for pixel in getPixels(smallPicture):
  valueRed = getRed(pixel)
  valueGreen = getGreen(pixel)
  valueBlue = getBlue(pixel)

  if (valueRed or valueBlue or valueGreen > 140):
     setColor(pixel, white)
  else:
     setColor(pixel, black)

return smallPicture

I am using Jython in JES 4.3.

Thanks!


Solution

  • In your code, Python was checking if valueRed evaluates to True or if valueGreen evaluates to True or if valueBlue is greater than 140. Python does not compare each variable in the if conditional to 140: You need to rewrite each comparison separated by or statements instead. Than Python will run each comparison and evaluate to either True or False, dependent on if the color value meets the comparison or not.

    You'll want to replace your conditional statements with the following:

    if (valueRed > 140 or valueBlue > 140 or valueGreen > 140):
        setCoor(pixel, white)
    else:
        setColor(pixel, black)