以下是使用 OpenCV 库实现轮廓检测的 Python 程序:

import cv2

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

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

# 二值化图像
_, threshold = cv2.threshold(gray, 50, 255, cv2.THRESH_BINARY)

# 查找轮廓
contours, hierarchy = cv2.findContours(threshold, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

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

# 显示图像
cv2.imshow('Contours', image)
cv2.waitKey(0)
cv2.destroyAllWindows()

该程序首先读取一张图像,将其转换为灰度图像,再进行二值化处理。然后使用cv2.findContours()函数查找轮廓,并使用cv2.drawContours()函数绘制轮廓。最后显示绘制好轮廓的图像。

Python OpenCV 轮廓检测:代码示例与解析

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

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