计算两条平行白色直线间黑色像素个数的python代码及测试图片
时间: 2023-05-28 18:01:18 浏览: 79
```python
from PIL import Image
def count_black_pixels(filename):
# 打开图片
img = Image.open(filename)
# 转换为灰度图
img_gray = img.convert('L')
# 获取像素矩阵
pixels = img_gray.load()
# 获取图片宽度和高度
width, height = img.size
# 计算黑色像素数
black_pixels = 0
for y in range(height):
for x in range(width):
if pixels[x, y] < 128:
black_pixels += 1
return black_pixels
if __name__ == '__main__':
filename = 'test.jpg' # 测试图片的文件名
left_line = (20, 0) # 平行线的左边线的起点坐标
right_line = (200, 0) # 平行线的右边线的起点坐标
height = 300 # 平行线的高度
# 在图片上画出平行线
img = Image.open(filename)
draw = ImageDraw.Draw(img)
draw.line((left_line, (left_line[0], left_line[1] + height)), fill='white', width=2)
draw.line((right_line, (right_line[0], right_line[1] + height)), fill='white', width=2)
img.show()
# 计算两条平行线之间的黑色像素数
black_pixels = count_black_pixels(filename)
print('两条平行线之间的黑色像素数:', black_pixels)
```
测试图片:
![test](https://img-blog.csdn.net/20180912202430973?watermark/2/text/aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L0d1aWRheV9HZW5n/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/q/85/blog_pic.jpg)
阅读全文