用opencv-pycharm求出图片中两点间黑色部分的像素数并标记在黑色部分
时间: 2024-02-15 20:02:40 浏览: 20
好的,我可以帮你解决这个问题。首先,我们需要导入OpenCV库和Numpy库。
```python
import cv2
import numpy as np
```
接着,我们需要读入一张图片并进行灰度化处理。
```python
img = cv2.imread('path/to/image')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
```
然后,我们需要找到两点的坐标。这里我假设你已经知道了两点的坐标,分别为`(x1, y1)`和`(x2, y2)`。
接下来,我们需要找到两点之间的所有像素,并统计黑色像素的数量。
```python
mask = np.zeros_like(gray) # 创建一个和灰度图像大小相同的全黑图像
cv2.line(mask, (x1, y1), (x2, y2), 255, 1) # 在mask上画出(x1, y1)到(x2, y2)的白线
pixels = np.where(mask == 255) # 找到mask中像素值为255的位置
black_pixels = len(pixels[0]) - np.sum(gray[pixels] > 128) # 统计黑色像素数量
```
这里我们首先创建了一个和灰度图像大小相同的全黑图像`mask`,然后在`mask`上画出了两点之间的白线。接着,我们使用`np.where()`函数找到了`mask`中像素值为255的位置,并统计了其中黑色像素的数量。
最后,我们可以将黑色像素的数量标记在图片上。
```python
cv2.putText(img, f'{black_pixels} pixels', (x1, y1-10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0,0,255), 1)
```
这里我们使用了`cv2.putText()`函数,在图片上标记了黑色像素的数量。
完整代码如下:
```python
import cv2
import numpy as np
img = cv2.imread('path/to/image')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
x1, y1 = 100, 100 # 第一个点的坐标
x2, y2 = 200, 200 # 第二个点的坐标
mask = np.zeros_like(gray)
cv2.line(mask, (x1, y1), (x2, y2), 255, 1)
pixels = np.where(mask == 255)
black_pixels = len(pixels[0]) - np.sum(gray[pixels] > 128)
cv2.putText(img, f'{black_pixels} pixels', (x1, y1-10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0,0,255), 1)
cv2.imshow('image', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
你可以将`path/to/image`替换成你想要处理的图片的路径。