树莓派应用--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)
相关推荐
学好statistics和DS1 小时前
【CV】神经网络中哪些参数需要被学习?
人工智能·神经网络·学习
大千AI助手1 小时前
机器学习特征筛选中的IV值详解:原理、应用与实现
人工智能·机器学习·kl散度·roc·iv·信息值·woe
姜—姜1 小时前
通过构建神经网络实现项目预测
人工智能·pytorch·深度学习·神经网络
Ro Jace1 小时前
模式识别与机器学习课程笔记(4):线性判决函数
人工智能·笔记·机器学习
科研小白_2 小时前
基于遗传算法优化BP神经网络(GA-BP)的数据时序预测
人工智能·算法·回归
互联网江湖3 小时前
蓝桥杯出局,少儿编程的价值祛魅时刻?
人工智能·生活
Elastic 中国社区官方博客3 小时前
根据用户行为数据中的判断列表在 Elasticsearch 中训练 LTR 模型
大数据·数据库·人工智能·elasticsearch·搜索引擎·ai·全文检索
paid槮4 小时前
OpenCV图像形态学详解
人工智能·opencv·计算机视觉
点控云4 小时前
点控云智能短信:重构企业与用户的连接,让品牌沟通更高效
大数据·人工智能·科技·重构·外呼系统·呼叫中心
救救孩子把7 小时前
14-机器学习与大模型开发数学教程-第1章 1-6 费马定理与极值判定
人工智能·数学·机器学习