OpenCV中文网站

 找回密码
 立即注册
搜索
热搜: 安装 配置
12
返回列表 发新帖
楼主: zdyy

车辆检测、车型识别、年检标检测等

[复制链接]
发表于 2019-10-22 14:41:40 | 显示全部楼层
能不能在交叉口识别车辆,获取轨迹和速度?
回复 支持 反对

使用道具 举报

 楼主| 发表于 2019-10-22 18:43:37 | 显示全部楼层
轨迹是有的,但是速度没有进行开发
回复 支持 反对

使用道具 举报

发表于 2019-10-31 20:34:14 | 显示全部楼层
看看这个了《一、多车辆识别可能和车辆车牌分割;》
https://www.cnblogs.com/jsxyhelu/p/11392219.html
回复 支持 反对

使用道具 举报

发表于 2019-10-31 20:35:11 | 显示全部楼层
图片
回复 支持 反对

使用道具 举报

发表于 2019-10-31 20:35:17 | 显示全部楼层
本帖最后由 jsxyheu2014 于 2019-10-31 20:36 编辑

基于OpenVINO
#include <algorithm>
#include <fstream>
#include <iomanip>
#include <vector>
#include <string>
#include <chrono>
#include <memory>
#include <utility>

#include <format_reader_ptr.h>
#include <inference_engine.hpp>
#include <ext_list.hpp>

#include <samples/slog.hpp>
#include <samples/ocv_common.hpp>
#include "segmentation_demo.h"

using namespace InferenceEngine;
using namespace std;
using namespace cv;

