Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save crapthings/81aa577b6eb62187d882ae45fadb4f01 to your computer and use it in GitHub Desktop.
Save crapthings/81aa577b6eb62187d882ae45fadb4f01 to your computer and use it in GitHub Desktop.
import cv2
import numpy as np
def rectify(h, l):
h = h.reshape((l, 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.argmax(diff)]
return hnew
image = cv2.imread('3.jpg', 0)
canvas = image.copy()
kernel = np.ones((5, 5), np.uint8)
# image = cv2.erode(image, kernel, iterations = 2)
image = cv2.medianBlur(image, 7)
image1 = image
# _, image1 = cv2.threshold(image, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
image1 = cv2.adaptiveThreshold(image1, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY_INV, 11, 10)
# image1 = cv2.Canny(image1, 100, 255, apertureSize = 3, L2gradient = True)
image1 = cv2.dilate(image1, kernel, iterations = 2)
cnts = cv2.findContours(image1, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)[-2]
cnts = sorted(cnts, key = cv2.contourArea)
cnt = cnts[-1]
arclen = cv2.arcLength(cnt, True)
approx = cv2.approxPolyDP(cnt, 0.02 * arclen, True)
# cv2.drawContours(canvas, [cnt], -1, (255, 0, 0), 5, cv2.LINE_AA)
approx = rectify(approx, len(approx))
pts2 = np.float32([[0, 0], [2480, 0], [2480, 3508], [0, 3508]])
M = cv2.getPerspectiveTransform(approx, pts2)
dst = cv2.warpPerspective(canvas, M, (2480, 3508))
cv2.namedWindow('image1', cv2.WINDOW_NORMAL)
cv2.imshow('image1', dst)
cv2.waitKey(0)
cv2.destroyAllWindows()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment