contribute上次修改:2026-09-29

2.3 绘制图形与文字

总目录:1.1 OpenCV介绍与学习路线 | 第二章:基础图像处理 | 编号:2.3

← 上一节:2.2 缩放裁剪与拼接 | 下一节:2.4 滤波与降噪 →


2.3 绘制图形与文字

检测程序最后总要把结果画回来:框在哪里、中心在哪、判断成什么形状。不然算法自己觉得找到了,你却只能盯着终端里的坐标发呆。

一、先准备画布和颜色

canvas = np.zeros((512, 512, 3), dtype=np.uint8)

OpenCV 颜色按 BGR:

BLUE = (255, 0, 0)
GREEN = (0, 255, 0)
RED = (0, 0, 255)
WHITE = (255, 255, 255)

二、线、矩形和圆

line:画线

cv2.line(canvas, (20, 30), (300, 200), GREEN, 3, cv2.LINE_AA)

rectangle:画矩形

cv2.rectangle(canvas, (50, 60), (250, 220), BLUE, 2)

thickness=-1 表示填充:

cv2.rectangle(canvas, (50, 60), (250, 220), BLUE, -1)

circle:画圆

cv2.circle(canvas, center=(300, 180), radius=60, color=RED, thickness=3)

圆心和半径都要是整数。要表达亚像素坐标,可以了解 shift 参数;入门和大部分检测显示保持默认 shift=0 即可。

三、putText:把结果写在图上

cv2.putText(
    canvas,
    "target",
    (40, 40),
    cv2.FONT_HERSHEY_SIMPLEX,
    0.8,
    WHITE,
    2,
    cv2.LINE_AA,
)

org=(40, 40) 指的是文字基线左下附近,不是文字框左上角。如果文字贴出边界,可以用 getTextSize 先估算:

(text_w, text_h), baseline = cv2.getTextSize(
    "target", cv2.FONT_HERSHEY_SIMPLEX, 0.8, 2
)

OpenCV 自带 Hershey 字体不直接支持中文。中文标注可以改用 Pillow,或者先在终端输出中文、画面只写英文缩写。

四、polylines 与 drawContours

画普通点集:

points = np.array([[50, 50], [220, 80], [180, 240]], dtype=np.int32)
cv2.polylines(canvas, [points], isClosed=True, color=GREEN, thickness=2)

画 findContours 返回的轮廓:

cv2.drawContours(canvas, contours, -1, RED, 2)

两者不是谁“更高级”:

  • polylines 适合已经整理好的 (N, 2) 点集;
  • drawContours 适合轮廓列表,也能使用 hierarchy 控制层级。

如果只有一个轮廓,也要装进列表:

cv2.drawContours(canvas, [contour], 0, RED, 2)

五、绘图会直接修改原图

result = image.copy()
cv2.rectangle(result, (x, y), (x + w, y + h), GREEN, 2)

大多数绘图函数会就地修改传入图像并返回它。若后面还要使用干净原图,先 .copy()。

一个可运行示例

import cv2
import numpy as np

canvas = np.zeros((400, 600, 3), dtype=np.uint8)

cv2.line(canvas, (20, 20), (580, 20), (0, 255, 0), 2)
cv2.rectangle(canvas, (60, 80), (260, 260), (255, 0, 0), 3)
cv2.circle(canvas, (420, 170), 90, (0, 0, 255), 3)
cv2.putText(canvas, "OpenCV", (210, 350),
            cv2.FONT_HERSHEY_SIMPLEX, 1.0, (255, 255, 255), 2,
            cv2.LINE_AA)

cv2.imshow("Drawing", canvas)
cv2.waitKey(0)
cv2.destroyAllWindows()

← 上一节:2.2 缩放裁剪与拼接 | 下一节:2.4 滤波与降噪 →

留言区

不收集任何个人信息;昵称只绑定浏览器里的随机 Cookie。