矩视智能AI视觉软件-检测环境与预测(C++)

如何检测

  • 将两个文件检测环境.exe和检查Env.bat放在SDK的bin文件夹中。
  • 在你的命令行中运行这个exe,有一个示例
  • detectEnvironmetnAndPreedict.exe -m C:\\NeuroBot\\ModelPath -f C:\\NeuroBot\\FilePath -n ModelName
  • 在 -m 之后,它是计算机中的模型路径。
  • 在 -f 之后,它是图片的字典。
  • 在 -n 之后,它是模型的名称,您可以自己命名。

作用

  • 可以检测计算机是否能够使用模型,包括以下信息。前三个是必要的,其他的推荐。
    • 配置文件和模型文件存在。
    • Windows 64位版本系统。
    • 已安装 NVIDIA 显卡和驱动程序。
    • 关闭防火墙和防病毒软件。
    • CPU采用英特尔主频2.5GHZ 6核及以上版本。
    • 系统内存大于 8GB。
  • 用我们的可执行文件进行预测。使用命令行参数接受模型文件和测试图片目录的输入。参数支持默认值。如果没有参数,请使用默认模型文件名和测试图片目录名称。
  • 可以加载预测目录图片的模型、显示测试图片的弹出窗口和显示结果框的覆盖,同时在控制台上记录特定值。

检查环境

@echo off
setlocal enabledelayedexpansion
chcp 437
path %path%;C:\Windows\System32\wbem
path %path%;C:\WINDOWS\System32\Wbem
path %path%;C:\WINDOWS\System32

set Ret1=0

for /f %%i in ('where.exe nvidia-smi.exe') do (
for /f "tokens=* delims=," %%i in ('nvidia-smi.exe ^|findstr "Version:"') do (
set Ret1=1
)
)

set rootSource=C:\Progra~1\NVIDIA~1\NVSMI\nvidia-smi.exe
set Source=C:\Program Files\NVIDIA Corporation\NVSMI\nvidia-smi.exe
if exist %Source%(
for /f "tokens=* delims=," %%i in (' %rootSource% ^|findstr "Version:"') do (
set Ret1=1
)
)

rem 是否是英伟达显卡
echo Is NVIDIA:
echo !Ret1!
echo.
rem 在exe内做检测
set Ret2=1

set Ret3=0
for /f %%i in ('wmic os get osarchitecture^|findstr "64"') do (
set Ret3=1
)

rem win是否是64位
echo Is Windows 64
echo !Ret3!
echo.
set Ret4=1
for /f "tokens=* delims=," %%i in ('netsh advfirewall show allprofiles^|findstr "State*"^|findstr "ON" ') do (
set Ret4=0
)
rem 是否关闭防火墙
echo Is ClosedNetWall
echo !Ret4!
echo.
echo.

set Ret5=0
for /f "tokens=* delims=," %%i in ('systeminfo ^|findstr "Windows.10" ') do (
set Ret5=1
)

for /f "tokens=* delims=," %%i in ('systeminfo ^|findstr "Windows.11" ') do (
set Ret5=1
)
rem 是否是win10/win11
echo Is Windows 64V10/11
echo !Ret5!

echo.

set Ret6=0

for /f "tokens=* delims=," %%i in ('wmic cpu list brief^|findstr "GHz"') do (
set tm1=%%i
)

