Reputation: 1
I want to find the center of yellow colour box which is in my image using opencv. It would be great if someone explain the code from scratch.
I tried to use numpy and find the coordinates. But i wasn't able to get the coordinates of all the yellow colour so that i can take avg nd find the center.
Upvotes: 0
Views: 895
Reputation: 136
It would be better if you could provide more information about the image/yellow color box.
Let's assume you have an image similar to the following image:
First, we have to read the image and convert it to HSV Space. HSV value represents the color closely to what we perceive. This article might be helpful for you.
image = cv2.imread("yellow_rectangle.jpg")
image_hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
Then we have to define what is yellow for us in HSV. Using cv2.inRange
we can get the mask for the image that falls within our defined boundary.
lower_yellow = (22,100,20)
upper_yellow = (35,255,255)
mask = cv2.inRange(image_hsv, lower_yellow, upper_yellow)
Then we may use the contour features to get the center of each yellow rectangle(or any shape) we have in the image.
cnts = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
for i, c in enumerate(cnts[0]):
# compute the center of the contour
M = cv2.moments(c)
cx = int(M["m10"] / M["m00"])
cy = int(M["m01"] / M["m00"])
print(f"Yellow Box {i} : cx={cx}, cx={cy}")
Upvotes: 1