Python Opencv 任意形状目标检测,并绘制框图

本文分享了使用OpenCV进行复杂图像中任意形状目标识别的实战经验,通过自定义算法处理噪声并找到目标轮廓,最终实现精准定位。代码示例展示了阈值分割、轮廓查找、平均面积筛选和绘制边界框等关键步骤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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)

图像及结果如下:
原图

结果图如下:
在这里插入图片描述

### YOLO检测框绘制实现方法 YOLO(You Only Look Once)是一种高效的目标检测框架,其核心思想是将输入图像划分为多个网格单元,预测每个网格内的边界框及其对应的类别概率[^1]。为了在图像上可视化这些检测结果,通常需要绘制检测框以及标注相应的类别名称。 以下是基于PythonOpenCV库的YOLO检测框绘制的具体实现方式: #### 使用OpenCV绘制YOLO检测框 当使用YOLO完成目标检测后,会返回一系列边界框坐标、置信度分数以及类别标签。可以借助OpenCV绘制这些检测框显示相关信息。 ```python import cv2 import numpy as np def draw_yolo_bounding_boxes(image, boxes, confidences, class_ids, classes, colors, confidence_threshold=0.5): """ 在给定图像上绘制YOLO检测到的对象边框。 参数: image (numpy.ndarray): 输入图像数组。 boxes (list of list): 边界框列表 [[x, y, w, h], ...]。 confidences (list of float): 对应于每个边界框的置信度得分。 class_ids (list of int): 每个边界框对应类别的索引。 classes (list of str): 类别名称列表。 colors (dict or list): 不同类别的颜色映射。 confidence_threshold (float): 过滤低置信度检测的阈值,默认为0.5。 返回: numpy.ndarray: 带有绘制边框的图像。 """ height, width = image.shape[:2] for i in range(len(boxes)): if confidences[i] >= confidence_threshold: box = boxes[i] x, y, w, h = box color = colors[class_ids[i]] if isinstance(colors, dict) else colors[class_ids[i]] # 计算左上角和右下角坐标 start_x, start_y = max(int(x), 0), max(int(y), 0) end_x, end_y = min(int(x + w), width), min(int(y + h), height) # 绘制矩形框 cv2.rectangle(image, (start_x, start_y), (end_x, end_y), color, thickness=2) # 添加文字说明 label = f"{classes[class_ids[i]]}: {confidences[i]:.2f}" text_size, _ = cv2.getTextSize(label, cv2.FONT_HERSHEY_SIMPLEX, 0.5, 1) text_width, text_height = text_size # 文字背景填充 cv2.rectangle( image, (start_x, start_y), (start_x + text_width, start_y - text_height - 8), color, thickness=cv2.FILLED ) # 显示文本 cv2.putText( image, label, (start_x, start_y - 3), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 255), 1, lineType=cv2.LINE_AA ) return image ``` 上述函数`draw_yolo_bounding_boxes`接收YOLO输出的结果参数,包括边界框位置、置信度分值、分类ID以及其他辅助信息。它通过循环遍历所有满足置信度条件的检测对象,在原始图片上画出相应区域,附加描述性标签[^2]。 此外,还可以扩展此功能以支持更多特性,比如调整字体样式、增加透明效果或者保存最终处理后的图像文件等操作[^3]。 ---
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值