从图像的特定部分提取色调值

Extracting HUE value from specific part of Image

我有一张具有某种结构(矩形)的图像,它们都近似为绿色。我使用这段代码在图像中找到了一些这样的对象,并在它们周围画了一个轮廓。它们的色调值会随时间变化。我需要添加一个代码来提取我们在上一步中检测到的每个计数器中新色调值的平均值,并将它们保存在一个新数组中。我想在一小时后找到面罩(或检测到的轮廓)内的平均色调值。感谢您的关注。 Real image

import cv2
import numpy as np
img = cv2.imread(r"C:\Users\Desktop\Image-1.PNG")
hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
lower_range = np.array([75, 50, 50])
upper_range = np.array([165, 200, 255])
mask = cv2.inRange(hsv, lower_range, upper_range)

(cnt, hierarchy) = cv2.findContours(mask.copy(),cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)
N2=0
for cont in cnt:
    if cv2.contourArea(cont) > 200:
     # NewVariable[N2,:]=cnt[cont,:]  this line do not work
       N2=N2+1
print("Number of section : ", N2)

rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
count=cv2.drawContours(rgb, cnt, -2, (100, 0, 255), 2)
cv2.imshow('count',count)
cv2.waitKey(0)
cv2.destroyAllWindows()

你做了什么调试?你列出区域了吗?

修复缩进、轮廓和绘图命令后,以下内容对我有用。我还必须将您的区域阈值降低到 160 才能获得所有区域。

输入:

import cv2
import numpy as np
img = cv2.imread("Image-1.PNG")
hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
hue = hsv[:,:,0]
lower_range = np.array([75, 50, 50])
upper_range = np.array([165, 200, 255])
thresh = cv2.inRange(hsv, lower_range, upper_range)

contours = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
contours = contours[0] if len(contours) == 2 else contours[1]
N2=0
count = img.copy()
for cnt in contours:
    area = cv2.contourArea(cnt)
    if area > 160:
        cv2.drawContours(count, [cnt], 0, (100, 0, 255), 2)
        mask = np.zeros_like(thresh, dtype=np.uint8)
        cv2.drawContours(mask, [cnt], 0, (255,255,255), -1)
        ave_hue = np.mean(hue[np.where(mask==255)])
        print("average hue:", ave_hue, "area:", area)
        N2=N2+1
print("Number of section : ", N2)

cv2.imwrite('Image-1-contours.PNG', count)

cv2.imshow('thresh',thresh)
cv2.imshow('hsv',hsv)
cv2.imshow('count',count)
cv2.waitKey(0)
cv2.destroyAllWindows()Result:

清单:

average hue: 92.6030534351145 area: 227.0
average hue: 92.32921810699588 area: 209.0
average hue: 92.48648648648648 area: 223.5
average hue: 93.0765306122449 area: 165.0
average hue: 92.99335548172758 area: 261.0
average hue: 92.44375 area: 280.0
average hue: 92.94326241134752 area: 244.0
average hue: 92.70454545454545 area: 267.0
average hue: 92.73374613003097 area: 282.5
average hue: 92.90847457627119 area: 255.0
average hue: 93.23026315789474 area: 266.0
average hue: 90.79323308270676 area: 231.0
average hue: 90.33333333333333 area: 253.0
average hue: 90.67405063291139 area: 276.5
average hue: 90.24846625766871 area: 285.0
average hue: 91.09375 area: 278.5
average hue: 90.29577464788733 area: 245.5
average hue: 90.89389067524115 area: 269.5
average hue: 90.12539184952978 area: 278.0
average hue: 90.67202572347267 area: 270.0
average hue: 90.28321678321679 area: 247.0
average hue: 89.54181818181819 area: 239.5
average hue: 89.75565610859728 area: 185.0

Number of section :  23