我一直在尝试寻找框架上棕色区域的轮廓。
我试图在for
循环中找到这些轮廓。
for c in cntrs:
area = cv2.contourArea(c)
if area > 1200: # i obtanied threshold with trial end error
x, y, w, h = cv2.boundingRect(c) #find coordinates of brown area
roi2 = results[y:y + h, x:x + w] #copy these parts to the another image
但是我只能看到一个轮廓
我不明白为什么我只看到一个轮廓。因为当我打印一些阈值轮廓时,我会看到2
这是我尝试过的
import cv2
import numpy as np
cv2.destroyAllWindows()
capture = cv2.VideoCapture(0) ##masaustunde 1, laptopta 0
def nothing(x):
pass
roi = cv2.imread('savedImage.jpg')
cv2.imshow('input', roi)
hsv = cv2.cvtColor(roi, cv2.COLOR_RGB2HSV)
lower_green = np.array([0, 0, 0])
upper_green = np.array([40, 255, 255])
mask = cv2.inRange(hsv, lower_green, upper_green)
mask_inv = cv2.bitwise_not(mask)
fg = cv2.bitwise_and(roi, roi, mask=mask_inv)
gray = cv2.cvtColor(fg, cv2.COLOR_BGR2GRAY)
gray = cv2.cvtColor(fg, cv2.COLOR_BGR2GRAY)
thresh = cv2.threshold(gray, 32, 255, 0)[1]
cntrs = cv2.findContours(thresh, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
cntrs = cntrs[0] if len(cntrs) == 2 else cntrs[1]
area_thresh = 0
syc = 0
results = fg.copy()
for c in cntrs:
area = cv2.contourArea(c)
if area > 1200: #esige dikkat
syc = syc + 1
x, y, w, h = cv2.boundingRect(c)
roi2 = results[y:y + h, x:x + w]
cv2.imshow('roi2', roi2)
cv2.waitKey(0)
capture.release() # release the camera from video capture
cv2.destroyAllWindows()
您正在循环中覆盖结果(roi2),而无需等待查看每个结果。您必须将waitKey()放入循环中。
正如我之前所说,您的区域阈值太高。
我还选择了更好的上下限。 (我保存了hsv文件,然后在GUI工具中测量了它的值)
这在Python / OpenCV中对我有用。显示每个roi2后,按返回键可继续进行下一个。
import cv2
import numpy as np
roi = cv2.imread('green_areas.jpg')
#cv2.imshow('input', roi)
hsv = cv2.cvtColor(roi, cv2.COLOR_RGB2HSV)
#cv2.imshow('hsv', hsv)
lower_green = np.array([30, 30, 30])
upper_green = np.array([60, 140, 100])
mask = cv2.inRange(hsv, lower_green, upper_green)
#cv2.imshow('mask', mask)
mask_inv = cv2.bitwise_not(mask)
fg = cv2.bitwise_and(roi, roi, mask=mask_inv)
#cv2.imshow('fg', fg)
gray = cv2.cvtColor(fg, cv2.COLOR_BGR2GRAY)
thresh = cv2.threshold(gray, 32, 255, 0)[1]
#cv2.imshow('thresh', thresh)
cntrs = cv2.findContours(thresh, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
cntrs = cntrs[0] if len(cntrs) == 2 else cntrs[1]
area_thresh = 0
syc = 0
results = fg.copy()
for c in cntrs:
area = cv2.contourArea(c)
if area > 500: #esige dikkat
syc = syc + 1
x, y, w, h = cv2.boundingRect(c)
roi2 = results[y:y + h, x:x + w]
cv2.imshow('roi2', roi2)
cv2.waitKey(0)
cv2.destroyAllWindows()