python在图片中画一个区域并标注指定颜色
时间: 2024-10-14 12:12:09 浏览: 74
在Python中,我们可以利用PIL(Pillow)库来处理图像,并通过matplotlib或OpenCV等库添加区域标记以及指定颜色。下面是一个基本步骤:
首先,你需要安装Pillow库,如果还没有安装可以使用
pip install pillow
命令。导入需要的模块:
from PIL import Image, ImageDraw import matplotlib.pyplot as plt
加载图片:
image = Image.open('your_image_path.jpg')
创建ImageDraw对象,用于绘制:
draw = ImageDraw.Draw(image)
定义你要标注的区域,比如矩形或圆形,然后指定颜色和填充边界: ```python
矩形标注示例
left, upper, right, lower = (x1, y1, x2, y2) # 起始和结束坐标 fill_color = 'red' # 指定颜色 outline_color = 'black' # 边框颜色 rect = draw.rectangle([left, upper, right, lower], fill=fill_color, outline=outline_color)
圆形标注示例
center_x, center_y = (cx, cy) # 圆心坐标 radius = 10 # 半径 circle = draw.ellipse((center_x-radius, center_y-radius, center_x+radius, center_y+radius), fill=fill_color, outline=outline_color)
6. 最后,保存修改后的图片:
```python
image.save('annotated_image.jpg')
如果你想用matplotlib直接显示而不是保存图片,可以这样做:
plt.imshow(image)
plt.show()
相关推荐


















