在OpenCV Python

时间:2016-10-23 14:20:12

标签: python python-2.7 opencv

我有一个代码,用于在视频帧上应用滤镜后识别轮廓。现在在我的情况下,我得到3个轮廓,我通过在它们周围绘制矩形来显示它们,我想要做的是围绕所有这3个轮廓矩形绘制一个矩形。就像它将是一个更大的矩形,包含3个检测到的矩形。 这是我在轮廓周围检测和绘制矩形的简单代码。

im2, contours, hierarchy = cv2.findContours(canny_img,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)

try: hierarchy = hierarchy[0]
except: hierarchy = []

# computes the bounding box for the contour, and draws it on the frame,
for contour, hier in zip(contours, hierarchy):
    (x,y,w,h) = cv2.boundingRect(contour)
    if w > 80 and h > 80:
            cv2.rectangle(frame, (x,y), (x+w,y+h), (255, 0, 0), 2)

cv2.imshow('Motion Detector',frame)

3 个答案:

答案 0 :(得分:8)

也许尝试这样的事情:

im2, contours, hierarchy = cv2.findContours(canny_img,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)

try: hierarchy = hierarchy[0]
except: hierarchy = []

height, width, _ = canny_img.shape
min_x, min_y = width, height
max_x = max_y = 0

# computes the bounding box for the contour, and draws it on the frame,
for contour, hier in zip(contours, hierarchy):
    (x,y,w,h) = cv2.boundingRect(contour)
    min_x, max_x = min(x, min_x), max(x+w, max_x)
    min_y, max_y = min(y, min_y), max(y+h, max_y)
    if w > 80 and h > 80:
        cv2.rectangle(frame, (x,y), (x+w,y+h), (255, 0, 0), 2)

if max_x - min_x > 0 and max_y - min_y > 0:
    cv2.rectangle(frame, (min_x, min_y), (max_x, max_y), (255, 0, 0), 2)

基本上你想要跟踪最小的x和y坐标是什么,以及最大的x和y坐标(包括宽度和高度)是什么,然后只绘制一个带有这些坐标的矩形。

答案 1 :(得分:1)

使用numpy:

boxes = []
for c in cnts:
    (x, y, w, h) = cv2.boundingRect(c)
    boxes.append([x,y, x+w,y+h])

boxes = np.asarray(boxes)
# need an extra "min/max" for contours outside the frame
left = np.min(boxes[:,0])
top = np.min(boxes[:,1])
right = np.max(boxes[:,2])
bottom = np.max(boxes[:,3])

cv2.rectangle(frame, (left,top), (right,bottom), (255, 0, 0), 2)

答案 2 :(得分:0)

如果要对二进制图像中的所有内容进行装箱,则可以从所有非零值生成点,并在其上应用算法。如下所示:

    points = cv2.findNonZero(thresholdImage)
    rect = cv2.minAreaRect(points)