AI学习笔记二十八:使用ESP32 CAM和YOLOV5实现目标检测

news2025/5/31 22:30:34

若该文为原创文章,转载请注明原文出处。

最近在研究使用APP如何显示ESP32 CAM的摄像头数据,看到有人实现把ESP32 CAM的数据流上传,通过YOLOV5来检测,实现拉流推理,这里复现一下。

一、环境

 arduino配置esp32-cam开发环境

https://www.jianshu.com/p/c1a69a6772f3

软件自行安装

二、程序

程序是基于esp32的例子上修改的

修改主要是几个地方

1、摄像头

根据自己的ESP32 CAM选择

2、WIFI

3、配置TCP端口

配置是为了YOLOV5拉流使用

4、源码

#include "esp_camera.h"
#include <WiFi.h>
 
//
// WARNING!!! PSRAM IC required for UXGA resolution and high JPEG quality
//            Ensure ESP32 Wrover Module or other board with PSRAM is selected
//            Partial images will be transmitted if image exceeds buffer size
//
 
// Select camera model
//#define CAMERA_MODEL_WROVER_KIT // Has PSRAM
//#define CAMERA_MODEL_ESP_EYE // Has PSRAM
//#define CAMERA_MODEL_M5STACK_PSRAM // Has PSRAM
//#define CAMERA_MODEL_M5STACK_V2_PSRAM // M5Camera version B Has PSRAM
//#define CAMERA_MODEL_M5STACK_WIDE // Has PSRAM
//#define CAMERA_MODEL_M5STACK_ESP32CAM // No PSRAM
//#define CAMERA_MODEL_M5STACK_UNITCAM // No PSRAM
#define CAMERA_MODEL_AI_THINKER // Has PSRAM
//#define CAMERA_MODEL_TTGO_T_JOURNAL // No PSRAM
 
#include "camera_pins.h"
 
const char* ssid = "yifeng";
const char* password = "1234567890";
 
// 配置TCP端口
WiFiServer ServerPort(1234);
 
void startCameraServer();
 
void setup() {
  Serial.begin(115200);
  Serial.setDebugOutput(true);
  Serial.println();
  // 配置闪光灯
  pinMode(4, OUTPUT);
  // 关闭闪光灯
  digitalWrite(4, LOW);
 
  camera_config_t config;
  config.ledc_channel = LEDC_CHANNEL_0;
  config.ledc_timer = LEDC_TIMER_0;
  config.pin_d0 = Y2_GPIO_NUM;
  config.pin_d1 = Y3_GPIO_NUM;
  config.pin_d2 = Y4_GPIO_NUM;
  config.pin_d3 = Y5_GPIO_NUM;
  config.pin_d4 = Y6_GPIO_NUM;
  config.pin_d5 = Y7_GPIO_NUM;
  config.pin_d6 = Y8_GPIO_NUM;
  config.pin_d7 = Y9_GPIO_NUM;
  config.pin_xclk = XCLK_GPIO_NUM;
  config.pin_pclk = PCLK_GPIO_NUM;
  config.pin_vsync = VSYNC_GPIO_NUM;
  config.pin_href = HREF_GPIO_NUM;
  config.pin_sscb_sda = SIOD_GPIO_NUM;
  config.pin_sscb_scl = SIOC_GPIO_NUM;
  config.pin_pwdn = PWDN_GPIO_NUM;
  config.pin_reset = RESET_GPIO_NUM;
  config.xclk_freq_hz = 20000000;
  config.pixel_format = PIXFORMAT_JPEG;
  
  // if PSRAM IC present, init with UXGA resolution and higher JPEG quality
  //                      for larger pre-allocated frame buffer.
  if(psramFound()){
    config.frame_size = FRAMESIZE_UXGA;
    config.jpeg_quality = 10;
    config.fb_count = 2;
  } else {
    config.frame_size = FRAMESIZE_SVGA;
    config.jpeg_quality = 12;
    config.fb_count = 1;
  }
 
#if defined(CAMERA_MODEL_ESP_EYE)
  pinMode(13, INPUT_PULLUP);
  pinMode(14, INPUT_PULLUP);
#endif
 
  // camera init
  esp_err_t err = esp_camera_init(&config);
  if (err != ESP_OK) {
    Serial.printf("Camera init failed with error 0x%x", err);
    return;
  }
 
  sensor_t * s = esp_camera_sensor_get();
  // initial sensors are flipped vertically and colors are a bit saturated
  if (s->id.PID == OV3660_PID) {
    s->set_vflip(s, 1); // flip it back
    s->set_brightness(s, 1); // up the brightness just a bit
    s->set_saturation(s, -2); // lower the saturation
  }
  // drop down frame size for higher initial frame rate
  //s->set_framesize(s, FRAMESIZE_QVGA);
  s->set_framesize(s, FRAMESIZE_SVGA);
 
  s->set_vflip(s, 1);
  s->set_hmirror(s, 1);
 
#if defined(CAMERA_MODEL_M5STACK_WIDE) || defined(CAMERA_MODEL_M5STACK_ESP32CAM)
  s->set_vflip(s, 1);
  s->set_hmirror(s, 1);
#endif
 
  WiFi.begin(ssid, password);
 
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.println("WiFi connected");
 
  startCameraServer();
 
  Serial.print("Camera Ready! Use 'http://");
  Serial.print(WiFi.localIP());
  Serial.println("' to connect");
 
  // 打开TCP
  ServerPort.begin();
}
 
