能加上图片裁剪功能吗
时间: 2024-02-24 20:58:52 浏览: 23
当然可以加上图片裁剪功能。下面是修改后的代码,可以实现对原始图像进行投影法分割,并将分割后的子图像保存为单独的文件:
```python
import cv2
import numpy as np
# 读取原始图像
img = cv2.imread('test.png')
# 转换为灰度图像
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# 二值化处理
ret, binary = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY_INV)
# 求出横向和纵向的投影值
h, w = binary.shape[:2]
h_proj = np.sum(binary, axis=1)
w_proj = np.sum(binary, axis=0)
# 绘制横向投影图
h_proj_img = np.zeros((h, w), dtype=np.uint8)
for i in range(h):
cv2.line(h_proj_img, (0, i), (int(h_proj[i] * w / h), i), 255, 1)
# 绘制纵向投影图
w_proj_img = np.zeros((h, w), dtype=np.uint8)
for i in range(w):
cv2.line(w_proj_img, (i, h), (i, h - int(w_proj[i] * h / w)), 255, 1)
# 分割图像
h_lines = cv2.findContours(h_proj_img.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)[-2]
h_lines = sorted(h_lines, key=cv2.boundingRect)
for i, contour in enumerate(h_lines):
x, y, w, h = cv2.boundingRect(contour)
if h > 10:
roi = img[y:y + h, x:x + w]
cv2.imwrite('roi_{}.png'.format(i), roi)
# 显示结果
cv2.imshow('original', img)
cv2.imshow('binary', binary)
cv2.imshow('h_proj', h_proj_img)
cv2.imshow('w_proj', w_proj_img)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
这个示例代码中加入了分割图像的代码。首先,利用`cv2.findContours()`函数找到横向投影图中的连通区域,并按照从上到下的顺序进行排序;然后,遍历每个连通区域,如果高度大于10个像素,就将该区域对应的子图像裁剪出来,并保存为单独的文件。裁剪后的子图像文件名为`roi_{}.png`,其中`{}`表示子图像的编号。
需要注意的是,这个示例代码中的分割阈值是10像素,也就是说,连通区域高度小于10个像素的部分会被忽略。如果需要调整分割阈值,可以修改`h > 10`这一行的代码。