📜  如何在 Matplotlib 中的图像上绘制矩形?

📅  最后修改于: 2022-05-13 01:55:07.399000             🧑  作者: Mango

如何在 Matplotlib 中的图像上绘制矩形?

先决条件: Matplotlib

给定一个图像,这里的任务是使用 matplotlib 绘制一个Python程序,在其上绘制一个矩形。 Matplotlib 带有 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()


输出:

原图

带有矩形的图像

示例 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()

输出:

原图

带有矩形的图像