void loop()
{
  unsigned char i = 200;
  // 等待客户端连接
  WiFiClient client = ServerPort.available();
  if (client) {
    Serial.println("New client connected");
    
    while (client.connected()) {
      // 检查是否有数据可供读取
      if (client.available()) {
        // 读取客户端发送的数据
        String data = client.readStringUntil('\n');
        Serial.print("Received data: ");
        Serial.println(data);
       

        // 发送响应到客户端
        String response = "Server received: " + data;
        client.println(response);
      }
    }
    
    // 断开与客户端的连接
    client.stop();
    Serial.println("Client disconnected");
  }
 
}

三、YOLOV5环境安装

YOLOV5采用的是5.0版本,下载源码后安装

参考:AI学习笔记二:YOLOV5环境搭建及测试全过程_yolov5 测试-CSDN博客

测试代码:

import cv2
import torch
import numpy as np
import socket
camera_url = "http://192.168.50.2:81/stream"
send_msg = "found"
# 创建socket对象
socket_client = socket.socket()
# 连接到服务器
socket_client.connect(("192.168.50.2", 1234))
# 读取yolov5模型
model = torch.hub.load('E:/desktop/ESP32_CAM/yolov5-5.0/', 'custom',
                       'E:/desktop/ESP32_CAM/yolov5-5.0/yolov5s.pt', source='local') 
# 设置模型
model.conf = 0.4
 
cap = cv2.VideoCapture(camera_url)
while True:
    ret, frame = cap.read()
    frame = cv2.flip(frame, 1)
    img_cvt = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
    results = model(img_cvt)
    # 打印得到的数据
    # print(str(results.pandas().xyxy[0].to_numpy()[:, -1]))  # tensor-to-numpy
 
    results_ = results.pandas().xyxy[0].to_numpy()
    for result in results_:
        target = result[6]
        if target != "":
            #发送消息
            socket_client.send(send_msg.encode("UTF-8"))
        print(target)
    i = 0
    # 画图
    for box in results_:
        l, t, r, b = box[:4].astype('int')
        confidence = str(round(box[4] * 100, 2)) + "%"
        cls_name = box[6]
        cv2.rectangle(frame, (l, t), (r, b), (0, 200, 55), 2)
        cv2.putText(frame, cls_name + "-" + confidence, (l, t), cv2.FONT_ITALIC, 1, (200, 55, 0), 2)
 
    cv2.imshow("result", frame)
 
    if cv2.waitKey(10) & 0xFF == ord("q"):
        break
cap.release()
cv2.destroyAllWindows()
# 关闭连接
socket_client.close()

代码需要注意的是地址,根据板子的地址,自行修改

测试结果:

四、YOLOV11测试

import cv2
import torch
import numpy as np
import socket
import cv2
from ultralytics import YOLO

camera_url = "http://192.168.1.106:81/stream"
send_msg = "found"
# 创建socket对象
socket_client = socket.socket()
# 连接到服务器
socket_client.connect(("192.168.1.106", 1234))


 
def predict(chosen_model, img, classes=[], conf=0.5):
    if classes:
        results = chosen_model.predict(img, classes=classes, conf=conf)
    else:
        results = chosen_model.predict(img, conf=conf)
 
    return results
 
def predict_and_detect(chosen_model, img, classes=[], conf=0.5, rectangle_thickness=2, text_thickness=1):
    results = predict(chosen_model, img, classes, conf=conf)
    for result in results:
        for box in result.boxes:
            cv2.rectangle(img, (int(box.xyxy[0][0]), int(box.xyxy[0][1])),
                          (int(box.xyxy[0][2]), int(box.xyxy[0][3])), (255, 0, 0), rectangle_thickness)
            cv2.putText(img, f"{result.names[int(box.cls[0])]}",
                        (int(box.xyxy[0][0]), int(box.xyxy[0][1]) - 10),
                        cv2.FONT_HERSHEY_PLAIN, 1, (255, 0, 0), text_thickness)
    return img, results
 
