Ask Your Question

Revision history [back]

Deskewing/aligning content of paper

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
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))
warped= warped[T:B, L:R]
cv2.imwrite("warped.jpg", warped)
enter code here

image description image description