Python实现图片方向矫正的代码
时间: 2023-06-06 18:04:32 浏览: 100
以下是Python实现图片方向矫正的代码示例:
```python
import cv2
def correct_orientation(img):
# Convert BGR image to grayscale
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# Apply thresholding to convert image to binary
_, thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY_INV | cv2.THRESH_OTSU)
# Find contours in binary image
contours, _ = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
# Get the largest contour
largest_contour = max(contours, key=cv2.contourArea)
# Get the rotated rectangle enclosing the largest contour
rectangle = cv2.minAreaRect(largest_contour)
# Get the angle by which the rectangle needs to be rotated
angle = rectangle[-1]
# Rotate the image by the calculated angle
(h, w) = img.shape[:2]
center = (w // 2, h // 2)
rotation_matrix = cv2.getRotationMatrix2D(center=center, angle=angle, scale=1.0)
rotated = cv2.warpAffine(img, rotation_matrix, dsize=(w, h), flags=cv2.INTER_CUBIC)
return rotated
```
这个函数接收一个图像作为输入,并返回经过矫正方向后的图像。它使用OpenCV库实现了以下步骤:
1. 将图像转换为灰度图
2. 将灰度图二值化
3. 获取二值图中最大的轮廓
4. 获取覆盖最大轮廓的旋转矩形
5. 计算旋转角度
6. 旋转图像
7. 返回旋转后的图像
如果图像方向已经正确,则返回原始图像无修改。
阅读全文