//从图片中获得车和车牌(这里没有输出模型的定位结果,如果需要可以适当修改)
vector< pair<Mat, Mat> > GetCarAndPlate(Mat src)
{
    vector<pair<Mat, Mat>> resultVector;
    // 模型准备
    InferencePlugin plugin(PluginDispatcher().getSuitablePlugin(TargetDevice::eCPU));
    plugin.AddExtension(std::make_shared<Extensions::Cpu::CpuExtensions>());//Extension,useful
    //读取模型(xml和bin
    CNNNetReader networkReader;
    networkReader.ReadNetwork("E:/OpenVINO_modelZoo/vehicle-license-plate-detection-barrier-0106.xml");
    networkReader.ReadWeights("E:/OpenVINO_modelZoo/vehicle-license-plate-detection-barrier-0106.bin");
    CNNNetwork network = networkReader.getNetwork();
    network.setBatchSize(1);
    // 输入输出准备
    InputsDataMap inputInfo(network.getInputsInfo());//获得输入信息
    if (inputInfo.size() != 1) throw std::logic_error("错误,该模型应该为单输入");
    string inputName = inputInfo.begin()->first;

    OutputsDataMap outputInfo(network.getOutputsInfo());//获得输出信息                                      
    DataPtr& _output = outputInfo.begin()->second;
    const SizeVector outputDims = _output->getTensorDesc().getDims();
    string firstOutputName = outputInfo.begin()->first;
    int maxProposalCount = outputDims[2];
    int objectSize = outputDims[3];
    if (objectSize != 7) {
        throw std::logic_error("Output should have 7 as a last dimension");
    }
    if (outputDims.size() != 4) {
        throw std::logic_error("Incorrect output dimensions for SSD");
    }
    _output->setPrecision(Precision::FP32);
    _output->setLayout(Layout::NCHW);

    // 模型读取和推断
    ExecutableNetwork executableNetwork = plugin.LoadNetwork(network, {});
    InferRequest infer_request = executableNetwork.CreateInferRequest();

    Blob::Ptr lrInputBlob = infer_request.GetBlob(inputName); //data这个名字是我看出来的,实际上这里可以更统一一些
    matU8ToBlob<float_t>(src, lrInputBlob, 0);//重要的转换函数,第3个参数是batchSize,应该是自己+1的

    infer_request.Infer();
    // --------------------------- 8. 处理结果-------------------------------------------------------
    const float *detections = infer_request.GetBlob(firstOutputName)->buffer().as<float *>();
    int i_car = 0;
    int i_plate = 0;
    for (int i = 0; i < 200; i++)
    {
        float confidence = detections[i * objectSize + 2];
        float x_min = static_cast<int>(detections[i * objectSize + 3] * src.cols);
        float y_min = static_cast<int>(detections[i * objectSize + 4] * src.rows);
        float x_max = static_cast<int>(detections[i * objectSize + 5] * src.cols);
        float y_max = static_cast<int>(detections[i * objectSize + 6] * src.rows);
        Rect rect = cv::Rect(cv::Point(x_min, y_min), cv::Point(x_max, y_max));
        if (confidence > 0.5)
        {
            if (rect.width > 150)//车辆
            {
                Mat roi = src(rect);
                pair<Mat, Mat> aPair;
                aPair.first = roi.clone();
                resultVector.push_back(aPair);
                i_car++;
            }
            else//车牌
            {
                Mat roi = src(rect);
                resultVector[i_plate].second = roi.clone();
                i_plate++;
            }

        }
    }
    return resultVector;
}
//从车的图片中识别车型
pair<string,string> GetCarAttributes(Mat src)
{
    pair<string, string> resultPair;
    // --------------------------- 1.为IE准备插件-------------------------------------
    InferencePlugin plugin(PluginDispatcher().getSuitablePlugin(TargetDevice::eCPU));
    printPluginVersion(plugin, std::cout);//正确回显表示成功
    plugin.AddExtension(std::make_shared<Extensions::Cpu::CpuExtensions>());//Extension,useful
    // --------------------------- 2.读取IR模型(xml和bin)---------------------------------
    CNNNetReader networkReader;
    networkReader.ReadNetwork("E:/OpenVINO_modelZoo/vehicle-attributes-recognition-barrier-0039.xml");
    networkReader.ReadWeights("E:/OpenVINO_modelZoo/vehicle-attributes-recognition-barrier-0039.bin");
    CNNNetwork network = networkReader.getNetwork();
    // --------------------------- 3. 准备输入输出的------------------------------------------
    InputsDataMap inputInfo(network.getInputsInfo());//获得输入信息
    BlobMap inputBlobs; //保持所有输入的blob数据
    if (inputInfo.size() != 1) throw std::logic_error("错误,该模型应该为单输入");

    auto lrInputInfoItem = *inputInfo.begin();//开始读入
    int w = static_cast<int>(lrInputInfoItem.second->getTensorDesc().getDims()[3]); //这种写法也是可以的,它的first就是data
    int h = static_cast<int>(lrInputInfoItem.second->getTensorDesc().getDims()[2]);   
    network.setBatchSize(1);//只有1副图片,故BatchSize = 1
    // --------------------------- 4. 读取模型 ------------------------------------------(后面这些操作应该可以合并了)
    ExecutableNetwork executableNetwork = plugin.LoadNetwork(network, {});
    // --------------------------- 5. 创建推断 -------------------------------------------------
    InferRequest infer_request = executableNetwork.CreateInferRequest();
    // --------------------------- 6. 将数据塞入模型 -------------------------------------------------
    Blob::Ptr lrInputBlob = infer_request.GetBlob("input"); //data这个名字是我看出来的,实际上这里可以更统一一些
    matU8ToBlob<float_t>(src, lrInputBlob, 0);//重要的转换函数,第3个参数是batchSize,应该是自己+1的

    // --------------------------- 7. 推断结果 -------------------------------------------------
    infer_request.Infer();//多张图片多次推断

    // --------------------------- 8. 处理结果-------------------------------------------------------
     // 7 possible colors for each vehicle and we should select the one with the maximum probability
    auto colorsValues = infer_request.GetBlob("color")->buffer().as<float*>();
    // 4 possible types for each vehicle and we should select the one with the maximum probability
    auto typesValues = infer_request.GetBlob("type")->buffer().as<float*>();

    const auto color_id = std::max_element(colorsValues, colorsValues + 7) - colorsValues;
    const auto type_id = std::max_element(typesValues, typesValues + 4) - typesValues;

    static const std::string colors[] = {
             "white", "gray", "yellow", "red", "green", "blue", "black"
    };
    static const std::string types[] = {
            "car", "bus", "truck", "van"
    };

    resultPair.first = colors[color_id];
    resultPair.second = types[type_id];

    return resultPair;

}
//识别车牌
string GetPlateNumber(Mat src)
{
    // --------------------------- 1.为IE准备插件-------------------------------------
    InferencePlugin plugin(PluginDispatcher().getSuitablePlugin(TargetDevice::eCPU));
    plugin.AddExtension(std::make_shared<Extensions::Cpu::CpuExtensions>());//Extension,useful
    // --------------------------- 2.读取IR模型(xml和bin)---------------------------------
    CNNNetReader networkReader;
    networkReader.ReadNetwork("E:/OpenVINO_modelZoo/license-plate-recognition-barrier-0001.xml");
    networkReader.ReadWeights("E:/OpenVINO_modelZoo/license-plate-recognition-barrier-0001.bin");
    CNNNetwork network = networkReader.getNetwork();
    network.setBatchSize(1);//只有1副图片,故BatchSize = 1
    // --------------------------- 3. 准备输入输出的------------------------------------------
    InputsDataMap inputInfo(network.getInputsInfo());//获得输入信息
    BlobMap inputBlobs; //保持所有输入的blob数据
    string    inputSeqName;

    if (inputInfo.size() == 2) {
        auto sequenceInput = (++inputInfo.begin());
        inputSeqName = sequenceInput->first;
    }
    else if (inputInfo.size() == 1) {
        inputSeqName = "";
    }
    else {
        throw std::logic_error("LPR should have 1 or 2 inputs");
    }

    InputInfo::Ptr& inputInfoFirst = inputInfo.begin()->second;
    inputInfoFirst->setInputPrecision(Precision::U8);
    string inputName = inputInfo.begin()->first;

    //准备输出数据
    OutputsDataMap outputInfo(network.getOutputsInfo());//获得输出信息            
    if (outputInfo.size() != 1) {
        throw std::logic_error("LPR should have 1 output");
    }
    string firstOutputName = outputInfo.begin()->first;

    DataPtr& _output = outputInfo.begin()->second;
    const SizeVector outputDims = _output->getTensorDesc().getDims();

    // --------------------------- 4. 读取模型 ------------------------------------------(后面这些操作应该可以合并了)
    ExecutableNetwork executableNetwork = plugin.LoadNetwork(network, {});
    // --------------------------- 5. 创建推断 -------------------------------------------------
    InferRequest infer_request = executableNetwork.CreateInferRequest();
    // --------------------------- 6. 将数据塞入模型 -------------------------------------------------
    Blob::Ptr lrInputBlob = infer_request.GetBlob(inputName); //data这个名字是我看出来的,实际上这里可以更统一一些
    matU8ToBlob<uint8_t>(src, lrInputBlob, 0);//重要的转换函数,第3个参数是batchSize,应该是自己+1的

    // --------------------------- 7. 推断结果 -------------------------------------------------
    infer_request.Infer();//多张图片多次推断
    // --------------------------- 8. 处理结果-------------------------------------------------------
    static std::vector<std::string> items = {
          "0", "1", "2", "3", "4", "5", "6", "7", "8", "9",
          "<Anhui>", "<Beijing>", "<Chongqing>", "<Fujian>",
          "<Gansu>", "<Guangdong>", "<Guangxi>", "<Guizhou>",
          "<Hainan>", "<Hebei>", "<Heilongjiang>", "<Henan>",
          "<HongKong>", "<Hubei>", "<Hunan>", "<InnerMongolia>",
          "<Jiangsu>", "<Jiangxi>", "<Jilin>", "<Liaoning>",
          "<Macau>", "<Ningxia>", "<Qinghai>", "<Shaanxi>",
          "<Shandong>", "<Shanghai>", "<Shanxi>", "<Sichuan>",
          "<Tianjin>", "<Tibet>", "<Xinjiang>", "<Yunnan>",
          "<Zhejiang>", "<police>",
          "A", "B", "C", "D", "E", "F", "G", "H", "I", "J",
          "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T",
          "U", "V", "W", "X", "Y", "Z"
    };

    const auto data = infer_request.GetBlob(firstOutputName)->buffer().as<float*>();
    std::string result;
    for (size_t i = 0; i < 88; i++) {
        if (data == -1)
            break;
        result += items[static_cast<size_t>(data)];
    }
    return result;
}

void main()
{
    string imageNames = "E:/OpenVINO_modelZoo/沪A51V39.jpg";
    Mat src = imread(imageNames);
    if (src.empty())
        return;

    vector<pair<Mat, Mat>> CarAndPlateVector = GetCarAndPlate(src);
    for (int i=0;i<CarAndPlateVector.size();i++)
    {
        pair<Mat, Mat> aPair = CarAndPlateVector;
        pair<string, string> ColorAndType = GetCarAttributes(aPair.first);
        string PlateNumber = GetPlateNumber(aPair.second);
        cout << ColorAndType.first <<"  "<<ColorAndType.second <<"   "<< PlateNumber << endl;
    }

    cv::waitKey();

}
回复 支持 反对

使用道具 举报

发表于 2019-12-23 21:22:50 | 显示全部楼层
怎么联系到你呢?楼主!
我的联系方式  289198055@qq.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

手机版|OpenCV中文网站

GMT+8, 2024-3-29 20:29 , Processed in 0.011550 second(s), 13 queries .

Powered by Discuz! X3.4

Copyright © 2001-2021, Tencent Cloud.

快速回复 返回顶部 返回列表