0
votes

I am trying to scan an image using openCV, I am doing it in total 4 steps:

  • Transformation to gray scale.
  • Blur
  • Canny Edge detection
  • Perspective transformation.

I am not getting any error but final scanned image is not clear it is just showing single color in background. I have two files 1.Scanner 2.Mapper.

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

final

2

2 Answers

0
votes

use Bilateral filter instead of Gaussian blur.

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
votes

Plz try this map function maybe it will work.

def mapp(h):
    h=h.reshape((4,2))
    hnew=np.zeros((4,2),dtype = np.float32)

    add=h.sum(axis=1)
    hnew[0]=h[np.argmin(add)]
    hnew[3]=h[np.argmax(add)] #put 3 NOT 2

    diff=np.diff(h,axis = 1)
    hnew[1]=h[np.argmin(diff)]
    hnew[2]=h[np.argmax(diff)] #put 2 NOT 3

    return hnew

Before:

plot approx point

After

final image