请用Python与matplotlib写出如何在一张图像上绘制mask的代码
时间: 2024-05-11 09:14:52 浏览: 188
下面是使用Python与matplotlib在一张图像上绘制mask的代码:
```python
import matplotlib.pyplot as plt
import numpy as np
# 加载图像
img = plt.imread('image.png')
# 创建一个黑色的遮罩
mask = np.zeros_like(img[:,:,0])
# 绘制矩形区域的遮罩
mask[100:250, 100:300] = 1
# 将遮罩应用于原始图像
masked_img = np.copy(img)
masked_img[:,:,0] = np.where(mask==1, 255, masked_img[:,:,0])
masked_img[:,:,1] = np.where(mask==1, 0, masked_img[:,:,1])
masked_img[:,:,2] = np.where(mask==1, 0, masked_img[:,:,2])
# 绘制原始图像和遮罩后的图像
fig, axs = plt.subplots(1, 2)
axs[0].imshow(img)
axs[0].set_title('Original Image')
axs[1].imshow(masked_img)
axs[1].set_title('Masked Image')
plt.show()
```
这段代码假设你要绘制一个长宽为200x200,左上角坐标为(100, 100)的矩形区域的遮罩,并将其应用于名为"image.png"的原始图像。运行后,将在一个窗口中呈现出原始图像和遮罩后的图像。
阅读全文
相关推荐

