for /f "tokens=16" %%i in ('echo !tm1! ') do (
set tm2=%%i
)
for /f "delims=0G" %%i in ('echo !tm2!') do (
set tm5=%%i

for /f "tokens=17" %%i in ('echo !tm1! ') do (
set tex1=%%i
)
for /f "delims=0G" %%i in ('echo !tex1!') do (
set tex2=%%i


echo Two results:
echo !tm5!
echo !tex2!

echo.

for /f "tokens=1" %%i in ('echo !tm1! ') do (
set tm3=%%i
)
set tm4=!tm3:~0,5%!
echo Intel:
echo !tm3!
echo.
for /f "tokens=1 delims=" %%i in ('wmic cpu get NumberOfCores^|findstr "[0-9]" ') do (
set tm6=%%i
)
echo CPU Core:
echo !tm6!
echo.

if !tm4! EQU Intel (set /a Ret6+=1)
if !tm5! GEQ 2.5 (set /a Ret6+=1)
if !tex2! GEQ 2.5 (set /a Ret6+=1)
if !tm6! GEQ 6 (set /a Ret6+=1)

echo Ret6sum:
echo !Ret6!
echo.
set tth=!Ret6!

if !tth! GEQ 3.0 (set Ret6=1)
if !tth! LSS 3.0 (set Ret6=0)

rem CPU为intel,主频大于2.5,6核心_Re6
echo Is CPU OK
echo !Ret6!

echo.

set Ret7=1

for /f "tokens=* delims=," %%i in ('systeminfo ^|findstr "Virtual.Memory:.Available.*"') do (
set tmpa=%%i
)

for /f "tokens=3 delims=:" %%i in ('echo !tmpa! ') do (
set tmpb=%%i
)

for /f "tokens=1 delims=,M" %%i in ('echo !tmpb!') do (
set tempc=%%i
set tempd=!tempc:~1!
)

for /f "tokens=2 delims=,M" %%i in ('echo !tmpb!') do (
set tempe=%%i
)

set /a tmpg=(!tempd!*1000)+!tempe!

if !tmpg! LSS 8192 (set Ret7=0)

rem 系统内存大于8GB
echo Memory Available 8GB:
echo !Ret7!
echo.
set ShenDuXue=0

if not exist .\deploy\template.json ( goto dump )

for /f "tokens=* delims=,:}]" %%i in ('findstr "ocr" .\deploy\template.json') do (
set ShenDuXue=1
)
for /f "tokens=* delims=,:}]" %%i in ('findstr "detection" .\deploy\template.json') do (
set ShenDuXue=1
)
for /f "tokens=* delims=,:}]" %%i in ('findstr "segmentation" .\deploy\template.json') do (
set ShenDuXue=1
)
for /f "tokens=* delims=,:}]" %%i in ('findstr "label_compute" .\deploy\template.json') do (
set ShenDuXue=1
)

:dump
echo Deep Learning:
echo !ShenDuXue!
echo.
echo=>./checked.json
type nul > ./checked.json
echo {>>./checked.json
echo "required":[>>./checked.json
if !ShenDuXue!==0 ( goto dump2 )
echo will check the GPU
echo {>>./checked.json
echo "name":"Is NVIDIA graphics card and driver installed",>>./checked.json
echo "status":!Ret1!,>>./checked.json
echo "key":"isNVIDIA",>>./checked.json
echo "info":"Low code development utilizes deep learning operators. Please check if the computer is equipped with a NVIDIA graphics card and install the relevant drivers correctly">>./checked.json
echo },>>./checked.json
:dump2
echo {>>./checked.json
echo "name":"Does the configuration file or model file exist",>>./checked.json
echo "status":!Ret2!,>>./checked.json
echo "key":"isFileNeed",>>./checked.json
echo "info":"Please copy the downloaded low code development components and models (if there are deep learning operators in the process) to the corresponding folder of the specified deployment package according to the operation manual. The model file needs to be renamed according to the manual requirements. The operation manual can be found in the 2DLowCodeGuide.pdf folder in the deployment package under 'readme'">>./checked.json
echo },>>./checked.json

echo {>>./checked.json
echo "name":"Is the system a Windows 64 bit version",>>./checked.json
echo "status":!Ret3!,>>./checked.json
echo "key":"isWindows64",>>./checked.json
echo "info":"The system does not support Windows 32-bit version. Please replace the system running Windows 64 bit and try again">>./checked.json
echo }>>./checked.json
echo ],>>./checked.json

echo "recommend":[>>./checked.json

echo {>>./checked.json
echo "name":"Turn off firewall or antivirus software",>>./checked.json
echo "status":!Ret4!,>>./checked.json
echo "key":"isClosedNetWall",>>./checked.json
echo "info":"Firewalls or antivirus software may accidentally kill the software or restrict communication. Please add the entire folder of this software, as well as the main programs (noncode. exe, nginx. exe) to the antivirus software whitelist; Or temporarily close the firewall or antivirus software">>./checked.json
echo },>>./checked.json

echo {>>./checked.json
echo "name":"The system is a Windows 10/11 64 bit version",>>./checked.json
echo "status":!Ret5!,>>./checked.json
echo "key":"isWindows64V10",>>./checked.json
echo "info":"This software cannot guarantee compatibility with Windows versions other than Windows 10/11. Please choose the system carefully">>./checked.json
echo },>>./checked.json

echo {>>./checked.json
echo "name":"CPU with Intel main frequency 2.5GHZ 6-core and above versions",>>./checked.json
echo "status":!Ret6!,>>./checked.json
echo "key":"Is CPU OK",>>./checked.json
echo "info":"If the CPU configuration is too low, it may cause slow detection speed or abnormal operation. Suggest choosing a machine with a higher CPU configuration">>./checked.json
echo },>>./checked.json

echo {>>./checked.json
echo "name":"System memory greater than 8GB",>>./checked.json
echo "status":!Ret7!,>>./checked.json
echo "key":"Memory Available 8GB:",>>./checked.json
echo "info":"If the memory capacity is too small, it may cause slow detection speed or abnormal operation. Suggest choosing a machine with larger memory capacity">>./checked.json
echo }>>./checked.json

echo ]>>./checked.json
echo }>>./checked.json

rem check exist

if not exist .checkSetting.json (
echo=>./checkSetting.json
echo {"checkConfigure":{"ignoreRecommend":0,"isAutoEntrance":0}} >>./checkSetting.json
)

检查环境以及预测

#pragma comment(lib,"Msi.lib")
#define _SILENCE_EXPERIMENTAL_FILESYSTEM_DEPRECATION_WARNING
#include <iostream>
#include <string>d
#include <stdlib.h>
#include <fstream>
#include <typeinfo>
#include <typeindex>
#include <json/json.h>
#include <Windows.h>
#include <experimental/filesystem>
#include <iostream>
#include <direct.h>
#include <vector>
#include <neuro_core.h>
#include <opencv2/opencv.hpp>
#include "putTextZH.h"
#include <Windows.h>
#include <msi.h>
#include "clipp.h"

using namespace std;
using namespace clipp;
namespace fs = experimental::filesystem;


// Get all the files's names in the dictionary, and the result will be put into the parameter vFileNames.
// 
// Parameters
// 
//         dir           [IN]           the name of dictionary.
//         vFileNames    [OUT]          the result will be put into it.
//         extension     [IN]           ZERO means having extension, such as A.jpg.
//                                      ONE means having no extension, such as A.
//  
// Returns  
//         The size of all the files.      


int getFilesName(const std::string dir, std::vector<std::string>& vFileNames, bool extension = 1)
{
    for (const auto& entry : fs::directory_iterator(dir))
    {
        if (1 == extension)
        {
            // with extension
            vFileNames.push_back(entry.path().filename().string());
        }
        else if (0 == extension)
        {
            // without extension
            std::string fileName;
            fileName = entry.path().filename().string();
            int pos = fileName.rfind(".");
            vFileNames.push_back(std::string(fileName, 0, pos));
            fileName.clear();
        }
    }
    if (vFileNames.empty()) {
        std::cout << "This dictionary is Empty, please check your dictinoary path." << endl;
    }
    return vFileNames.size();

}


// Mask is used to cover non areas of interest, highlight areas of interest, 
// and focus image processing only on the ROI part.
// 
// Here marks the results in the picture used for segmentation.
// 
// The rectangle box x0,y0 in the result is the upper left corner,
// and the height and width of the mask are the height and width.
// 
// Parameters
//         image           [IN]           the image in Mat format.
//         DetectionResult [IN]           the result after detection.
//  
//


void drawMask(cv::Mat& image, const DetectionResult& info)
{

    cv::Mat imgMask = info.mask;
    auto x0 = std::max(std::floor(info.box.x0) - 1, 0.f);
    auto y0 = std::max(std::floor(info.box.y0) - 1, 0.f);
    cv::Rect roi((int)x0, (int)y0, info.mask_width, info.mask_height);

    // split the RGB channels, overlay mask to a specific color channel
    cv::Mat ch[3];
    split(image, ch);
    int col = 0;
    cv::bitwise_or(imgMask, ch[col](roi), ch[col](roi));   // The pixel value of each pixel is bitwise or
    merge(ch, 3, image);

}

// visualize the result by drawing the picture in the new window.
// 
// Parameters
//         image           [IN]           the image in Mat format. 
//         info            [IN]           the results after detection.
//         window_name     [IN]           the new window's name.                   
//  
// 


void visualResult(cv::Mat& image, const std::vector<DetectionResult>& info, const std::string& window_name)
{
    if (image.empty())
    {
        cerr << "input is empty, please check the path!" << std::endl;
        return;
    }

    int fontface = cv::FONT_HERSHEY_PLAIN;
    double fontscale = 1;
    int thickness = 1;

    for (int i = 0; i < info.size(); i++)
    {
        //  Generate two points and show the label on the graph.
        cv::Point p1(info[i].box.x0, info[i].box.y0), p2(info[i].box.x1, info[i].box.y1);
        putTextZH(image, (info[i].label).c_str(), p1, cv::Scalar(0, 0, 255), 50, "Arial", false, false);
        if (info[i].mask.empty()) {
            cv::rectangle(image, p1, p2, cv::Scalar(0, 255, 0), 2);
        }
        drawMask(image, info[i]);
    }

    // create a new display window and specify the type of window and then show in the screen.
    cv::namedWindow(window_name, cv::WINDOW_FREERATIO);
    cv::imshow(window_name, image);

    // wait until user presses any key to exit.
    cv::waitKey(0);

    // to close the window and de-allocate any associated memory usage.
    // For a simple program, you do not really have to call these functions because all the resources and windows of the application are closed automatically by the operating system upon exit.
    cv::destroyAllWindows();
}


// Read the results in the Json file, including the following informations. 
// The first two are requested, and others are recommended.
// 
// 1. configuration file And model file exist.
// 2. The system is a Windows 64 bit version.
// 3. Turn off firewall And antivirus software.
// 4. CPU is with Intel main frequency 2.5GHZ 6-core and above versions.
// 5. System memory is greater than 8GB.
// 
//

int readDataFromJson() {
    Json::Reader reader;
    Json::Value root;
    ifstream srcFile("checked.json", ios::binary);
    if (!srcFile.is_open()) {
        cout << "failed to open the file. please check the path." << endl;
        return -1;
    }
    if (reader.parse(srcFile, root)) {
        const int required_num = root["required"].size();
        const int recommend_num = root["recommend"].size();
        for (int i = 0; i < required_num; i++) {
            // 
            int status = root["requied"][i]["status"].asInt();
            if (!status) {
                cerr << root["required"][i]["info"].asString() << endl;
                return -1;
            }
        }
        for (int i = 0; i < recommend_num; i++) {
            int status = root["recommend"][i]["status"].asInt();
            if (!status) {
                cout << root["recommend"][i]["info"].asString() << endl;
            }
        }
    }
    return 1;
}


int main(int argc, char** argv) {

    system("checkEnv.bat");
    int isOk = readDataFromJson();
    if (isOk < 0) {
        return -1;
    }
    cout << endl << endl;
    cout << "Environment detection is successful. " << endl;

    //  model_path is the path of the model,    such as "C:\\Users\\NeuroBot\\A"
    //  file_path  is the path of the pictures, such as "C:\\Users\\NeuroBot\\picture"

    string model_path = "C:\\Users\\Administrator\\Desktop\\zy\\02detc\\trt";
    string file_path = "C:\\Users\\Administrator\\Desktop\\zy\\02detc\\testImage";
    string device_name = "cuda";
    string model_name = "neuro_deteor";                    // the model name, you can name it by yourself.
    if (argc != 1) {
        // such as -m "C:\\Users\\NeuroBot\\A" - f "C:\\Users\\NeuroBot\\picture" - n "neuro_deteor"
        string m = "-m", n = "-n", d = "-d";
        for (int i = 1; i < argc; i++) {
            if (!m.compare(argv[i])) {
                model_path = argv[++i];
            }
            else if (!n.compare(argv[i])) {
                model_name = argv[++i];
            }
            else if (!d.compare(argv[i])) {
                file_path = argv[++i];
            }
            else {
            }
        }
    }
    int total_time = 0;
    int status{};                                          // the state after loading the model, and the default is zero.
    load_model(model_name.c_str(), model_path.c_str(), status);
    if (status != 0) {
        cerr << "failed to create detector, code: " << status << endl;
        return -1;
    }
    vector<string> img_paths;                             // the list of the pictures' name 
    getFilesName(file_path, img_paths);                   // get all the files's names in the dictionary,
    vector<cv::Mat> images;                               // the information in opencv mat format.
    vector<int> image_ids;                                // the image's id 
    vector<cv::Mat> mats;                                 // the information in opencv mat format.

    //  predict and print the result.
    //  batch_size is given in the file model.conf. the default is ONE.
    for (int i = 0; i < (int)img_paths.size(); ++i) {
        cout << endl;
        auto img = cv::imread(file_path + "\\" + img_paths[i]);
        if (!img.data) {
            cerr << "Load image: " << img_paths[i] << "is failed" << endl;
            continue;
        }
        else {
            cout << "Load image: " << img_paths[i] << "is successful" << endl;
        }
        images.push_back(img);
        image_ids.push_back(i);
        mats.push_back(img);
        cout << img_paths[i] << endl;
        if ((int)mats.size() == get_batch(model_name.c_str())) {
            vector<vector<DetectionResult>> out_results{};
            DWORD start = GetTickCount64();        // beginning time
            int predictStatus = predict_model(model_name.c_str(), mats, out_results);
            DWORD end = GetTickCount64();          //  end time
            if (predictStatus != 0) {
                cout << "This prediction is failed " << endl;
                cout << "Time cost:                          " << end - start << " ms" << endl << endl << endl;
                continue;
            }
            // The results to be printed.
            // 
            // for OCR and object Detection, results are rectangle box, confidence level,category.
            // 
            // for Pixel Segmentation, results are rectangle box, confidence level,category, pixel segmentation image.
            int index = 0;
            for (auto res : out_results) {
                for (auto r : res) {
                    cout << endl;
                    cout << "label:                              " << r.label << endl;
                    cout << "Label_index:                        " << r.label_index << endl;
                    cout << "Confidential score:                 " << r.score << endl;
                    cout << "Position of result(x0,y0,x1,y1):    " << r.box.x0 << "  " << r.box.y0 << "  " << r.box.x1 << "  " << r.box.y1 << endl;
                    cout << "Row_index:                          " << r.row_index << endl;
                    cout << "Col_index:                          " << r.col_index << endl;
                    cout << "Mask_width:                         " << r.mask_width << endl;
                    cout << "Mask_height:                        " << r.mask_height << endl;
                }
                cout << endl;
                cout << "Time cost:                          " << end - start << " ms" << endl << endl << endl;
                cout << "Press enter to continue             " << endl;
                // It will visual a result by a new window whose name is show.
                visualResult(mats[index], res, img_paths[index]);
                index++;
            }
            mats.clear();
            image_ids.clear();
            images.clear();
            cout << endl << endl;
        }
    }
    if (!mats.empty()) {
        int requested_batch = get_batch(model_name.c_str());
        cv::Mat last_pict = mats[mats.size() - 1];
        while (mats.size() < requested_batch()) {
            mats.push_back(last_pict);
        }
        vector<vector<DetectionResult>> out_results{};
        (void)predict_model(model_name.c_str(), mats, out_results);
    }
    destroy_model(model_name.c_str());

    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值