# defining function for creating a writer (for mp4 videos)
def create_video_writer(video_cap, output_filename):
    # grab the width, height, and fps of the frames in the video stream.
    frame_width = int(video_cap.get(cv2.CAP_PROP_FRAME_WIDTH))
    frame_height = int(video_cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
    fps = int(video_cap.get(cv2.CAP_PROP_FPS))
    # initialize the FourCC and a video writer object
    fourcc = cv2.VideoWriter_fourcc(*'MP4V')
    writer = cv2.VideoWriter(output_filename, fourcc, fps,
                             (frame_width, frame_height))
    return writer
 
model = YOLO("G:/enpei_Project_Code/ESP32_CAM/yolo11s.pt")

 
cap = cv2.VideoCapture(camera_url)
while True:
    success, img = cap.read()
    if not success:
        break
    result_img, _ = predict_and_detect(model, img, classes=[], conf=0.5)
    # 打印得到的数据
    # print(str(results.pandas().xyxy[0].to_numpy()[:, -1]))  # tensor-to-numpy
 
    cv2.imshow("Image", result_img)

 
    if cv2.waitKey(10) & 0xFF == ord("q"):
        break
cap.release()
cv2.destroyAllWindows()
# 关闭连接
socket_client.close()

这个只是个demo测试,还是想实现如果使用APP显示。

如有侵权,或需要完整代码,请及时联系博主。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2386673.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

免费分享50本web全栈学习电子书

最近搞到一套非常不错的 Web 全栈电子书合集&#xff0c;整整 50 本&#xff0c;都是epub电子书格式&#xff0c;相当赞&#xff01;作为一个被期末大作业和项目 ddl 追着跑的大学生&#xff0c;这套书真的救我狗命&#xff01; 刚接触 Web 开发的时候&#xff0c;我天天对着空…

【prometheus+Grafana篇】基于Prometheus+Grafana实现MySQL数据库的监控与可视化

&#x1f4ab;《博主主页》&#xff1a; &#x1f50e; CSDN主页 &#x1f50e; IF Club社区主页 &#x1f525;《擅长领域》&#xff1a;擅长阿里云AnalyticDB for MySQL(分布式数据仓库)、Oracle、MySQL、Linux、prometheus监控&#xff1b;并对SQLserver、NoSQL(MongoDB)有了…

全链路解析:影刀RPA+Coze API自动化工作流实战指南

在数字化转型加速的今天&#xff0c;如何通过RPA与API的深度融合实现业务自动化提效&#xff0c;已成为企业降本增效的核心命题。本文以「影刀RPA」与「Coze API」的深度协作为例&#xff0c;系统性拆解从授权配置、数据交互到批量执行的完整技术链路&#xff0c;助你快速掌握跨…

高阶数据结构——哈希表的实现

目录 1.概念引入 2.哈希的概念&#xff1a; 2.1 什么叫映射&#xff1f; 2.2 直接定址法 2.3 哈希冲突&#xff08;哈希碰撞&#xff09; 2.4 负载因子 2.5 哈希函数 2.5.1 除法散列法&#xff08;除留余数法&#xff09; 2.5.2 乘法散列法&#xff08;了解&#xff09…

2025 年网络安全趋势报告

一、引言 自欧洲信息安全协会&#xff08;Infosecurity Europe&#xff09;首次举办活动的 30 年来&#xff0c;网络安全格局发生了翻天覆地的变化。如今&#xff0c;网络安全领导者必须应对众多威胁&#xff0c;维持法规合规性&#xff0c;并与董事会成员合作推进组织的网络安…

uniapp 条件筛选

v3 版本 <template><view class"store flex "><view class"store_view"><view class"store_view_search flex jsb ac"><!-- <view class"store_view_search_select">全部</view> --><v…

pytorch问题汇总

conda环境下 通过torch官网首页 pip安装 成功运行 后面通过conda安装了别的包 似乎因为什么版本问题 就不能用了 packages\torch_init_.py", line 245, in _load_dll_libraries raise err OSError: [WinError 127] 找不到指定的程序。 Error loading ackages\torch\lib\c…

开发过的一个Coding项目

一、文档资料、人员培训&#xff1a; 1、文档资料管理&#xff1a;这个可以使用OnLineHelpDesk。 2、人员培训&#xff1a;可以参考Is an Online Medical Billing and Coding Program Right for You - MedicalBillingandCoding.org。 3、人员招聘、考核&#xff1a;可以在Onli…

数据仓库维度建模详细过程

数据仓库的维度建模&#xff08;Dimensional Modeling&#xff09;是一种以业务用户理解为核心的设计方法&#xff0c;通过维度表和事实表组织数据&#xff0c;支持高效查询和分析。其核心目标是简化复杂业务逻辑&#xff0c;提升查询性能。以下是维度建模的详细过程&#xff1…

python打卡day37

早停策略和模型权重保存 知识点回顾&#xff1a; 过拟合的判断&#xff1a;测试集和训练集同步打印指标模型的保存和加载 仅保存权重保存权重和模型保存全部信息checkpoint&#xff0c;还包含训练状态 早停策略 是否过拟合&#xff0c;可以通过同步打印训练集和测试集的loss曲线…

各个网络协议的依赖关系

网络协议的依赖关系 学习网络协议之间的依赖关系具有多方面重要作用&#xff0c;具体如下&#xff1a; 帮助理解网络工作原理 - 整体流程明晰&#xff1a;网络协议分层且相互依赖&#xff0c;如TCP/IP协议族&#xff0c;应用层协议依赖传输层的TCP或UDP协议来传输数据&#…

OSC协议简介、工作原理、特点、数据的接收和发送

OSC协议简介 Open Sound Control&#xff08;OSC&#xff09; 是一种开放的、独立于传输的基于消息的协议&#xff0c;主要用于计算机、声音合成器和其他多媒体设备之间的通信。它提供了一种灵活且高效的方式来发送和接收参数化消息&#xff0c;特别适用于实时控制应用&#x…

区块链可投会议CCF C--APSEC 2025 截止7.13 附录用率

Conference&#xff1a;32nd Asia-Pacific Software Engineering Conference (APSEC 2025) CCF level&#xff1a;CCF C Categories&#xff1a;软件工程/系统软件/程序设计语言 Year&#xff1a;2025 Conference time&#xff1a;December 2-5, 2025 in Macao SAR, China …

【数字图像处理】_笔记

第一章 概述 1.1 什么是数字图像&#xff1f; 图像分为两大类&#xff1a;模拟图像与数字图像 模拟图像&#xff1a;通过某种物理&#xff08;光、电&#xff09;的强弱变化来记录图像上各个点的亮度信息 连续&#xff1a;从空间上和数值上是不间断的 举例&…

从0开始学习R语言--Day10--时间序列分析数据

在数据分析中&#xff0c;我们经常会看到带有时间属性的数据&#xff0c;比如股价波动&#xff0c;各种商品销售数据&#xff0c;网站的网络用户活跃度等。一般来说&#xff0c;根据需求我们会分为两种&#xff0c;分析历史数据的特点和预测未来时间段的数据。 移动平均 移动平…

基于开源链动2+1模式AI智能名片S2B2C商城小程序的产品驱动型增长策略研究

摘要&#xff1a;在数字化经济时代&#xff0c;产品驱动型增长&#xff08;Product-Led Growth, PLG&#xff09;已成为企业突破流量瓶颈、实现用户裂变的核心战略。本文以“开源链动21模式AI智能名片S2B2C商城小程序”&#xff08;以下简称“链动AI-S2B2C系统”&#xff09;为…

使用 OpenCV 实现“随机镜面墙”——多镜片密铺的哈哈镜效果

1. 引言 “哈哈镜”是一种典型的图像变形效果&#xff0c;通过局部镜面反射产生扭曲的视觉趣味。在计算机视觉和图像处理领域&#xff0c;这类效果不仅有趣&#xff0c;还能用于艺术创作、交互装置、视觉特效等场景。 传统的“哈哈镜”往往是针对整张图像做某种镜像或扭曲变换…

鸿蒙仓颉开发语言实战教程:页面跳转和传参

前两天分别实现了商城应用的首页和商品详情页面&#xff0c;今天要分享新的内容&#xff0c;就是这两个页面之间的相互跳转和传递参数。 首先我们需要两个页面。如果你的项目中还没有第二个页面&#xff0c;可以右键cangjie文件夹新建仓颉文件&#xff1a; 新建的文件里面没什…

最新Spring Security实战教程(十六)微服务间安全通信 - JWT令牌传递与校验机制

&#x1f337; 古之立大事者&#xff0c;不惟有超世之才&#xff0c;亦必有坚忍不拔之志 &#x1f390; 个人CSND主页——Micro麦可乐的博客 &#x1f425;《Docker实操教程》专栏以最新的Centos版本为基础进行Docker实操教程&#xff0c;入门到实战 &#x1f33a;《RabbitMQ》…

【五】Spring Cloud微服务开发:解决版本冲突全攻略

Spring Cloud微服务开发&#xff1a;解决版本冲突全攻略 目录 Spring Cloud微服务开发&#xff1a;解决版本冲突全攻略 概述 一、Spring Boot 二、Spring Cloud 三、Spring Cloud Alibaba 总结 概述 spring cloud微服务项目开发过程中经常遇到程序包版本冲突的问题&…