繁体   English   中英

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

[英]Python, OpenCV and rectangles on scanned image

带有矩形的图像

你好! 掌握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复制矩形轮廓。 我怎样才能切断重复?

你非常接近解决方案,同时迭代for c in cnts:for c in cnts:的轮廓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)

在应用canny边缘检测之前,您可以使用自适应阈值处理作为预处理步骤,然后使用高斯模糊。

import cv2
import numpy as np

img = cv2.imread('image with boxes.jpg')
blur = cv2.GaussianBlur(img,(7,7),0)
gray = cv2.cvtColor(blur, cv2.COLOR_BGR2GRAY)
mask = cv2.adaptiveThreshold(gray,255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C,cv2.THRESH_BINARY,11,2)
canny = cv2.Canny(mask, 30, 200)
(_, cnts, _) = cv2.findContours(canny, cv2.RETR_EXTERNAL, 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(img, [approx], -1, (0, 0, 255), 1)

cv2.imshow('result', img)
cv2.waitKey(0)
cv2.destroyAllWindows()

最终形象

如您所见,没有分配没有任何背景的矩形

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM