Today, we are going to talk about color detection in opencv using python. As you know RGB format is a very regular color format these days. But there are other image color spaces that each one has their own advantages and disadvantages. In this situation , HSV color space would be very useful because of showing the colors. For more information check wikipedia.
Now, we are talking about the code. First of all we have to read the image using imread function. Then changing the color space using cvtColor function and after all some noise reduction using erosion and dilate functions.
import cv2 import numpy as np from google.colab.patches import cv2_imshow img = cv2.imread("/content/JSjbB.png") cv2_imshow(img) img_output = img cv2_imshow(img_output) frame_hsv = cv2.cvtColor(img_output, cv2.COLOR_BGR2HSV) frame_hsv_blur = cv2.GaussianBlur(frame_hsv, (7, 7), 0) #print(frame_hsv_blur) lower_values = np.array([130, 100,0]) upper_values = np.array([170,255, 255]) mask = cv2.inRange(frame_hsv_blur, lower_values, upper_values) cv2_imshow(mask) kernel = np.ones((5,5),np.uint8) erosion = cv2.erode(mask,kernel,iterations = 3) dilation = cv2.dilate(erosion,kernel,iterations = 3) cv2_imshow(dilation)
The result will be some thing like this.
And this would be tha result before erosion and dilate.