您可以通过首先创建与输入图像尺寸相同且像素值设置为零的新图像来创建mask。
然后使用像素值255将轮廓绘制到此图像上。生成的图像可用作mask。
mask = np.zeros(frame.shape, np.uint8)cv2.drawContours(mask, c, -1, 255, -1)然后,mask可以用作cv.mean之类的参数
mean = cv.mean(frame, mask=mask)只需提醒一句,RGB颜色的平均值并不总是有意义的。也许尝试转换为HSV色彩空间,并仅使用H通道检测对象的颜色。
图像上的解决方案
1)找到轮廓(在这种情况下是矩形,非矩形的轮廓更难制作)
2)找到轮廓的坐标
3)从轮廓切割图像
4)对各个通道求和并将其除以其中的像素数(或平均函数)
import numpy as npimport cv2img = cv2.imread('my_image.jpg',1)cp = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)ret,thresh = cv2.threshold(cp,150,255,0)cv2.imshow('img',thresh) cv2.waitKey(0)im2,contours,hierarchy = cv2.findContours(thresh.astype(np.uint8), 1, 2)cnts = contoursfor cnt in cnts:
if cv2.contourArea(cnt) >800: # filter small contours
x,y,w,h = cv2.boundingRect(cnt) # offsets - with this you get 'mask'
cv2.rectangle(img,(x,y),(x+w,y+h),(0,255,0),2)
cv2.imshow('cutted contour',img[y:y+h,x:x+w])
print('Average color (BGR): ',np.array(cv2.mean(img[y:y+h,x:x+w])).astype(np.uint8))
cv2.waitKey(0)
cv2.imshow('img',img) cv2.waitKey(0)cv2.destroyAllWindows()要消除噪音,您可以只取轮廓的中心,并采用较小的矩形进行检查。