Python,OpenCV和扫描图像上的矩形

时间:2017-06-13 13:47:50

标签: python opencv

image with rectangles

您好!掌握OpenCV,我遇到了一个问题:我找不到任何这些盒子然后剪切。请告诉我,使用什么过滤器和逻辑?

#!/usr/bin/env python
import cv2
import os

img_path = os.path.join('img', '1.jpg')
image = cv2.imread(img_path)

gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
gray = cv2.bilateralFilter(gray, 11, 17, 17)
edged = cv2.Canny(gray, 30, 200)

cv2.imshow('gray', gray)
cv2.waitKey(0)

cv2.imshow('edged', edged)
cv2.waitKey(0)


(_, cnts, _) = cv2.findContours(edged.copy(), cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

for c in cnts:
    peri = cv2.arcLength(c, True)
    approx = cv2.approxPolyDP(c, 0.02 * peri, True)

    if len(approx) == 4:
        cv2.drawContours(image, [approx], -1, (0, 255, 0), 3)


cv2.imshow('result', image)
cv2.waitKey(0)

此示例查找了大量垃圾和所有矩形(不仅仅是那些具有背景的矩形)

编辑: OpenСV复制矩形轮廓。我怎样才能切断重复?

2 个答案:

答案 0 :(得分:0)

您非常接近解决方案,在for c in cnts:中迭代轮廓时,您根据从轮廓近似的多边形边数过滤轮廓,您只需要为轮廓区域添加滤镜为了删除被检测的较小矩形,可以这样做:

for c in cnts:
    peri = cv2.arcLength(c, True)
    approx = cv2.approxPolyDP(c, 0.02 * peri, True)

    if len(approx) == 4 and cv2.contourArea(c) > 200:
        cv2.drawContours(image, [approx], -1, (0, 255, 0), 3)

答案 1 :(得分:0)

在应用Canny边缘检测之前,可以将自适应阈值用作预处理步骤,然后进行高斯模糊处理。

//c_file.c
#include "Python.h"
#include "cy_file.h"

struct Container container;
//...
Py_Initialize();
PyInit_cy_file();
// and call the cython function that fills up the numpy array
create_np_array(&container, start, stop, n_elements, n);
// shutdown of python interpreter
Py_Finalize();

// *** here comes the crash if the array longarray is 'too long' ***
container.np_array[0]

final image

您会看到没有分配没有背景的矩形