Python 批量自动纠正歪斜图像 - OpenCV 代码示例
以下是使用 OpenCV 库和 Python 编写的批量自动纠正多个歪斜的图像的示例代码:
import cv2
import os
# 定义函数用于自动纠正图像
def auto_correct(image_path):
# 读取图像
img = cv2.imread(image_path)
# 转换为灰度图像
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# 检测图像中的直线
lines = cv2.HoughLinesP(gray, 1, cv2.PI/180, 100, minLineLength=100, maxLineGap=10)
# 计算直线的平均角度
angles = []
for line in lines:
x1, y1, x2, y2 = line[0]
angle = cv2.fastAtan2(y2-y1, x2-x1)
angles.append(angle)
avg_angle = sum(angles) / len(angles)
# 旋转图像
rows, cols, _ = img.shape
M = cv2.getRotationMatrix2D((cols/2, rows/2), -avg_angle, 1)
rotated = cv2.warpAffine(img, M, (cols, rows))
# 保存纠正后的图像
cv2.imwrite(image_path, rotated)
# 遍历指定目录下的所有图像文件,并自动纠正它们
for filename in os.listdir('image_dir'):
if filename.endswith('.jpg'):
image_path = os.path.join('image_dir', filename)
auto_correct(image_path)
该代码会遍历指定目录下的所有以.jpg为后缀的图像文件,并对它们进行自动纠正。自动纠正的过程包括读取图像、转换为灰度图像、检测直线、计算平均角度、旋转图像和保存纠正后的图像。
原文地址: https://www.cveoy.top/t/topic/ga44 著作权归作者所有。请勿转载和采集!