Last active
March 20, 2020 13:05
-
-
Save mweibel/bd2d6c2271e42ed97b97 to your computer and use it in GitHub Desktop.
Python OpenCV deskew function, based on http://felix.abecassis.me/2011/10/opencv-rotation-deskewing/
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import cv2 | |
import numpy as np | |
from matplotlib import pyplot as plt | |
img = cv2.imread('image.jpg', cv2.IMREAD_GRAYSCALE) | |
def compute_skew(image): | |
image = cv2.bitwise_not(image) | |
height, width = image.shape | |
edges = cv2.Canny(image, 150, 200, 3, 5) | |
lines = cv2.HoughLinesP(edges, 1, cv2.cv.CV_PI/180, 100, minLineLength=width / 2.0, maxLineGap=20) | |
angle = 0.0 | |
nlines = lines.size | |
for x1, y1, x2, y2 in lines[0]: | |
angle += np.arctan2(y2 - y1, x2 - x1) | |
return angle / nlines | |
def deskew(image, angle): | |
image = cv2.bitwise_not(image) | |
non_zero_pixels = cv2.findNonZero(image) | |
center, wh, theta = cv2.minAreaRect(non_zero_pixels) | |
root_mat = cv2.getRotationMatrix2D(center, angle, 1) | |
rows, cols = image.shape | |
rotated = cv2.warpAffine(image, root_mat, (cols, rows), flags=cv2.INTER_CUBIC) | |
return cv2.getRectSubPix(rotated, (cols, rows), center) | |
deskewed_image = deskew(img.copy(), compute_skew(img)) |
me too i got an error in 'nlines = lines.size.shape[0]', it says 'int' object has no attribute 'shape'
me too i got an error in 'nlines = lines.size.shape[0]', it says 'int' object has no attribute 'shape'
For those that are getting the error in 'nlines = lines.size.shape[0]', it says 'int' object has no attribute 'shape'.
You can resolve this issue by changing it to 'nlines = lines.shape[0]'
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@avsthiago i got an error in 'nlines = lines.size.shape[0]', it says 'int' object has no attribute 'shape'