尝试使用python制作Document Scanner,但无法获得所需的输出图像

时间:2019-06-22 18:41:12

标签: python opencv

我正在尝试使用openCV扫描图像,我总共需要4个步骤:

  • 转换为灰度。
  • 模糊
  • Canny Edge检测
  • 透视变换。

我没有收到任何错误,但最终扫描的图像不清楚,它只是在背景中显示单色。 我有两个档案 1.扫描仪 2地图

  

Blockquote

#Scanner code is given below
import cv2  
import numpy as np
import mapper 
image = cv2.imread("test_img.jpg")
image = cv2.resize(image,(1080,550))
orig = image.copy()
gray = cv2.cvtColor(image,cv2.COLOR_BGR2GRAY)
cv2.imshow("title",gray)
blurred = cv2.GaussianBlur(gray,(5,5),0)cv2.imshow("blur",blurred)


edged = cv2.Canny(blurred,50,80)
cv2.imshow("Canny",edged)

image,contours,hierarchy=cv2.findContours(edged,cv2.RETR_LIST,cv2.CHAIN_APPROX_SIMPLE)  #retrieve the contours as a list, with simple apprximation model
contours=sorted(contours,key=cv2.contourArea,reverse=True)

#the loop extracts the boundary contours of the page
for c in contours:
    p=cv2.arcLength(c,True)
    approx=cv2.approxPolyDP(c,0.02*p,True)

    if len(approx)==4:
        target=approx
        break
approx=mapper.mapp(target) #find endpoints of the sheet

pts=np.float32([[0,0],[800,0],[800,800],[0,800]])  #map to 800*800 tar`enter code here`get window

op=cv2.getPerspectiveTransform(approx,pts)  #get the top or bird eye view effect
dst=cv2.warpPerspective(orig,op,(800,800))


cv2.imshow("Scanned",dst)
cv2.waitKey(0)
#Mapper Code is given below

import numpy as np

def mapp(h):
    h = h.reshape((4,2))
    hnew = np.zeros((4,2),dtype = np.float32)
    add = h.sum(1)
    hnew[0] = h[np.argmin(add)]
    hnew[2] = h[np.argmax(add)]

    diff = np.diff(h,axis = 1)
    hnew[1] = h[np.argmin(diff)]
    hnew[3] = h[np.argmin(diff)]

    return hnew 

Canny

canny

最终

final

2 个答案:

答案 0 :(得分:0)

使用双边滤镜代替高斯模糊。

  

Blockquote

orig = image.copy()
gray = cv2.cvtColor(image,cv2.COLOR_BGR2GRAY)
cv2.imshow("title",gray)
blurred =cv2.bilateralFilter(gray,15,75,75)
cv2.imshow("blur",blurred)
edged = cv2.Canny(blurred,50,80)
cv2.imshow("Canny",edged)

答案 1 :(得分:-1)

请尝试使用此地图功能,也许它会起作用。

+

之前:

plot approx point

之后

final image