利用霍夫变换,将in文件夹中倾斜的图像进行校正,并输出到out文件夹。
关键代码摘自:https://blog.csdn.net/feilong_csdn/article/details/81586322
注意
1、文件夹名不能有中文
2、in文件夹内不要有其他文件或文件夹
3、out文件夹需要为空
每一个文件的变换都会需要几秒种时间。
#################
# 在指定目录下放置需要水平不正的图片文件,注意文件夹和文件名不能有中文
# 图像源文件在 文件夹\in 目录,输入为 文件夹\out 目录
# 注意:源文件夹里没有其他文件或文件夹,没有做相关判断
# 通过霍夫变换(网上找的)
# 运行后,在另一个文件夹中输出调整好方向的文件
#################
import os
import cv2
import math
import numpy as np
from scipy import ndimage
import imageio
# 源文件夹,注意不能有中文
filepath = 'E:\\pythonProject\\picRotate'
# 遍历文件
for filename in os.listdir(filepath + '\\in'):
# 读取图像
img = cv2.imread(filepath + '\\in/%s' % filename)
# 二值化
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
# 边缘检测
edges = cv2.Canny(gray,50,150,apertureSize = 3)
#霍夫变换,摘自https://blog.csdn.net/feilong_csdn/article/details/81586322
lines = cv2.HoughLines(edges,1,np.pi/180,0)
for rho,theta in lines[0]:
a = np.cos(theta)
b = np.sin(theta)
x0 = a*rho
y0 = b*rho
x1 = int(x0 + 1000*(-b))
y1 = int(y0 + 1000*(a))
x2 = int(x0 - 1000*(-b))
y2 = int(y0 - 1000*(a))
if x1 == x2 or y1 == y2:
continue
t = float(y2-y1)/(x2-x1)
# 得到角度后
rotate_angle = math.degrees(math.atan(t))
if rotate_angle > 45:
rotate_angle = -90 + rotate_angle
elif rotate_angle < -45:
rotate_angle = 90 + rotate_angle
# 图像根据角度进行校正
rotate_img = ndimage.rotate(img, rotate_angle)
# 输出图像
imageio.imwrite(filepath + '\\out\\' + filename, rotate_img)
print(filename + " 已转换")
print("转换结束")