# Deskew skews the untilted image

Code:

    def correct_skew(image, delta=0.5, limit=5):
def determine_score(arr, angle):
data = inter.rotate(arr, angle, reshape=False, order=0)
histogram = np.sum(data, axis=1)
score = np.sum((histogram[1:] - histogram[:-1]) ** 2)
return histogram, score
scores = []
angles = np.arange(-limit, limit + delta, delta)
for angle in angles:
histogram, score = determine_score(image, angle)
scores.append(score)
best_angle = angles[scores.index(max(scores))]

return best_angle
thresh = cv2.threshold(img, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)[1]
angle = correct_skew(img)
(h, w) = img.shape[:2]
center = (w // 2, h // 2)
M = cv2.getRotationMatrix2D(center, angle, 1.0)
rotated = cv2.warpAffine(img, M, (w, h), flags=cv2.INTER_CUBIC, \
borderMode=cv2.BORDER_REPLICATE)
cv2.imwrite(rotimages_path,rotated)

edit retag close merge delete

context ? explanation ? example image ?

( 2020-07-01 01:11:06 -0500 )edit

@berak. No needed to do that context ? explanation ? example image. The indentation isn't accurately.

( 2020-07-01 07:38:45 -0500 )edit

Sort by ยป oldest newest most voted

I solved problem. It should be working. Your indentation isn't probably def correct_skew(image, delta=0.5, limit=5):, The correct way for indentation:

    def correct_skew(image, delta=0.5, limit=5):
def determine_score(arr, angle):
data = inter.rotate(arr, angle, reshape=False, order=0)
histogram = np.sum(data, axis=1)
score = np.sum((histogram[1:] - histogram[:-1]) ** 2)
return histogram, score
scores = []
angles = np.arange(-limit, limit + delta, delta)
for angle in angles:
histogram, score = determine_score(image, angle)
scores.append(score)
best_angle = angles[scores.index(max(scores))]

return best_angle

thresh = cv2.threshold(img, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)[1]
angle = correct_skew(img)
(h, w) = img.shape[:2]
center = (w // 2, h // 2)
M = cv2.getRotationMatrix2D(center, angle, 1.0)
rotated = cv2.warpAffine(img, M, (w, h), flags=cv2.INTER_CUBIC, \
borderMode=cv2.BORDER_REPLICATE)
cv2.imwrite(rotimages_path,rotated)

more

It is not a syntax error. It is working in my system, but for correct images, it adds skew. It is only on posting code alignment may be gone.

( 2020-07-02 07:06:06 -0500 )edit

Official site

GitHub

Wiki

Documentation