如何用python得到圆圈内的平均RGB值?

How to get the average RGB value inside circle with python?

我需要有关此代码的帮助。我只想获取圆的RGB值。

如何return圆形的RGB值?

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)

这是 Python/OpenCV 中的一种方法。

从HoughCircles获取圆圈后,将圆圈画成黑底白底作为遮罩。然后将 cv2.mean() 与掩码一起使用,以在找到的圆圈内获取输入图像内的通道颜色。

输入:

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()

找到圈子:

蒙版图片:

数据:

circles: [[[596.5 516.5 367.1]]]
average circle color: (1.1791196817751013, 254.96112948094645, 254.88615376615763)