我有一个脚本,它生成一个HSV掩模,并检测一些基于面积的矩形:

我已经包含了一些区域限制,我的目标是只检测底部最低的框(上图中红色的那个)。
这是我的检测代码部分,我想在其中添加新函数,能够只保留一个盒子:
cnts, hierarchy = cv2.findContours(mask_merged.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
for c in cnts:
p_box = round((cv2.contourArea(c)/image_area)*100,1)
print('p_box'+str(p_box))
if (p_box <= 2.2) and (p_box >= 0.7):
(x, y, w, h) = cv2.boundingRect(c)
print(x,y,w,h)
print(cv2.contourArea(c))
cv2.imshow('frame_ocr_zone',image_src[y:y+h, x:x+w])
cv2.rectangle(image_src, (x,y), (x+w,y+h), (0, 255, 0), 2)
## BEGIN - draw rotated rectangle
rect = cv2.minAreaRect(c)
box = cv2.boxPoints(rect)
box = np.int0(box)
cv2.drawContours(image_src,[box],0,(123, 245, 66),5)
font = cv2.FONT_HERSHEY_SIMPLEX
color = (157,252,3)
thickness = 2
fontScale = 1
org = (x-50,y-20)我在考虑修改这里的函数(排序):
def sort_contours(cnts, method="left-to-right"):
# initialize the reverse flag and sort index
reverse = False
i = 0
# handle if we need to sort in reverse
if method == "right-to-left" or method == "bottom-to-top":
reverse = True
# handle if we are sorting against the y-coordinate rather than
# the x-coordinate of the bounding box
if method == "top-to-bottom" or method == "bottom-to-top":
i = 1
# construct the list of bounding boxes and sort them from top to
# bottom
boundingBoxes = [cv2.boundingRect(c) for c in cnts]
(cnts, boundingBoxes) = zip(*sorted(zip(cnts, boundingBoxes),
key=lambda b:b[1][i], reverse=reverse))
# return the list of sorted contours and bounding boxes
return (cnts, boundingBoxes)但我不能想出只检索1个盒子(从上到下排序,并保留最大的c?)
提前感谢您的任何建议。
我确实在这里找到了这篇文章:Python opencv sorting contours
这段代码实际上能够做到这一点:
def get_contour_precedence(contour, cols):
tolerance_factor = 10
origin = cv2.boundingRect(contour)
return ((origin[1] // tolerance_factor) * tolerance_factor) * cols + origin[0]
im, contours, h = cv2.findContours(img.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
contours.sort(key=lambda x:get_contour_precedence(x, img.shape[1]))发布于 2020-10-25 00:31:33
def get_contour_precedence(contour, cols):
tolerance_factor = 10
origin = cv2.boundingRect(contour)
return ((origin[1] // tolerance_factor) * tolerance_factor) * cols + origin[0]
im, contours, h = cv2.findContours(img.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
contours.sort(key=lambda x:get_contour_precedence(x, img.shape[1]))发布于 2020-09-26 22:43:17
首先,我们定义初始X和初始Y为0,我们没有轮廓线,所以没有轮廓线,然后我们在轮廓线上循环检查x坐标和y坐标,因为底角的x和y都比其他坐标大
intial_x,intial_y = 0,0
my_cnt =None
for c in cnts:
(x, y, w, h) = cv2.boundingRect(c)
if x>intial_x and y>intial_y:
my_cnt = c
intial_x = x+w
intial_y =y+h
else:
continuehttps://stackoverflow.com/questions/64076884
复制相似问题