如何在 Matplotlib 中的图像上绘制矩形?
先决条件: Matplotlib
给定一个图像,这里的任务是使用 matplotlib 绘制一个Python程序,在其上绘制一个矩形。 Matplotlib 带有 rectangle()函数,可用于我们的要求。
Syntax: Rectangle(xy, width, height, angle=0.0, **kwargs)
Parameters:
- xy: Lower left point to start the rectangle plotting
- width : width of the rectangle
- height: Height of the rectangle.
- angle: Angle of rotation of the rectangle.
方法
- 导入必要的库。
- 插入并显示图像。
- 创建绘图的图形和轴
- 将补丁添加到轴
- 显示图像
示例 1:在图像上绘制矩形
Python3
import matplotlib.pyplot as plt
import matplotlib.patches as patches
from PIL import Image
import numpy as np
x = np.array(Image.open('geek.png'), dtype=np.uint8)
plt.imshow(x)
# Create figure and axes
fig, ax = plt.subplots(1)
# Display the image
ax.imshow(x)
# Create a Rectangle patch
rect = patches.Rectangle((50, 100), 40, 30, linewidth=1,
edgecolor='r', facecolor="none")
# Add the patch to the Axes
ax.add_patch(rect)
plt.show()
Python3
import matplotlib.pyplot as plt
import matplotlib.patches as patches
from PIL import Image
import numpy as np
x = np.array(Image.open('geek.png'), dtype=np.uint8)
plt.imshow(x)
# Create figure and axes
fig, ax = plt.subplots(1)
# Display the image
ax.imshow(x)
# Create a Rectangle patch
rect = patches.Rectangle((50, 100), 40, 30, linewidth=1,
edgecolor='r', facecolor="g")
# Add the patch to the Axes
ax.add_patch(rect)
plt.show()
输出:
![](https://mangodoc.oss-cn-beijing.aliyuncs.com/geek8geeks/How_to_Draw_Rectangle_on_Image_in_Matplotlib?_0.jpg)
原图
![](https://mangodoc.oss-cn-beijing.aliyuncs.com/geek8geeks/How_to_Draw_Rectangle_on_Image_in_Matplotlib?_1.jpg)
带有矩形的图像
示例 2:绘制一个实心矩形
蟒蛇3
import matplotlib.pyplot as plt
import matplotlib.patches as patches
from PIL import Image
import numpy as np
x = np.array(Image.open('geek.png'), dtype=np.uint8)
plt.imshow(x)
# Create figure and axes
fig, ax = plt.subplots(1)
# Display the image
ax.imshow(x)
# Create a Rectangle patch
rect = patches.Rectangle((50, 100), 40, 30, linewidth=1,
edgecolor='r', facecolor="g")
# Add the patch to the Axes
ax.add_patch(rect)
plt.show()
输出:
![](https://mangodoc.oss-cn-beijing.aliyuncs.com/geek8geeks/How_to_Draw_Rectangle_on_Image_in_Matplotlib?_2.jpg)
原图
![](https://mangodoc.oss-cn-beijing.aliyuncs.com/geek8geeks/How_to_Draw_Rectangle_on_Image_in_Matplotlib?_3.jpg)
带有矩形的图像