怎么只对图像的上半部分找出的轮廓进行处
时间: 2024-03-13 17:46:01 浏览: 14
可以使用 Numpy 库来对轮廓的坐标进行筛选,只保留上半部分的轮廓点坐标。具体方法是,对于每个轮廓点,判断其 y 坐标是否小于图像高度的一半,如果是,则保留该点坐标,否则舍弃。下面是 Python 的示例代码:
```python
import cv2
import numpy as np
img = cv2.imread('image.jpg')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
ret, thresh = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY)
contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
# 筛选上半部分的轮廓点
height, width = img.shape[:2]
half_height = height // 2
filtered_contours = []
for contour in contours:
filtered_contour = []
for point in contour:
x, y = point.ravel()
if y < half_height:
filtered_contour.append([x, y])
if filtered_contour:
filtered_contours.append(np.array(filtered_contour))
# 在原图上绘制筛选后的轮廓
cv2.drawContours(img, filtered_contours, -1, (0, 255, 0), 3)
cv2.imshow('image', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
在上面的代码中,我们首先使用 `findContours()` 函数找到轮廓,然后对每个轮廓点进行筛选,只保留其 y 坐标小于图像高度的一半的点。筛选后,将筛选后的轮廓绘制到原图上。运行程序后,会显示原图像和只绘制了上半部分轮廓的图像,可以通过按键输入结束程序。