My code is detecting colors other than what I am looking for

64 Views Asked by At

I am trying to make a Python bot for a Roblox game where you hit spacebar whenever a white bar hovers over a yellow bar. However I am having a problem detecting the right color pixels. Whenever I try to check for pixels with a RGB value of 255,255,0 it gets colors other then yellow like light green and white.

import random
import cv2
import keyboard
import numpy as np

game_img = cv2.imread('test.png', cv2.IMREAD_UNCHANGED)
dodge_img = cv2.imread('dodge8.png', cv2.IMREAD_UNCHANGED)

print(type(game_img))
print(game_img.shape)

for y in range(0,game_img.shape[0]):
    for x in range(0,game_img.shape[1]):
        if np.any(game_img[y][x] == [255,255,0]):
            game_img[y][x] = [random.randint(0,255),random.randint(0,255),random.randint(0,255)]

cv2.imshow("this", game_img)
cv2.waitKey(0)

Original Image:

Original Image

Image After "yellow" pixels were changed:

Image After "yellow" pixels were changed

1

There are 1 best solutions below

0
Cris Luengo On

np.any(game_img[y][x] == [255,255,0]) Will be true if either the blue component is 255, or the green component is 254, or the red component is yellow (OpenCV uses BGR order for RGB by default).

If you want to detect pure yellow, (0,255,255) in BGR, then you need to ensure all three color components match, not any one component matches. The condition should be np.all(game_img[y][x] == [0,255,255])