如何从opencv中的图片中检测文档?

时间:2017-02-05 19:58:08

标签: opencv image-processing edge-detection

我正在尝试设计类似于camscanner的应用。为此,我必须拍摄一张图片然后找到该文件。我从这里描述的代码开始 - http://opencvpython.blogspot.in/2012/06/sudoku-solver-part-2.html

我发现轮廓和最大面积的矩形轮廓应该是所需的文件。对于每个轮廓,我发现一个近似封闭的PolyDP。在所有大小为4的polyDP中,具有最大面积的polyDP应该是所需的文档。但是,这种方法不起作用。

该过程的输入图像是这样的 input Image

我尝试用最大面积打印轮廓,这导致了这个(Contour inside letter' C') enter image description here

代码:

img = cv2.imread('bounce.jpeg')
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
gray = cv2.GaussianBlur(gray,(5,5),0) 
thresh = cv2.adaptiveThreshold(gray,255,1,1,11,2)
_, contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

def biggestRectangle(contours):
    biggest = None
    max_area = 0
    indexReturn = -1
    for index in range(len(contours)):
            i = contours[index]
            area = cv2.contourArea(i)
            if area > 100:
                    peri = cv2.arcLength(i,True)
                    approx = cv2.approxPolyDP(i,0.1*peri,True)
                    if area > max_area: #and len(approx)==4:
                            biggest = approx
                            max_area = area
                            indexReturn = index
    return indexReturn

indexReturn = biggestRectangle(contours)
cv2.imwrite('hola.png',cv2.drawContours(img, contours, indexReturn, (0,255,0)))

这出了什么问题?有没有其他方法可以捕捉到这张照片中的文件?

2 个答案:

答案 0 :(得分:6)

试试这个: output image

import cv2
import numpy as np

img = cv2.imread('bounce.jpg')
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
invGamma = 1.0 / 0.3
table = np.array([((i / 255.0) ** invGamma) * 255
for i in np.arange(0, 256)]).astype("uint8")

# apply gamma correction using the lookup table
gray = cv2.LUT(gray, table)

ret,thresh1 = cv2.threshold(gray,80,255,cv2.THRESH_BINARY)

#thresh = cv2.adaptiveThreshold(gray,255,1,1,11,2)
_, contours, hierarchy = cv2.findContours(thresh1, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

def biggestRectangle(contours):
    biggest = None
    max_area = 0
    indexReturn = -1
    for index in range(len(contours)):
            i = contours[index]
            area = cv2.contourArea(i)
            if area > 100:
                peri = cv2.arcLength(i,True)
                approx = cv2.approxPolyDP(i,0.1*peri,True)
                if area > max_area: #and len(approx)==4:
                        biggest = approx
                        max_area = area
                        indexReturn = index
    return indexReturn

indexReturn = biggestRectangle(contours)
hull = cv2.convexHull(contours[indexReturn])
cv2.imwrite('hola.png',cv2.drawContours(img, [hull], 0, (0,255,0),3))
#cv2.imwrite('hola.png',thresh1)

答案 1 :(得分:3)

我会这样做:

  1. 像blur / canny

  2. 一样进行预处理
  3. 使用hough line transform (open cv doc)从图像中提取所有线条。

  4. 使用4条最强的行

  5. 尝试使用四行

  6. 构建文档的轮廓

    现在我没有安装OpenCV,所以我不能尝试这种方法,但也许它会引导你进入正确的方向。