Advertisement
Guest User

Untitled

a guest
Mar 19th, 2018
73
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.35 KB | None | 0 0
  1. import cv2
  2. import numpy as np
  3. import os
  4. import shutil
  5.  
  6.  
  7. def transform(pos):
  8. # This function is used to find the corners of the object and the dimensions of the object
  9. pts = []
  10. n = len(pos)
  11. for i in range(n):
  12. pts.append(list(pos[i][0]))
  13.  
  14. sums = {}
  15. diffs = {}
  16. tl = tr = bl = br = 0
  17. for i in pts:
  18. x = i[0]
  19. y = i[1]
  20. sum = x + y
  21. diff = y - x
  22. sums[sum] = i
  23. diffs[diff] = i
  24. sums = sorted(sums.items())
  25. diffs = sorted(diffs.items())
  26. n = len(sums)
  27. rect = [sums[0][1], diffs[0][1], diffs[n - 1][1], sums[n - 1][1]]
  28. # top-left top-right bottom-left bottom-right
  29.  
  30. h1 = np.sqrt((rect[0][0] - rect[2][0]) ** 2 + (rect[0][1] - rect[2][1]) ** 2) # height of left side
  31. h2 = np.sqrt((rect[1][0] - rect[3][0]) ** 2 + (rect[1][1] - rect[3][1]) ** 2) # height of right side
  32. h = max(h1, h2)
  33.  
  34. w1 = np.sqrt((rect[0][0] - rect[1][0]) ** 2 + (rect[0][1] - rect[1][1]) ** 2) # width of upper side
  35. w2 = np.sqrt((rect[2][0] - rect[3][0]) ** 2 + (rect[2][1] - rect[3][1]) ** 2) # width of lower side
  36. w = max(w1, w2)
  37.  
  38. return int(w), int(h), rect
  39.  
  40.  
  41. img1 = cv2.imread('images.jpg')
  42.  
  43. dim = (4952, 6824) # Original Image size
  44. dim = (2476, 3412) # Resized
  45. img = cv2.resize(img1, dim, interpolation=cv2.INTER_AREA) # Commet this line to stop resize
  46. edge = cv2.Canny(img, 100, 100)
  47. _, contours, _ = cv2.findContours(edge.copy(), 1, 1)
  48. # n=len(contours)
  49. max_area = 0
  50. pos = 0
  51. for i in contours:
  52. area = cv2.contourArea(i)
  53. if area > max_area:
  54. max_area = area
  55. pos = i
  56.  
  57. peri = cv2.arcLength(pos, True)
  58. approx = cv2.approxPolyDP(pos, 0.02 * peri, True)
  59.  
  60. size = img.shape
  61. w, h, arr = transform(approx)
  62. pts2 = np.float32([[0, 0], [w, 0], [0, h], [w, h]])
  63. pts1 = np.float32(arr)
  64. print('pt',pts1,'\npt2',pts2)
  65.  
  66. M = cv2.getPerspectiveTransform(pts1*2, pts2*2)
  67. dst = cv2.warpPerspective(img1, M, (w*2, h*2))
  68.  
  69. # cv2.namedWindow('dst',cv2.WINDOW_NORMAL)
  70. cv2.imshow('dst',dst)
  71. # image=cv2.cvtColor(dst,cv2.COLOR_BGR2GRAY)
  72. image = cv2.resize(dst, (w*2, h*2), interpolation=cv2.INTER_AREA)
  73.  
  74. cv2.namedWindow('OUTPUT',cv2.WINDOW_NORMAL)
  75. cv2.imshow('OUTPUT', image)
  76. # cv2.namedWindow('edge',cv2.WINDOW_NORMAL)
  77. # cv2.imshow('edge',edge)
  78. cv2.imwrite('crop.jpg',image)
  79. cv2.waitKey(0)
  80. cv2.destroyAllWindows()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement