Python OpenCV实现任意形状目标检测与绘制

向北走
向北走
发布时间:2026-10-13| 5人浏览过
原创

本文介绍使用Python和OpenCV进行任意形状目标识别的方法。通过OTSU阈值分割和二值化处理,结合轮廓查找与面积筛选机制,有效去除噪声干扰。代码展示了如何计算轮廓边界并绘制检测框,适用于形状不固定且存在不确定噪声影响的简单图像场景。

OpenCV任意形状目标检测实现

利用OpenCV库进行任意形状的目标识别,以下提供具体实现方案供参考。

在实际工作中,曾遇到需要在简单图像中进行目标识别的需求。由于目标形状不固定,且受到一定程度的噪声影响,而噪声的具体特征具有不确定性,这增加了识别难度。鉴于图像结构相对简单,现将相关代码公开如下。


import cv2


def otsu_seg(img):

  ret_th, bin_img = cv2.threshold(img, 0, 255, cv2.THRESH_BINARY+cv2.THRESH_OTSU)

  return ret_th, bin_img

def find_pole(bin_img):
  img, contours, hierarchy = cv2.findContours(bin_img, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
  area = 0
  for i in range(len(contours)):
    area += cv2.contourArea(contours[i])
  area_mean = area / len(contours)
  mark = []
  for i in range(len(contours)):
    if cv2.contourArea(contours[i]) < area_mean:
      mark.append(i)

  return img, contours, hierarchy, mark

def draw_box(img,contours):
  img = cv2.rectangle(img,
         (contours[0][0], contours[0][1]),
         (contours[1][0], contours[1][1]),
         (255,255,255),
         3)
  return img

def main(img):
  ret, th = otsu_seg(img)
  img_new, contours, hierarchy, mark = find_pole(th)
  for i in range(len(contours)):
    if i not in mark:
      left_point = contours[i].min(axis=1).min(axis=0)
      right_point = contours[i].max(axis=1).max(axis=0)
      img = draw_box(img, (left_point, right_point))
  return img


if __name__ =="__main__":
  img = cv2.imread('G:/test.png')
  img = main(img)
  cv2.imwrite('G:/test_d.png', img)

最终生成的检测结果如图所示。

以上内容为本文的全部分享,希望能为读者的学习提供有益帮助,同时也欢迎大家继续支持本站。

相关标签:

免责声明:本文内容仅供参考,不代表本站观点。转载或引用请注明出处。

Python 相关产品和应用

全部下载
Selenium

Selenium

4.51.0 · Windows

用于浏览器自动化和 Web 测试的 Python 工具。

scikit-learn

scikit-learn

1.9.1 · Windows

常用 Python 机器学习算法与模型评估工具库。

Black

Black

26.10.1 · Windows

强调一致性的 Python 自动代码格式化工具。

Ruff

Ruff

0.17.1 · macOS

由 Rust 编写的高速 Python 代码检查和格式化工具。

pytest

pytest

9.1.1 · Windows

简洁而强大的 Python 自动化测试框架。

FastAPI

FastAPI

0.146.0 · Windows

高性能 Python API 框架,支持类型提示和自动接口文档。

Flask

Flask

3.1.3 · Windows

轻量灵活的 Python Web 应用框架。

Django

Django

6.1.2 · Windows

成熟的 Python Web 框架,适合构建内容站点和业务系统。

Spyder

Spyder

6.1.7 · Windows

面向科学计算与数据分析的 Python 集成开发环境。

SciPy

SciPy

1.18.1 · Windows

面向科学、工程和技术计算的 Python 算法库。