pycv实时目标检测快速实现

使用python_cv实现目标实时检测

python 安装依赖

python 复制代码
opencv_python==4.7.0.72
pandas==1.5.3
tensorflow==2.11.0
tensorflow_hub==0.13.0
tensorflow_intel==2.11.0
numpy==1.23.5

核心代码快速使用

python 复制代码
# 使用了TensorFlow Hub和OpenCV库来实现实时对象检测
# tensorflow_hub:用于加载预训练的模型。
# cv2:OpenCV库,用于图像处理和视频流操作。
# tensorflow:深度学习框架。
# pandas:数据处理库。

import tensorflow_hub as hub
import cv2
# import numpy
import tensorflow as tf
import pandas as pd

# 加载了EfficientDet Lite2检测模型,并读取了标签文件:

# 模型加载方式被注释掉,直接通过本地路径加载模型。
# 从CSV文件中读取标签,以ID作为索引,获取对象名称。

# Carregar modelos
# detector = hub.load("https://tfhub.dev/tensorflow/efficientdet/lite2/detection/1")
detector = hub.load("efficientdet_lite2_detection_1")
labels = pd.read_csv('labels.csv', sep=';', index_col='ID')
labels = labels['OBJECT (2017 REL.)']

# 初始化摄像头捕获,0表示默认摄像头。
cap = cv2.VideoCapture(0)

# 定义输入图像的宽度和高度。

width = 512
height = 512

# 接下来是一个循环,用于实时处理视频流:
while (True):
    # Capture frame-by-frame
    # 在循环中,逐帧捕获视频并调整尺寸以匹配模型输入。
    ret, frame = cap.read()
    # Resize to respect the input_shape
    inp = cv2.resize(frame, (width, height))

    # 将BGR格式的图像转换为RGB格式,这是因为大多数深度学习模型接受RGB输入。
    # Convert img to RGB
    rgb = cv2.cvtColor(inp, cv2.COLOR_BGR2RGB)

    # Is optional but i recommend (float convertion and convert img to tensor image)
    rgb_tensor = tf.convert_to_tensor(rgb, dtype=tf.uint8)

    # 将图像转换为TensorFlow张量,类型为uint8。
    # Add dims to rgb_tensor
    rgb_tensor = tf.expand_dims(rgb_tensor, 0)
    
    # 增加一个维度以匹配模型输入要求。
    boxes, scores, classes, num_detections = detector(rgb_tensor)
    pred_labels = classes.numpy().astype('int')[0]
    pred_labels = [labels[i] for i in pred_labels]
    pred_boxes = boxes.numpy()[0].astype('int')
    pred_scores = scores.numpy()[0]
    # 将预测结果转换为可处理的格式,包括标签、边界框和得分。
    #循环遍历每个检测到的对象,绘制边界框和标签,只显示得分高于0.5的对象。
    # loop throughout the faces detected and place a box around it
    for score, (ymin, xmin, ymax, xmax), label in zip(pred_scores, pred_boxes, pred_labels):
        if score < 0.5:
            continue
        score_txt = f'{100 * round(score,0)}'
        img_boxes = cv2.rectangle(rgb, (xmin, ymax), (xmax, ymin), (0,  255, 0), 1)
        font = cv2.FONT_HERSHEY_SIMPLEX
        cv2.putText(img_boxes, label, (xmin, ymax-10), font, 0.5, (255, 0, 0), 1, cv2.LINE_AA)
        cv2.putText(img_boxes, score_txt, (xmax, ymax-10), font, 0.5, (255, 0, 0), 1, cv2.LINE_AA)
    # 显示处理后的图像,并在按下'q'键时退出循环。
    # Display the resulting frame
    cv2.imshow('black and white', img_boxes)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

# 释放摄像头资源并关闭所有OpenCV窗口,确保程序正常结束。
# When everything done, release the capture
cap.release()
cv2.destroyAllWindows()

实现结果展示

enjoy

github:liveCamer

相关推荐
Shockang38 分钟前
AI 编码智能体生产化工程
人工智能
jay神2 小时前
深度学习确定baseline之后怎么做改进?
人工智能·深度学习·yolo·计算机视觉·分类
acrel72 小时前
安科瑞Acrel-1000变电站综合自动化系统在合肥某新材料公司35kV综合自动化项目中的应用分析
大数据·人工智能
UWA2 小时前
隐藏视频变“常驻刺客”,VideoPlayer与“N/A”纹理该怎么查
人工智能·性能优化·音视频·memory·cpu·游戏开发
V哥AI增长2 小时前
小红书笔记在生成式AI引擎中的可见性机制解析:从抓取原理到GEO工程化实践
大数据·人工智能·笔记
ajassi20003 小时前
AI语音智能体开发日记(十二)GX8006 固件定制指南——从双唤醒词到 UART 音频传输
人工智能·ai·ai编程
大模型momo3 小时前
告别单体 Agent:多智能体设计模式(Multi-Agent Patterns)深度实战手册
人工智能·agent·multi-agent·多agent
DisonTangor3 小时前
【SeeDream开源平替】MiniMax H3 重磅开源:全模态视频生成新标杆,2K 画质 + 原生立体声,15 秒大片一键生成!
人工智能·ai作画·开源·aigc·音视频
很楠爱上3 小时前
(附上相关学习资源)适合新手做的第一个agent项目*ovo*Dify Agent 全栈实战:从智能选车顾问到新能源汽车之家的端到端开发
人工智能·汽车·agent·项目·开发笔记
IT智慧客07313 小时前
2026年7月前端面试高频考点与趋势分析(面20个前端后的总结)
人工智能