以下是一个基本的 Python 程序,可以使用 OpenCV 库来查找并绘制图像中的轮廓:

import cv2

# 读取图像
img = cv2.imread('image.jpg')

# 将图像转换为灰度图像
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

# 对灰度图像进行二值化处理
ret, thresh = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY)

# 查找轮廓
contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

# 绘制轮廓
cv2.drawContours(img, contours, -1, (0, 255, 0), 3)

# 显示图像
cv2.imshow('Image', img)
cv2.waitKey(0)
cv2.destroyAllWindows()

在这个程序中,首先读取一张图像,然后将其转换为灰度图像。接下来,使用 cv2.threshold() 函数将灰度图像进行二值化处理,以得到二值化图像。然后使用 cv2.findContours() 函数查找图像中的轮廓,返回轮廓的列表以及轮廓的层次结构。最后,使用 cv2.drawContours() 函数将轮廓绘制在原始图像上,并显示该图像。

Python OpenCV 轮廓检测与绘制 - 详细步骤与代码示例

原文地址: https://www.cveoy.top/t/topic/mS4u 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录