Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import cv2
- import numpy as np
- import os
- import shutil
- def transform(pos):
- # This function is used to find the corners of the object and the dimensions of the object
- pts = []
- n = len(pos)
- for i in range(n):
- pts.append(list(pos[i][0]))
- sums = {}
- diffs = {}
- tl = tr = bl = br = 0
- for i in pts:
- x = i[0]
- y = i[1]
- sum = x + y
- diff = y - x
- sums[sum] = i
- diffs[diff] = i
- sums = sorted(sums.items())
- diffs = sorted(diffs.items())
- n = len(sums)
- rect = [sums[0][1], diffs[0][1], diffs[n - 1][1], sums[n - 1][1]]
- # top-left top-right bottom-left bottom-right
- h1 = np.sqrt((rect[0][0] - rect[2][0]) ** 2 + (rect[0][1] - rect[2][1]) ** 2) # height of left side
- h2 = np.sqrt((rect[1][0] - rect[3][0]) ** 2 + (rect[1][1] - rect[3][1]) ** 2) # height of right side
- h = max(h1, h2)
- w1 = np.sqrt((rect[0][0] - rect[1][0]) ** 2 + (rect[0][1] - rect[1][1]) ** 2) # width of upper side
- w2 = np.sqrt((rect[2][0] - rect[3][0]) ** 2 + (rect[2][1] - rect[3][1]) ** 2) # width of lower side
- w = max(w1, w2)
- return int(w), int(h), rect
- img1 = cv2.imread('images.jpg')
- dim = (4952, 6824) # Original Image size
- dim = (2476, 3412) # Resized
- img = cv2.resize(img1, dim, interpolation=cv2.INTER_AREA) # Commet this line to stop resize
- edge = cv2.Canny(img, 100, 100)
- _, contours, _ = cv2.findContours(edge.copy(), 1, 1)
- # n=len(contours)
- max_area = 0
- pos = 0
- for i in contours:
- area = cv2.contourArea(i)
- if area > max_area:
- max_area = area
- pos = i
- peri = cv2.arcLength(pos, True)
- approx = cv2.approxPolyDP(pos, 0.02 * peri, True)
- size = img.shape
- w, h, arr = transform(approx)
- pts2 = np.float32([[0, 0], [w, 0], [0, h], [w, h]])
- pts1 = np.float32(arr)
- print('pt',pts1,'\npt2',pts2)
- M = cv2.getPerspectiveTransform(pts1*2, pts2*2)
- dst = cv2.warpPerspective(img1, M, (w*2, h*2))
- # cv2.namedWindow('dst',cv2.WINDOW_NORMAL)
- cv2.imshow('dst',dst)
- # image=cv2.cvtColor(dst,cv2.COLOR_BGR2GRAY)
- image = cv2.resize(dst, (w*2, h*2), interpolation=cv2.INTER_AREA)
- cv2.namedWindow('OUTPUT',cv2.WINDOW_NORMAL)
- cv2.imshow('OUTPUT', image)
- # cv2.namedWindow('edge',cv2.WINDOW_NORMAL)
- # cv2.imshow('edge',edge)
- cv2.imwrite('crop.jpg',image)
- cv2.waitKey(0)
- cv2.destroyAllWindows()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement