需求描述:
对倾斜的图片进行矫正,返回倾斜角度和矫正后的图片。
解决方法:
1、各种角度点被投影到一个累加器阵列中,其中倾斜角度可以定义为在最大化对齐的搜索间隔内的投影角度。
2、以不同的角度旋转图像,并为每次迭代生成像素的直方图。
3、为了确定倾斜角度,比较峰值之间的最大差异,并使用这个倾斜角度,旋转图像来纠正倾斜。
#coding=utf-8
import cv2
import numpy as np
def rotate_image(image, angle):
(h, w) = image.shape[: 2]
center = (w // 2, h // 2)
M = cv2.getRotationMatrix2D(center, angle, 1.0)
corrected = cv2.warpAffine(image, M, (w, h), flags = cv2.INTER_CUBIC, \
borderMode = cv2.BORDER_REPLICATE)
return corrected
def determine_score(arr):
histogram = np.sum(arr, axis = 2, dtype = float)
score = np.sum((histogram[..., 1 :] - histogram[..., : -1]) ** 2, \
axis = 1, dtype = float)
return score
def correct_skew(image, delta = 0.1, limit = 5):
thresh = cv2.threshold(image, 0, 255, cv2.THRESH_BINARY_INV + \
cv2.THRESH_OTSU)[1]
angles = np.arange(-limit, limit + delta, delta)
img_stack = np.stack([rotate_image(thresh, angle) for angle \
in angles], axis = 0)
scores = determine_score(img_stack)
best_angle = angles[np.argmax(scores)]
corrected = rotate_image(image, best_angle)
return best_angle, corrected
if __name__ == "__main__":
file_path=r'D:/_21.png'
img = cv2.imread(file_path, 0)
angle, corrected = correct_skew(img)
print(angle)
cv2.imwrite(r'D:/temp_' + file_path.split('/')[-1], corrected)
执行结果:
矫正前:
矫正后: