Hi! I’m trying to work with detecting the color red by using OpenCV and masking. However, I seem to run into a problem. My code sometimes works and sometimes doesn’t work.
In some pictures, I get the perfect result.
However, when I try it with this one the detection is very bad even when I try to adjust the image’s gamma to make it lighter. Even working with the RGB values, I tried lowering the mask to 0,10,10 but still it doesn’t detect the red
Here’s my code:
import cv2
from matplotlib import image
import numpy as np
def adjust_gamma(image, gamma=1.0):
invGamma = 1.0 / gamma
table = np.array([((i / 255.0) ** invGamma) * 255
for i in np.arange(0, 256)]).astype("uint8")
return cv2.LUT(image, table)
path = r'C:\Users\Admin\Desktop\Researcher\VisualServoing\MovementCalibration\Height2.5Meters\opencv_2.5_86.png' #location of the image
image = cv2.imread(path, 1)
img = image
gamma = 1.0
img = adjust_gamma(img,gamma=gamma)
img_hsv=cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
# lower mask (0-10)
lower_red = np.array([0,50,50]) # 0,50,50 original
upper_red = np.array([10,255,255])
mask0 = cv2.inRange(img_hsv, lower_red, upper_red)
# upper mask (170-180)
lower_red = np.array([160,100,100]) # 170,50,50 original
upper_red = np.array([180,255,255])
mask1 = cv2.inRange(img_hsv, lower_red, upper_red)
mask = mask0+mask1
output_img = img.copy()
output_img[mask==0] = 0
output_img[mask!=0] = 255
pixels = np.where(mask==[0]) #Pixels for the Undetected
pixels2 =np.where(mask==[255]) #Pixels for the Detected
print("Undetected Pixels", len(pixels[0]))
print("Pixel Area:", len(pixels2[0]))
cv2.imshow("Orig Image", img)
cv2.imshow("Detected Red",output_img)
cv2.waitKey(0)