Python 通过ImageDraw.rectangle 画矩形框

文章介绍了如何使用Python的PIL库中的ImageDraw.rectangle函数和OpenCV的cv2.rectangle函数来绘制矩形,包括设置填充色、轮廓色和边框宽度,并提供了相应的示例代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1. 函数讲解

源代码如下:ImageDraw.rectangle(xy, fill=None, outline=None, width=1)
主要的参数如下:

  • xy: 定义边界框长宽边界,主要格式如下:[(x0, y0), (x1, y1)]或者 [x0, y0, x1, y1]
  • fill:填充颜色
  • outline:轮廓颜色
  • width:矩形边框的宽度

2. 示例代码

# importing image object from PIL 
import math 
from PIL import Image, ImageDraw 
  
img = Image.open("Gym.jpg") 

ImageDraw.Draw(img).rectangle([(100, 300), (300, 700)] , fill =None, outline ="red",width =2) 

plt.imshow(img)
plt.show()

截图如下:

在这里插入图片描述

3. 补充cv2.rectangle

cv2.rectangle 则根据对角线画矩形

示例代码如下:

import os
import cv2
import matplotlib.pyplot as plt

img = cv2.imread("Gym.jpg")
xmin = 100
xmax = 500
ymin = 100
ymax = 800
cv2.rectangle(img, (xmin, ymin), (xmax, ymax), (0,0,255), 2)
cv2.rectangle(img, (xmin, ymax), (xmax, ymin), (255,0,0), 2)
#     cv2.imshow('src',img)
#     cv2.waitKey()

plt.imshow(img)
plt.show()

截图如下:
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

码农研究僧

你的鼓励将是我创作的动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值