以下是使用OpenCV库在Python中实现轮廓检测和编号的示例代码:

import cv2

# 读取图像
img = cv2.imread('example.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)

# 绘制轮廓并编号
for i, contour in enumerate(contours):
    cv2.drawContours(img, [contour], 0, (0, 255, 0), 3)
    # 计算轮廓中心坐标
    M = cv2.moments(contour)
    cX = int(M["m10"] / M["m00"])
    cY = int(M["m01"] / M["m00"])
    # 在中心位置写上编号
    cv2.putText(img, str(i+1), (cX, cY), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255), 2)

# 显示结果
cv2.imshow('contours', img)
cv2.waitKey(0)
cv2.destroyAllWindows()

运行以上代码后,会在图片上绘制出所有的轮廓,并在每个轮廓中心位置写上对应的编号。

用python写一个轮廓检测编号

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

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