You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Python OpenCV的cv2.drawContour绘制指定轮廓红线?

OpenCV绘制指定网格轮廓实现方案

实现逻辑

通过阈值分割分离网格与背景,再调用轮廓检测接口拿到所有内外层轮廓,最后直接调用cv2.drawContours绘制即可。

具体步骤

  • 读取输入图像后转换为灰度图,反色二值化让网格区域为白色、背景为黑色
  • 使用cv2.findContours的RETR_TREE模式同时检测外层轮廓和内部孔洞轮廓
  • 用指定的红色参数绘制所有检测到的轮廓

完整可运行代码

import cv2
import numpy as np

# 读取原图
img = cv2.imread("input.png")
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

# 二值化反色处理
_, thresh = cv2.threshold(gray, 150, 255, cv2.THRESH_BINARY_INV)

# 可选:如果有噪点可加形态学开运算过滤
# kernel = np.ones((2,2), np.uint8)
# thresh = cv2.morphologyEx(thresh, cv2.MORPH_OPEN, kernel, iterations=1)

# 检测轮廓
contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

# 绘制红色轮廓,线宽2,-1代表绘制所有轮廓
cv2.drawContours(img, contours, -1, (0, 0, 255), 2)

# 结果展示与保存
cv2.imshow("result", img)
cv2.waitKey(0)
cv2.destroyAllWindows()
# cv2.imwrite("output.png", img)

参考图像

输入原图

原图

目标效果参考

目标效果图

内容的提问来源于stack exchange,提问作者kkk

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 01:39:00