Python OpenCV轮廓提取与中心点计算

本篇博客文章将介绍如何使用OpenCV库在Python中进行图像处理,特别是轮廓提取和中心点计算。

代码解释

以下是代码片段及其解释:

groundtruth = dilate[:, :] 
h1, w1 = groundtruth.shape
contours, cnt = cv.findContours(np.uint8(groundtruth), cv.RETR_EXTERNAL, cv.CHAIN_APPROX_SIMPLE)
X_center = []
Y_center = []
image_flag = cropped.copy()
for i in range(len(contours)):
    M = cv.moments(contours[i]) # 字典形式,计算各阶矩
    center_x = int(M['m10'] / M['m00'])
    center_y = int(M['m01'] / M['m00'])
    # print('区域中心坐标为:(%d, %d)' % (center_x, center_y))
    X_center.append(center_x)
    Y_center.append(center_y)
    cv.drawContours(cropped.copy(), contours, i, 255, -1) # 绘制轮廓,填充
    m_image = cv.circle(image_flag, (center_x, center_y), 10, (0, 0, 255), -1) # 绘制中心点
image_flag = m_image
  • groundtruth = dilate[:, :]: 将 dilate 数组的所有元素复制到 groundtruth 数组,创建一个相同内容的新数组。
  • h1, w1 = groundtruth.shape: 获取 groundtruth 数组的高度和宽度,并将其分别赋值给 h1w1
  • contours, cnt = cv.findContours(np.uint8(groundtruth), cv.RETR_EXTERNAL, cv.CHAIN_APPROX_SIMPLE): 使用OpenCV函数 cv.findContours() 查找二值图像 groundtruth 中的轮廓。
    • np.uint8(groundtruth): 将 groundtruth 转换为 uint8 类型。
    • cv.RETR_EXTERNAL: 只检测外部轮廓。
    • cv.CHAIN_APPROX_SIMPLE: 使用简化的轮廓编码方式。
  • X_center = []Y_center = []: 创建空列表,用于存储每个轮廓的中心坐标。
  • image_flag = cropped.copy(): 创建 cropped 图像的副本,用于绘制操作。
  • for i in range(len(contours)):: 遍历所有找到的轮廓。
    • M = cv.moments(contours[i]): 使用 cv.moments() 函数计算轮廓 contours[i] 的各阶矩,返回一个字典。
    • center_x = int(M['m10'] / M['m00'])center_y = int(M['m01'] / M['m00']): 计算轮廓的中心点坐标。
    • X_center.append(center_x)Y_center.append(center_y): 将中心点坐标添加到列表中。
    • cv.drawContours(cropped.copy(), contours, i, 255, -1): 在 cropped 图像副本上绘制轮廓并填充。
    • m_image = cv.circle(image_flag, (center_x, center_y), 10, (0, 0, 255), -1): 在 image_flag 图像上绘制一个圆,表示中心点。
  • image_flag = m_image: 将绘制了轮廓和中心点的图像赋值给 image_flag

总结

这段代码展示了如何使用OpenCV库在Python中进行轮廓提取和中心点计算。它涵盖了图像预处理、轮廓查找、中心点计算和结果可视化等步骤。通过学习这段代码,你可以了解OpenCV库的基本功能,并将其应用于自己的图像处理项目中。

Python OpenCV轮廓提取与中心点计算

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

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