python - 尝试使用 python 制作文档扫描仪但无法获得所需的输出图像
问题描述
我正在尝试使用 openCV 扫描图像,我总共执行了 4 个步骤:
- 转换为灰度。
- 模糊
- Canny 边缘检测
- 透视变换。
我没有收到任何错误,但最终扫描的图像不清楚,它只是在背景中显示单色。我有两个文件 1.Scanner 2.Mapper。
块引用
#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
精明的
最后
解决方案
使用双边滤波器而不是高斯模糊。
块引用
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)