import matplotlib.pyplot as plt
import cv2
import numpy as np
import matplotlib.pyplot as plt
# 完成灰度化,二值化
def Image_Binarization(img_raw):
img_gray = cv2.cvtColor(img_raw, cv2.COLOR_BGR2GRAY) # 灰度化
ret, img_process = cv2.threshold(img_gray, 127, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU) # 二值化
return img_process
# 旋转函数
def rotate(img_rotate_raw, angle):
(h, w) = img_rotate_raw.shape[:2]
(cx, cy) = (w // 2, h // 2)
m = cv2.getRotationMatrix2D((cx, cy), angle, 1.0) # 计算二维旋转的仿射变换矩阵
return cv2.warpAffine(img_rotate_raw, m, (w, h), borderValue=(0, 0, 0))
# 霍夫直线检测
def get_angle(img_hou_raw):
sum_theta = 0
img_canny = cv2.Canny(img_hou_raw, 50, 200, 3)
lines = cv2.HoughLines(img_canny, 1, np.pi / 180, 300, 0, 0)
# lines 是三维的
for i in range(lines.shape[0]):
theta = lines[i][0][1]
sum_theta += theta
average = sum_theta / lines.shape[0]
angle = average / np.pi * 180 - 90
return angle
def correct(img_cor_raw):
img_process = Image_Binarization(img_cor_raw)
angle = get_angle(img_process)
if angle == -1:
print("No lines!!!")
return 0
return rotate(img_cor_raw, angle)
if __name__ == "__main__":
img = cv2.imread('Pic_2020_10_11_161606_blockId#1527.bmp')
img_rot2 = correct(img)
cv2.imshow('dst',img_rot2)
cv2.waitKey()
版权声明:本文为qq_42247018原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。