Advertisement
acclivity

pyChangeBalloonColour

Nov 24th, 2021
858
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.98 KB | None | 0 0
  1. # Given a JPG image of coloured balloons, find the yellow balloon and change it to black
  2. import cv2
  3.  
  4. img = cv2.imread("Balloons.jpg")
  5. cv2.imshow("img", img)      # Show the original image
  6. cv2.waitKey(0)              # Wait for a key press
  7.  
  8. yellow = (0, 255, 255)       # Colour code of Yellow, in Blue, Green, Red sequence (as per CV2)
  9.  
  10. for y, line in enumerate(img):          # y is line counter
  11.     for x, bgr in enumerate(line):      # x is horizontal pixel counter
  12.         # find a pixel that is yellowish by computing a numerical difference from yellow
  13.         diffred = abs(yellow[2] - bgr[2])
  14.         diffgrn = abs(yellow[1] - bgr[1])
  15.         diffblu = abs(yellow[0] - bgr[0])
  16.         diff = diffred + diffgrn + diffblu
  17.         if diff < 180:                   # 180 was found empirically, to be a value that worked well
  18.             img[y][x] = (0, 0, 0)        # Set this pixel to black
  19.  
  20. cv2.imshow("img", img)                  # Show the modified image
  21. cv2.waitKey(0)                          # Wait for a key press
  22.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement