繁体   English   中英

Opencv在图像上找到轮廓

[英]Opencv find Contours on image

我写了一个代码来检测图像上的书。 第一步是找到图像上的轮廓,但我对一些书有问题。 有时我无法正确检测轮廓(一本书是一个矩形,所以只需找到 4 个轮廓),因为线条未正确指定,并且我有间隙击败它们,如图所示。 有没有办法扩展检测到的边缘?

在此处输入图片说明

这是我的代码:

imgg = cv2.imread('\book.jpg')

gray = cv2.cvtColor(imgg, cv2.COLOR_BGR2GRAY)
gray = cv2.bilateralFilter(gray, 11, 17, 17)
edged = cv2.Canny(gray , 10, 250)


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

#binary = cv2.bitwise_not(gray)

for c in cnts:

    area = cv2.contourArea(c)

    peri = cv2.arcLength(c, True)
    approx = cv2.approxPolyDP(c, 0.03 * peri, True)

    if (len(approx) == 4) and (area > 100000):

        cv2.drawContours(imgg, [approx], -1, (0, 255, 0), 4)

cv2.imshow('image',imgg)
cv2.waitKey(0)
cv2.destroyAllWindows()

边缘检测通常效果不佳。 在这里您丢弃高度相关的信息,即颜色对比度。

饱和分量的二值化将更加有效。

在此处输入图片说明

这是阈值的快速示例,请记住在与以下脚本相同的文件夹中有一个 test.png。 在应用 findContours 之前使用它,应该是一个显着的改进。 否则谷歌Otsu's Binarization

import cv2 as cv
import numpy as np
from matplotlib import pyplot as plt
img = cv.imread('test.png',0)
img = cv.medianBlur(img,5)
ret,th1 = cv.threshold(img,127,255,cv.THRESH_BINARY)
th2 = cv.adaptiveThreshold(img,255,cv.ADAPTIVE_THRESH_MEAN_C,\
            cv.THRESH_BINARY,11,2)
th3 = cv.adaptiveThreshold(img,255,cv.ADAPTIVE_THRESH_GAUSSIAN_C,\
            cv.THRESH_BINARY,11,2)
titles = ['Original Image', 'Global Thresholding (v = 127)',
            'Adaptive Mean Thresholding', 'Adaptive Gaussian Thresholding']
images = [img, th1, th2, th3]
for i in xrange(4):
    plt.subplot(2,2,i+1),plt.imshow(images[i],'gray')
    plt.title(titles[i])
    plt.xticks([]),plt.yticks([])
plt.show()

暂无
暂无

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

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