树莓派应用--AI项目实战篇来啦-9.OpenCV实现汽车检测

1.介绍

该项目使用的汽车检测使用的也是 haar 模型。这是一种基于机器学习的汽车检测算法。它使用了 Haar 特征来检测汽车,可以在图像中快速检测到汽车并输出其位置。采用该方法检测速度较快,但准确率略低。

2.OpenCV 实现汽车检测

可以采用官方自带的汽车检测 HAAR 分类器实现对视频的汽车检测,也可以自己改成摄像头的方式。

3.源程序代码

python 复制代码
# 载入必要的库
import cv2
import time
import numpy as np

# 载入HAAR分类器
car_classifier = cv2.CascadeClassifier('./images/haarcascade_car.xml')
# 载入视频文件
cap = cv2.VideoCapture('./images/cars.avi')

# 线程函数操作库
import threading # 线程
import ctypes
import inspect

# 线程结束代码
def _async_raise(tid, exctype):
    tid = ctypes.c_long(tid)
    if not inspect.isclass(exctype):
        exctype = type(exctype)
    res = ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, ctypes.py_object(exctype))
    if res == 0:
        raise ValueError("invalid thread id")
    elif res != 1:
        ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, None)
        raise SystemError("PyThreadState_SetAsyncExc failed")
        
def stop_thread(thread):
    _async_raise(thread.ident, SystemExit)

# 创建显示控件
def bgr8_to_jpeg(value, quality=75):
    return bytes(cv2.imencode('.jpg', value)[1])
    
import traitlets
import ipywidgets.widgets as widgets
from IPython.display import display
car_imge = widgets.Image(format='jpeg', width=480, height=320)
display(car_imge)

#一旦视频成功加载,循环播放
def car_Video_display():
    while cap.isOpened():
        time.sleep(.05)
        # Read first frame
        ret, frame = cap.read()
        gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
        
        # Pass frame to our car classifier
        cars = car_classifier.detectMultiScale(gray, 1.4, 2)       
        # Extract bounding boxes for any bodies identified
        for (x,y,w,h) in cars:
            cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 255, 255), 2)
            car_imge.value = bgr8_to_jpeg(frame)
    cap.release()

t = threading.Thread(target=car_Video_display)
t.setDaemon(True)
t.start()

# 结束线程
stop_thread(t)
相关推荐
淬炼之火1 分钟前
图文跨模态融合基础 3:基于Windows和WSL构建LLaVA(视觉语言模型)研究环境
人工智能·语言模型·自然语言处理
方见华Richard3 分钟前
递归对抗引擎RAE:世毫九重构AGI底层逻辑的终极范式与全维度价值极致解读
人工智能·交互·学习方法·原型模式·空间计算
Agent_阿杨3 分钟前
智能体来了(西南总部):如何成为智能体行业的领航员
大数据·人工智能
LS_learner15 分钟前
Clawdbot介绍与平台部署
人工智能
大傻^16 分钟前
大模型基础知识-神经网络
人工智能·深度学习·神经网络
小程故事多_8018 分钟前
平台工程工具,解锁研发效能的核心密码
人工智能·aigc
多恩Stone18 分钟前
【3DV 进阶-12】Trellis.2 数据处理脚本细节
人工智能·pytorch·python·算法·3d·aigc
vx-bot55566620 分钟前
企业微信接口在AI智能体与知识库集成中的架构实践
人工智能·架构·企业微信
生成论实验室21 分钟前
生成式通用智能(GAGI):基于《易经》状态空间的认知架构
人工智能·神经网络·算法·架构·信息与通信
丝斯201121 分钟前
AI学习笔记整理(69)——物理AI中世界模型
人工智能·笔记·学习