树莓派应用--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)
相关推荐
千里码aicood32 分钟前
[含文档+PPT+源码等]精品基于springboot实现的原生微信小程序汽车保养服务
spring boot·微信小程序·汽车
PaLu-LI1 小时前
ORB-SLAM2之OpenCV reshape函数
开发语言·c++·opencv·学习·ubuntu
吃什么芹菜卷1 小时前
机器学习:opencv--人脸检测以及微笑检测
人工智能·opencv·机器学习
子午1 小时前
【交通标志识别系统】Python+卷积神经网络算法+人工智能+深度学习+机器学习+算法模型
人工智能·深度学习·机器学习
工作姬1 小时前
《柬埔寨语翻译通》App是如何实现高棉语语音识别翻译技术的,高精度OCR文字识别技术分享!
人工智能·ocr·语音识别·柬埔寨·柬埔寨语·高棉语·柬埔寨语翻译
kejijianwen1 小时前
端到端语音大模型上线,Soul App创始人张璐团队提升用户语音互动体验
人工智能
沈询-阿里1 小时前
用Spring AI 做智能客服,基于私有知识库和RAG技术
java·人工智能·spring
强哥之神1 小时前
大型语言模型(LLMs)关键技术指南
人工智能·深度学习·机器学习·语言模型·自然语言处理·llm·llama
还在抒写2 小时前
西瓜书机器学习第五章——神经网络
人工智能·神经网络·机器学习
GISer Liu2 小时前
AI金融攻防赛:YOLO理论学习及赛题代码进阶(DataWhale组队学习)
人工智能·python·算法·yolo·leetcode·金融·目标识别