I need help with this code. I want to get the RGB value of the circle only.
How do I return the RGB value of the circle?
prevCircle = None
dist = lambda x1,y1,x2,y2 : (x1-x2)**2 (y1-y2)**2
while True:
(grabbed, frame) = videoCapture.read()
grayFrame = cv.cvtColor(frame,cv.COLOR_BGR2GRAY)
blurFrame = cv.GaussianBlur(grayFrame,(11,11),0)
height, width, _ = frame.shape
circles = cv.HoughCircles(blurFrame ,cv.HOUGH_GRADIENT,1.2,50,param1=100,param2=30,minRadius=75,maxRadius=400)
if circles is not None:
circles = np.uint16(np.around(circles))
chosen=None
for i in circles[0 ,:]:
if chosen is None: chosen =i
if prevCircle is not None:
if dist(chosen[0],chosen[1],prevCircle[0],prevCircle[1]) <= dist(i[0],i[1],prevCircle[0],prevCircle[1]):chosen = i
cv.circle(frame,(chosen[0],chosen[1]),1,(0,100,100),3)
cv.circle(frame,(chosen[0],chosen[1]),chosen[2],(0,0,0),3)
prevCirlce = chosen
cv.imshow("Camera", frame)
CodePudding user response:
Here is one way to do that in Python/OpenCV.
After getting the circle from HoughCircles, draw the circle as white filled on a black background as a mask. Then use cv2.mean() with the mask to get the channel colors inside the input image within the found circle.
Input:
import cv2
import numpy as np
# Read image
img = cv2.imread('yellow_circle.jpg')
hh, ww = img.shape[:2]
# Convert to grayscale
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# get Hough circles
min_dist = int(ww/10)
circles = cv2.HoughCircles(gray, cv2.HOUGH_GRADIENT, 1, minDist=min_dist, param1=150, param2=20, minRadius=0, maxRadius=0)
print("circles:", circles)
# draw circles
img_circle = img.copy()
mask = np.zeros_like(gray)
for circle in circles[0]:
# draw the circle in the output image, then draw a rectangle
# corresponding to the center of the circle
(x,y,r) = circle
x = int(x)
y = int(y)
r = int(r)
cv2.circle(img_circle, (x, y), r, (0, 0, 255), 2)
cv2.circle(mask, (x, y), r, 255, -1)
# get average color with mask
ave_color = cv2.mean(img, mask=mask)[:3]
print("average circle color:", ave_color)
# save results
cv2.imwrite('yellow_circle_circle.jpg', img_circle)
cv2.imwrite('yellow_circle_mask.jpg', mask)
# show images
cv2.imshow('circle', img_circle)
cv2.imshow('mask', mask)
cv2.waitKey(0)
cv2.destroyAllWindows()
Circle Found:
Mask Image:
Data:
circles: [[[596.5 516.5 367.1]]]
average circle color: (1.1791196817751013, 254.96112948094645, 254.88615376615763)