图像分割加倾斜校正代码
时间: 2023-10-15 20:05:49 浏览: 66
以下是一个简单的图像分割加倾斜校正的代码示例,使用 Python 和 OpenCV 库实现。
```python
import cv2
import numpy as np
# 读入原始图像
img = cv2.imread('image.png')
# 灰度化处理
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# 二值化处理
ret, thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY_INV+cv2.THRESH_OTSU)
# 进行形态学操作,去除噪点
kernel = np.ones((3,3), np.uint8)
opening = cv2.morphologyEx(thresh, cv2.MORPH_OPEN, kernel, iterations=2)
# 找到轮廓
contours, hierarchy = cv2.findContours(opening, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
# 计算轮廓中心坐标,并将轮廓按照 x 坐标排序
centers = []
for contour in contours:
M = cv2.moments(contour)
cx = int(M['m10']/M['m00'])
cy = int(M['m01']/M['m00'])
centers.append((cx, cy))
centers.sort()
# 分割图像并进行倾斜校正
for i in range(len(centers)-1):
img_crop = img[:, centers[i][0]:centers[i+1][0]]
gray_crop = gray[:, centers[i][0]:centers[i+1][0]]
# 使用 Hough 变换进行倾斜校正
edges = cv2.Canny(gray_crop, 50, 150, apertureSize=3)
lines = cv2.HoughLines(edges, 1, np.pi/180, 100)
if lines is not None and len(lines) > 0:
angle = lines[0][0][1] * 180 / np.pi - 90
img_crop = cv2.rotate(img_crop, cv2.ROTATE_90_CLOCKWISE)
gray_crop = cv2.rotate(gray_crop, cv2.ROTATE_90_CLOCKWISE)
# 保存分割后的图像
cv2.imwrite('img_crop{}.png'.format(i), img_crop)
```
这段代码将原始图像进行灰度化和二值化处理,使用形态学操作去除噪点,找到轮廓并按照 x 坐标排序。然后将图像分割成多个子图像,并使用 Hough 变换进行倾斜校正。最后保存分割后的图像。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)