发布于2026-07-17 阅读(0)
扫一扫,手机访问
在实际的图像处理项目里,画矩形(Rectangle) 这个操作,出现的频率之高,甚至超过了画线。

从目标检测中的边界框(Bounding Box),到OCR识别中的文字区域高亮,再到隐私保护里的马赛克遮挡,这些功能的核心,归根结底都是在画矩形。
今天,我们就继续沿用 OpenCV 和 Pillow 这两把“利器”,深入聊聊如何在 Python 中把矩形画得既优雅又高效。
(x, y, w, h)。在动手写代码之前,先来梳理一下画矩形的几个核心要素:
(x1, y1)(x2, y2)[x1, y1, x2, y2],用起来更顺手。OpenCV 在计算机视觉领域堪称首选,它的 rectangle 函数效率极高,与 numpy 数组操作配合得天衣无缝。
import cv2
import numpy as np
# 创建一张黑色背景图
img = np.zeros((500, 500, 3), dtype=np.uint8)
# 定义左上角和右下角坐标
pt1 = (50, 50) # (x, y)
pt2 = (400, 300) # (x, y)
# 定义颜色 (OpenCV 是 BGR,所以 (0, 0, 255) 是红色)
color = (0, 0, 255)
# 定义线宽 (如果是 -1,表示填充)
thickness = 3
# 画矩形
cv2.rectangle(img, pt1, pt2, color, thickness)
cv2.imshow("OpenCV Rectangle", img)
cv2.waitKey(0)
cv2.destroyAllWindows()
只需将 thickness 设置为 -1,就能画出一个填充的矩形。这在遮挡敏感信息时非常实用。
# 画一个绿色的实心矩形 cv2.rectangle(img, (50, 350), (450, 450), (0, 255, 0), -1)
OpenCV 本身没有提供画圆角矩形的直接函数,但我们可以通过组合画线和画圆来模拟。这里分享一个简单的“伪圆角”方法:
# 简单的圆角矩形函数
def draw_rounded_rectangle(img, pt1, pt2, color, radius, thickness):
x1, y1 = pt1
x2, y2 = pt2
# 画四条边
cv2.line(img, (x1 + radius, y1), (x2 - radius, y1), color, thickness)
cv2.line(img, (x1 + radius, y2), (x2 - radius, y2), color, thickness)
cv2.line(img, (x1, y1 + radius), (x1, y2 - radius), color, thickness)
cv2.line(img, (x2, y1 + radius), (x2, y2 - radius), color, thickness)
# 画四个角
cv2.circle(img, (x1 + radius, y1 + radius), radius, color, thickness)
cv2.circle(img, (x2 - radius, y1 + radius), radius, color, thickness)
cv2.circle(img, (x1 + radius, y2 - radius), radius, color, thickness)
cv2.circle(img, (x2 - radius, y2 - radius), radius, color, thickness)
# 使用
draw_rounded_rectangle(img, (50, 50), (250, 200), (255, 255, 0), 20, 2)
Pillow 的 API 在处理坐标时更加灵活,支持直接传入列表,而且颜色是直观的 RGB 模式,对新手更友好。
from PIL import Image, ImageDraw
# 创建白色背景图
img = Image.new('RGB', (500, 500), color='white')
draw = ImageDraw.Draw(img)
# 坐标可以是 [左上角x, 左上角y, 右下角x, 右下角y]
box = [50, 50, 400, 300]
# 画蓝色边框,宽度为 3
draw.rectangle(box, outline='blue', width=3)
# 画一个红色实心矩形
draw.rectangle([50, 350, 450, 450], fill='red')
img.show()
实际上,Pillow 的 rectangle 方法可以接受任意多边形坐标(只要遵循矩形框选逻辑),或者配合 ImageDraw.polygon 使用,自由度更高。
在目标检测中,我们经常需要在矩形框的上方贴一个带背景色的文字标签,让输出结果一目了然。
import cv2
img = cv2.imread("test.jpg") # 假设有一张原图
x, y, w, h = 100, 100, 200, 300 # 模拟检测框
# 1. 画矩形框
cv2.rectangle(img, (x, y), (x+w, y+h), (0, 255, 0), 2)
# 2. 画文字背景(实心小矩形)
label = "Person"
(text_width, text_height), _ = cv2.getTextSize(label, cv2.FONT_HERSHEY_SIMPLEX, 0.6, 2)
cv2.rectangle(img, (x, y - 25), (x + text_width, y), (0, 255, 0), -1) # 填充
# 3. 写文字
cv2.putText(img, label, (x, y - 5), cv2.FONT_HERSHEY_SIMPLEX, 0.6, (255, 255, 255), 2)
cv2.imshow("Labeled", img)
cv2.waitKey(0)
一个简单的实心色块太生硬了,真正的马赛克效果,是由许多小矩形组成的。
def apply_mosaic(img, x, y, w, h, block_size=10):
"""
对指定区域 (x, y, w, h) 进行马赛克处理
"""
roi = img[y:y+h, x:x+w]
# 缩小再放大,模拟马赛克
roi = cv2.resize(roi, (w // block_size, h // block_size), interpolation=cv2.INTER_LINEAR)
roi = cv2.resize(roi, (w, h), interpolation=cv2.INTER_NEAREST)
img[y:y+h, x:x+w] = roi
return img
# 使用
img = cv2.imread("face.jpg")
img = apply_mosaic(img, 50, 50, 200, 200)
cv2.imshow("Mosaic", img)
cv2.waitKey(0)
虽然这里用了 resize,但原理上就是通过像素块来模拟“大矩形”的效果。
有时候,我们需要高亮某个区域,但又不想完全遮住底下的图像内容。
import cv2
import numpy as np
img = cv2.imread("test.jpg")
overlay = img.copy()
# 定义区域
x, y, w, h = 100, 100, 300, 300
# 在覆盖层上画一个半透明矩形
# 先画一个实心矩形
cv2.rectangle(overlay, (x, y), (x+w, y+h), (255, 0, 0), -1)
# 混合原图和覆盖层 (alpha=0.3 表示覆盖层透明度)
cv2.addWeighted(overlay, 0.3, img, 0.7, 0, img)
cv2.imshow("Transparent Overlay", img)
cv2.waitKey(0)
| 特性 | OpenCV (cv2.rectangle) | Pillow (ImageDraw.rectangle) |
|---|---|---|
| 坐标系 | 左上角(0,0),向右下增长 | 左上角(0,0),向右下增长 |
| 参数 | (img, pt1, pt2, color, thickness) | (xy, outline, fill, width) |
| 填充 | thickness = -1 | fill = 'color' |
| 性能 | 极快 (底层C++,支持Numpy) | 中等 (纯Python实现部分) |
| 颜色 | BGR (易错点) | RGB (直观) |
| 推荐场景 | 视频处理、实时检测、算法开发 | 批量图片处理、Web后端生成图 |
画矩形看起来简单,但到了实际项目里,往往需要结合坐标计算、颜色空间转换和图层混合等一系列技巧。
cv2.rectangle 必须熟练掌握。特别是利用 -1 做遮挡,以及用 addWeighted 做半透明高亮,都是非常实用的技巧。
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
正版软件
正版软件
正版软件
正版软件
正版软件
1
2
3
7
8