Deskewing/aligning content of paper

asked 2020-06-14 12:49:19 -0500

adammo gravatar image

Hi guys, I have a following problem. I load a photo. Then I search for a paper, warp it and cut margins (I know how big they are so it's fine). However the content of the paper is skewed. Grid size of labyrinth and grid size drawn onto the image are the same, however it's not very well aligned. Do you guys have an idea on how can I align it properly? Example and code below:

image = cv2.imread("image2.jpg")
ratio = image.shape[0] / 500.0
orig = image.copy()
image = imutils.resize(image, height = 500)
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
gray = cv2.GaussianBlur(gray, (5, 5), 0)
edged = cv2.Canny(gray, 75, 200)
print("STEP 1: Edge Detection")
cnts = cv2.findContours(edged.copy(), cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
cnts = imutils.grab_contours(cnts)
cnts = sorted(cnts, key = cv2.contourArea, reverse = True)[:5]
for c in cnts:
    peri = cv2.arcLength(c, True)
    approx = cv2.approxPolyDP(c, 0.02 * peri, True)
    if len(approx) == 4:
        screenCnt = approx
        break
cv2.drawContours(image, [screenCnt], -1, (0, 255, 0), 2)
warped = four_point_transform(orig, screenCnt.reshape(4, 2) * ratio)
warped = cv2.cvtColor(warped, cv2.COLOR_BGR2GRAY)
ret,warped = cv2.threshold(warped,160,255,cv2.THRESH_BINARY)
cv2.imshow("Scanned", imutils.resize(warped, height = 650))
L=int((5/210)*warped.shape[1])
R=int((205/210)*warped.shape[1])
T=int((8.5/297)*warped.shape[0])
B=int((288.5/297)*warped.shape[0])
warped= warped[T:B, L:R]
cv2.imwrite("warped.jpg", warped)
cv2.imshow("warped",warped)
enter code here

image description image description

edit retag flag offensive close merge delete