Advertisement
Guest User

Untitled

a guest
Oct 22nd, 2019
67
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.18 KB | None | 0 0
  1. import numpy as np
  2. import cv2
  3.  
  4.  
  5. def scan(input_image="test.jpg")
  6.  
  7. #read image
  8. img = cv2.imread(input_image,1)
  9.  
  10. #resize image
  11. img = cv2.resize(img,(600,800))
  12.  
  13. #convert image to grayscale
  14. grey = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
  15.  
  16. #blurr image to smooth
  17. blurr = cv2.GaussianBlur(grey, (5,5),0)
  18.  
  19. #finding edges
  20. edge = cv2.Canny(blurr, 0, 50)
  21.  
  22. #apadtive threshold and canny gave similar final output
  23. #threshold = cv2.adaptiveThreshold(blurr ,255,cv2.ADAPTIVE_THRESH_MEAN_C,cv2.THRESH_BINARY,11,2)
  24. #find contours in thresholded image and sort them according to decreasing area
  25. _, contours, _ = cv2.findContours(edge, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
  26. contours = sorted(contours, key=cv2.contourArea, reverse= True)
  27.  
  28. #contour approximation
  29. for i in contours:
  30. elip = cv2.arcLength(i, True)
  31. approx = cv2.approxPolyDP(i,0.08*elip, True)
  32.  
  33. if len(approx) == 4 :
  34. doc = approx
  35. break
  36.  
  37. #draw contours
  38. cv2.drawContours(img, [doc], -1, (0, 255, 0), 2)
  39.  
  40. #reshape to avoid errors ahead
  41. doc=doc.reshape((4,2))
  42.  
  43. #create a new array and initialize
  44. new_doc = np.zeros((4,2), dtype="float32")
  45.  
  46. Sum = doc.sum(axis = 1)
  47. new_doc[0] = doc[np.argmin(Sum)]
  48. new_doc[2] = doc[np.argmax(Sum)]
  49.  
  50. Diff = np.diff(doc, axis=1)
  51. new_doc[1] = doc[np.argmin(Diff)]
  52. new_doc[3] = doc[np.argmax(Diff)]
  53.  
  54. (tl,tr,br,bl) = new_doc
  55.  
  56. #find distance between points and get max
  57. dist1 = np.linalg.norm(br-bl)
  58. dist2 = np.linalg.norm(tr-tl)
  59.  
  60. maxLen = max(int(dist1),int(dist2))
  61.  
  62. dist3 = np.linalg.norm(tr-br)
  63. dist4 = np.linalg.norm(tl-bl)
  64.  
  65. maxHeight = max(int(dist3), int(dist4))
  66.  
  67. dst = np.array([[0,0],[maxLen-1, 0],[maxLen-1, maxHeight-1], [0, maxHeight-1]], dtype="float32")
  68.  
  69. N = cv2.getPerspectiveTransform(new_doc, dst)
  70. warp = cv2.warpPerspective(img, N, (maxLen, maxHeight))
  71.  
  72. img2 = cv2.cvtColor(warp, cv2.COLOR_BGR2GRAY)
  73. img2 = cv2.resize(img2,(600,800))
  74.  
  75. #cv2.imwrite("edge.jpg", edge)
  76. #cv2.imwrite("contour.jpg", img)
  77. #cv2.imwrite("Scanned.jpg", img2)
  78.  
  79. # show all images
  80. cv2.imshow("Original.jpg",img)
  81. cv2.imshow("Grey.jpg",grey)
  82. cv2.imshow("Gaussian_Blur.jpb",blurr)
  83. cv2.imshow("Canny_Edge.jpg",edge)
  84. #cv2.imshow("Threshold.jpg",threshold)
  85. cv2.imshow("Contours.jpg", img)
  86. cv2.imshow("Scanned.jpg", img2)
  87.  
  88. cv2.waitKey(0)
  89. cv2.destroyAllWindows()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement