建设医院网站的重点与难点在于专业网站设计开发网站

news/2025/9/23 0:49:54/文章来源:
建设医院网站的重点与难点在于,专业网站设计开发网站,重庆整合网络营销,上海市工程质量建设协会网站项目背景 最近停在门前的车被人开走了#xff0c;虽然有监控#xff0c;但是看监控太麻烦了#xff0c;于是想着框选一个区域用yolov8直接检测闯入到这个区域的所有目标#xff0c;这样1ms一帧#xff0c;很快就可以跑完一天的视频 用到的技术 COpenCVYolov8 OnnxRunt…项目背景 最近停在门前的车被人开走了虽然有监控但是看监控太麻烦了于是想着框选一个区域用yolov8直接检测闯入到这个区域的所有目标这样1ms一帧很快就可以跑完一天的视频 用到的技术 COpenCVYolov8 OnnxRuntime yolov8介绍 YOLOv8支持Pose和Segment,在使用TensorRT可以跑到1-2ms一帧YOLOv8提供了一个全新的SOTA模型包括P5 640和P6 1280分辨率的目标检测网络和基于YOLACT的实例分割模型。YOLOv8和YOLOv5一样基于缩放系数也提供了N/S/M/L/X尺度的不同大小模型用于满足不同场景需求。YOLOv8骨干网络和Neck部分可能参考了YOLOv7 ELAN设计思想将YOLOv5的C3结构换成了梯度流更丰富的C2f结构并对不同尺度模型调整了不同的通道数。YOLOv8 Head部分相比YOLOv5改动较大换成了目前主流的解耦头结构将分类和检测头分离同时也从Anchor-Based换成了Anchor-Free。YOLOv8 Loss计算方面采用了TaskAlignedAssigner正样本分配策略并引入了Distribution Focal Loss。YOLOv8训练的数据增强部分引入了YOLOX中的最后10 epoch关闭Mosiac增强的操作可以有效地提升精度。 实现步骤 首先打开视频第一帧框选区域我们直接使用opencv实现这个功能加载模型检测画面中的所有对象计算IOU如果有重合就保存这一帧具体信息跟踪闯入画面的目标否则会重复保存信息 使用opencv打开视频并框选区域 #include opencv2/opencv.hpp #include inference.husing namespace cv;// 定义一个全局变量用于存放鼠标框选的矩形区域 Rect g_rect; // 定义一个全局变量用于标记鼠标是否按下 bool g_bDrawingBox false;// 定义一个回调函数用于处理鼠标事件 void on_MouseHandle(int event, int x, int y, int flags, void* param) {// 将param转换为Mat类型的指针Mat image *(Mat*) param;// 根据不同的鼠标事件进行处理switch (event){// 鼠标左键按下事件case EVENT_LBUTTONDOWN:{// 标记鼠标已按下g_bDrawingBox true;// 记录矩形框的起始点g_rect.x x;g_rect.y y;break;}// 鼠标移动事件case EVENT_MOUSEMOVE:{// 如果鼠标已按下更新矩形框的宽度和高度if (g_bDrawingBox){g_rect.width x - g_rect.x;g_rect.height y - g_rect.y;}break;}// 鼠标左键松开事件case EVENT_LBUTTONUP:{// 标记鼠标已松开g_bDrawingBox false;// 如果矩形框的宽度和高度为正绘制矩形框到图像上if (g_rect.width 0 g_rect.height 0){rectangle(image, g_rect, Scalar(0, 255, 0));}break;}} }int main(int argc, char* argv[]) {// 读取视频文件cv::VideoCapture vc;vc.open(argv[1]);if(vc.isOpened()){cv::Mat frame;vc frame;if(!frame.empty()){// 创建一个副本图像用于显示框选过程Mat temp;frame.copyTo(temp);// 创建一个窗口显示图像namedWindow(image);// 设置鼠标回调函数传入副本图像作为参数setMouseCallback(image, on_MouseHandle, (void*)temp);while (1){// 如果鼠标正在框选绘制一个虚线矩形框到副本图像上并显示框的大小和坐标if (g_bDrawingBox){temp.copyTo(frame);rectangle(frame, g_rect, Scalar(0, 255, 0), 1, LINE_AA);char text[32];sprintf(text, w%d, h%d, g_rect.width, g_rect.height);putText(frame, text, Point(g_rect.x 5, g_rect.y - 5), FONT_HERSHEY_SIMPLEX, 0.5, Scalar(0, 255, 0));}// 显示副本图像imshow(image, frame);// 等待按键如果按下ESC键退出循环if (waitKey(10) 27){break;}}while(!frame.empty()){cv::imshow(image, frame);cv::waitKey(1);vc frame;}}}return 0; }使用YoloV8检测目标 inference.h #pragma once#define RET_OK nullptr#ifdef _WIN32 #include Windows.h #include direct.h #include io.h #endif#include string #include vector #include cstdio #include opencv2/opencv.hpp #include onnxruntime_cxx_api.h#ifdef USE_CUDA #include cuda_fp16.h #endifenum MODEL_TYPE {//FLOAT32 MODELYOLO_ORIGIN_V5 0,YOLO_ORIGIN_V8 1,//only support v8 detector currentlyYOLO_POSE_V8 2,YOLO_CLS_V8 3,YOLO_ORIGIN_V8_HALF 4,YOLO_POSE_V8_HALF 5,YOLO_CLS_V8_HALF 6 };typedef struct _DCSP_INIT_PARAM {std::string ModelPath;MODEL_TYPE ModelType YOLO_ORIGIN_V8;std::vectorint imgSize {640, 640};float RectConfidenceThreshold 0.6;float iouThreshold 0.5;bool CudaEnable false;int LogSeverityLevel 3;int IntraOpNumThreads 1; } DCSP_INIT_PARAM;typedef struct _DCSP_RESULT {int classId;float confidence;cv::Rect box; } DCSP_RESULT;class DCSP_CORE { public:DCSP_CORE();~DCSP_CORE();public:char *CreateSession(DCSP_INIT_PARAM iParams);char *RunSession(cv::Mat iImg, std::vectorDCSP_RESULT oResult);char *WarmUpSession();templatetypename Nchar *TensorProcess(clock_t starttime_1, cv::Mat iImg, N blob, std::vectorint64_t inputNodeDims,std::vectorDCSP_RESULT oResult);std::vectorstd::string classes{};private:Ort::Env env;Ort::Session *session;bool cudaEnable;Ort::RunOptions options;std::vectorconst char * inputNodeNames;std::vectorconst char * outputNodeNames;MODEL_TYPE modelType;std::vectorint imgSize;float rectConfidenceThreshold;float iouThreshold; };inference.cpp #include inference.h #include regex#define benchmarkDCSP_CORE::DCSP_CORE() {}DCSP_CORE::~DCSP_CORE() {delete session; }#ifdef USE_CUDA namespace Ort {templatestruct TypeToTensorTypehalf { static constexpr ONNXTensorElementDataType type ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT16; }; } #endiftemplatetypename T char *BlobFromImage(cv::Mat iImg, T iBlob) {int channels iImg.channels();int imgHeight iImg.rows;int imgWidth iImg.cols;for (int c 0; c channels; c) {for (int h 0; h imgHeight; h) {for (int w 0; w imgWidth; w) {iBlob[c * imgWidth * imgHeight h * imgWidth w] typename std::remove_pointerT::type((iImg.atcv::Vec3b(h, w)[c]) / 255.0f);}}}return RET_OK; }char *PostProcess(cv::Mat iImg, std::vectorint iImgSize, cv::Mat oImg) {cv::Mat img iImg.clone();cv::resize(iImg, oImg, cv::Size(iImgSize.at(0), iImgSize.at(1)));if (img.channels() 1) {cv::cvtColor(oImg, oImg, cv::COLOR_GRAY2BGR);}cv::cvtColor(oImg, oImg, cv::COLOR_BGR2RGB);return RET_OK; }char *DCSP_CORE::CreateSession(DCSP_INIT_PARAM iParams) {char *Ret RET_OK;std::regex pattern([\u4e00-\u9fa5]);bool result std::regex_search(iParams.ModelPath, pattern);if (result) {Ret [DCSP_ONNX]:Model path error.Change your model path without chinese characters.;std::cout Ret std::endl;return Ret;}try {rectConfidenceThreshold iParams.RectConfidenceThreshold;iouThreshold iParams.iouThreshold;imgSize iParams.imgSize;modelType iParams.ModelType;env Ort::Env(ORT_LOGGING_LEVEL_WARNING, Yolo);Ort::SessionOptions sessionOption;if (iParams.CudaEnable) {cudaEnable iParams.CudaEnable;OrtCUDAProviderOptions cudaOption;cudaOption.device_id 0;sessionOption.AppendExecutionProvider_CUDA(cudaOption);}sessionOption.SetGraphOptimizationLevel(GraphOptimizationLevel::ORT_ENABLE_ALL);sessionOption.SetIntraOpNumThreads(iParams.IntraOpNumThreads);sessionOption.SetLogSeverityLevel(iParams.LogSeverityLevel);#ifdef _WIN32int ModelPathSize MultiByteToWideChar(CP_UTF8, 0, iParams.ModelPath.c_str(), static_castint(iParams.ModelPath.length()), nullptr, 0);wchar_t* wide_cstr new wchar_t[ModelPathSize 1];MultiByteToWideChar(CP_UTF8, 0, iParams.ModelPath.c_str(), static_castint(iParams.ModelPath.length()), wide_cstr, ModelPathSize);wide_cstr[ModelPathSize] L\0;const wchar_t* modelPath wide_cstr; #elseconst char *modelPath iParams.ModelPath.c_str(); #endif // _WIN32session new Ort::Session(env, modelPath, sessionOption);Ort::AllocatorWithDefaultOptions allocator;size_t inputNodesNum session-GetInputCount();for (size_t i 0; i inputNodesNum; i) {Ort::AllocatedStringPtr input_node_name session-GetInputNameAllocated(i, allocator);char *temp_buf new char[50];strcpy(temp_buf, input_node_name.get());inputNodeNames.push_back(temp_buf);}size_t OutputNodesNum session-GetOutputCount();for (size_t i 0; i OutputNodesNum; i) {Ort::AllocatedStringPtr output_node_name session-GetOutputNameAllocated(i, allocator);char *temp_buf new char[10];strcpy(temp_buf, output_node_name.get());outputNodeNames.push_back(temp_buf);}options Ort::RunOptions{nullptr};WarmUpSession();return RET_OK;}catch (const std::exception e) {const char *str1 [DCSP_ONNX]:;const char *str2 e.what();std::string result std::string(str1) std::string(str2);char *merged new char[result.length() 1];std::strcpy(merged, result.c_str());std::cout merged std::endl;delete[] merged;return [DCSP_ONNX]:Create session failed.;}}char *DCSP_CORE::RunSession(cv::Mat iImg, std::vectorDCSP_RESULT oResult) { #ifdef benchmarkclock_t starttime_1 clock(); #endif // benchmarkchar *Ret RET_OK;cv::Mat processedImg;PostProcess(iImg, imgSize, processedImg);if (modelType 4) {float *blob new float[processedImg.total() * 3];BlobFromImage(processedImg, blob);std::vectorint64_t inputNodeDims {1, 3, imgSize.at(0), imgSize.at(1)};TensorProcess(starttime_1, iImg, blob, inputNodeDims, oResult);} else { #ifdef USE_CUDAhalf* blob new half[processedImg.total() * 3];BlobFromImage(processedImg, blob);std::vectorint64_t inputNodeDims { 1,3,imgSize.at(0),imgSize.at(1) };TensorProcess(starttime_1, iImg, blob, inputNodeDims, oResult); #endif}return Ret; }templatetypename N char *DCSP_CORE::TensorProcess(clock_t starttime_1, cv::Mat iImg, N blob, std::vectorint64_t inputNodeDims,std::vectorDCSP_RESULT oResult) {Ort::Value inputTensor Ort::Value::CreateTensortypename std::remove_pointerN::type(Ort::MemoryInfo::CreateCpu(OrtDeviceAllocator, OrtMemTypeCPU), blob, 3 * imgSize.at(0) * imgSize.at(1),inputNodeDims.data(), inputNodeDims.size()); #ifdef benchmarkclock_t starttime_2 clock(); #endif // benchmarkauto outputTensor session-Run(options, inputNodeNames.data(), inputTensor, 1, outputNodeNames.data(),outputNodeNames.size()); #ifdef benchmarkclock_t starttime_3 clock(); #endif // benchmarkOrt::TypeInfo typeInfo outputTensor.front().GetTypeInfo();auto tensor_info typeInfo.GetTensorTypeAndShapeInfo();std::vectorint64_t outputNodeDims tensor_info.GetShape();auto output outputTensor.front().GetTensorMutableDatatypename std::remove_pointerN::type();delete blob;switch (modelType) {case 1://V8_ORIGIN_FP32case 4://V8_ORIGIN_FP16{int strideNum outputNodeDims[2];int signalResultNum outputNodeDims[1];std::vectorint class_ids;std::vectorfloat confidences;std::vectorcv::Rect boxes;cv::Mat rawData;if (modelType 1) {// FP32rawData cv::Mat(signalResultNum, strideNum, CV_32F, output);} else {// FP16rawData cv::Mat(signalResultNum, strideNum, CV_16F, output);rawData.convertTo(rawData, CV_32F);}rawData rawData.t();float *data (float *) rawData.data;float x_factor iImg.cols / 640.;float y_factor iImg.rows / 640.;for (int i 0; i strideNum; i) {float *classesScores data 4;cv::Mat scores(1, this-classes.size(), CV_32FC1, classesScores);cv::Point class_id;double maxClassScore;cv::minMaxLoc(scores, 0, maxClassScore, 0, class_id);if (maxClassScore rectConfidenceThreshold) {confidences.push_back(maxClassScore);class_ids.push_back(class_id.x);float x data[0];float y data[1];float w data[2];float h data[3];int left int((x - 0.5 * w) * x_factor);int top int((y - 0.5 * h) * y_factor);int width int(w * x_factor);int height int(h * y_factor);boxes.emplace_back(left, top, width, height);}data signalResultNum;}std::vectorint nmsResult;cv::dnn::NMSBoxes(boxes, confidences, rectConfidenceThreshold, iouThreshold, nmsResult);for (int i 0; i nmsResult.size(); i) {int idx nmsResult[i];DCSP_RESULT result;result.classId class_ids[idx];result.confidence confidences[idx];result.box boxes[idx];oResult.push_back(result);}#ifdef benchmarkclock_t starttime_4 clock();double pre_process_time (double) (starttime_2 - starttime_1) / CLOCKS_PER_SEC * 1000;double process_time (double) (starttime_3 - starttime_2) / CLOCKS_PER_SEC * 1000;double post_process_time (double) (starttime_4 - starttime_3) / CLOCKS_PER_SEC * 1000;if (cudaEnable) {std::cout [DCSP_ONNX(CUDA)]: pre_process_time ms pre-process, process_time ms inference, post_process_time ms post-process. std::endl;} else {std::cout [DCSP_ONNX(CPU)]: pre_process_time ms pre-process, process_time ms inference, post_process_time ms post-process. std::endl;} #endif // benchmarkbreak;}}return RET_OK; }char *DCSP_CORE::WarmUpSession() {clock_t starttime_1 clock();cv::Mat iImg cv::Mat(cv::Size(imgSize.at(0), imgSize.at(1)), CV_8UC3);cv::Mat processedImg;PostProcess(iImg, imgSize, processedImg);if (modelType 4) {float *blob new float[iImg.total() * 3];BlobFromImage(processedImg, blob);std::vectorint64_t YOLO_input_node_dims {1, 3, imgSize.at(0), imgSize.at(1)};Ort::Value input_tensor Ort::Value::CreateTensorfloat(Ort::MemoryInfo::CreateCpu(OrtDeviceAllocator, OrtMemTypeCPU), blob, 3 * imgSize.at(0) * imgSize.at(1),YOLO_input_node_dims.data(), YOLO_input_node_dims.size());auto output_tensors session-Run(options, inputNodeNames.data(), input_tensor, 1, outputNodeNames.data(),outputNodeNames.size());delete[] blob;clock_t starttime_4 clock();double post_process_time (double) (starttime_4 - starttime_1) / CLOCKS_PER_SEC * 1000;if (cudaEnable) {std::cout [DCSP_ONNX(CUDA)]: Cuda warm-up cost post_process_time ms. std::endl;}} else { #ifdef USE_CUDAhalf* blob new half[iImg.total() * 3];BlobFromImage(processedImg, blob);std::vectorint64_t YOLO_input_node_dims { 1,3,imgSize.at(0),imgSize.at(1) };Ort::Value input_tensor Ort::Value::CreateTensorhalf(Ort::MemoryInfo::CreateCpu(OrtDeviceAllocator, OrtMemTypeCPU), blob, 3 * imgSize.at(0) * imgSize.at(1), YOLO_input_node_dims.data(), YOLO_input_node_dims.size());auto output_tensors session-Run(options, inputNodeNames.data(), input_tensor, 1, outputNodeNames.data(), outputNodeNames.size());delete[] blob;clock_t starttime_4 clock();double post_process_time (double)(starttime_4 - starttime_1) / CLOCKS_PER_SEC * 1000;if (cudaEnable){std::cout [DCSP_ONNX(CUDA)]: Cuda warm-up cost post_process_time ms. std::endl;} #endif}return RET_OK; }main.cpp int read_coco_yaml(DCSP_CORE *p) {// Open the YAML filestd::ifstream file(coco.yaml);if (!file.is_open()) {std::cerr Failed to open file std::endl;return 1;}// Read the file line by linestd::string line;std::vectorstd::string lines;while (std::getline(file, line)) {lines.push_back(line);}// Find the start and end of the names sectionstd::size_t start 0;std::size_t end 0;for (std::size_t i 0; i lines.size(); i) {if (lines[i].find(names:) ! std::string::npos) {start i 1;} else if (start 0 lines[i].find(:) std::string::npos) {end i;break;}}// Extract the namesstd::vectorstd::string names;for (std::size_t i start; i end; i) {std::stringstream ss(lines[i]);std::string name;std::getline(ss, name, :); // Extract the number before the delimiterstd::getline(ss, name); // Extract the string after the delimiternames.push_back(name);}p-classes names;return 0; }int main(int argc, char* argv[]) {DCSP_CORE *yoloDetector new DCSP_CORE;//std::string model_path yolov8n.onnx;std::string model_path argv[1];read_coco_yaml(yoloDetector);#ifdef USE_CUDA// GPU FP32 inferenceDCSP_INIT_PARAM params{ model_path, YOLO_ORIGIN_V8, {640, 640}, 0.1, 0.5, true };// GPU FP16 inference// DCSP_INIT_PARAM params{ model_path, YOLO_ORIGIN_V8_HALF, {640, 640}, 0.1, 0.5, true };#else// CPU inferenceDCSP_INIT_PARAM params{model_path, YOLO_ORIGIN_V8, {640, 640}, 0.1, 0.5, false};#endifyoloDetector-CreateSession(params);cv::VideoCapture vc;vc.open(argv[2]);if(vc.isOpened()){cv::Mat frame;vc frame;while(!frame.empty()){std::vectorDCSP_RESULT res;yoloDetector-RunSession(frame, res);for (int i 0; i res.size(); i){DCSP_RESULT detection res[i];cv::Rect box detection.box;cv::RNG rng(cv::getTickCount());cv::Scalar color(rng.uniform(0, 256), rng.uniform(0, 256), rng.uniform(0, 256));;// Detection boxcv::rectangle(frame, box, color, 2);// Detection box textstd::string classString yoloDetector-classes[detection.classId] std::to_string(detection.confidence).substr(0, 4);cv::Size textSize cv::getTextSize(classString, cv::FONT_HERSHEY_DUPLEX, 1, 2, 0);cv::Rect textBox(box.x, box.y - 40, textSize.width 10, textSize.height 20);cv::rectangle(frame, textBox, color, cv::FILLED);cv::putText(frame, classString, cv::Point(box.x 5, box.y - 10), cv::FONT_HERSHEY_DUPLEX, 1, cv::Scalar(0, 0, 0), 2, 0);}cv::rectangle(frame, g_rect, Scalar(0, 255, 0), 3, cv::LINE_AA);cv::imshow(image, frame);cv::waitKey(1);vc frame;}} } opencv的框选区域和yolov8检测目标框融合 #include opencv2/opencv.hpp #include fstream #include inference.husing namespace cv;// 定义一个全局变量用于存放鼠标框选的矩形区域 Rect g_rect; // 定义一个全局变量用于标记鼠标是否按下 bool g_bDrawingBox false;// 定义一个回调函数用于处理鼠标事件 void on_MouseHandle(int event, int x, int y, int flags, void* param) {// 将param转换为Mat类型的指针Mat image *(Mat*) param;// 根据不同的鼠标事件进行处理switch (event){// 鼠标左键按下事件case EVENT_LBUTTONDOWN:{// 标记鼠标已按下g_bDrawingBox true;// 记录矩形框的起始点g_rect.x x;g_rect.y y;break;}// 鼠标移动事件case EVENT_MOUSEMOVE:{// 如果鼠标已按下更新矩形框的宽度和高度if (g_bDrawingBox){g_rect.width x - g_rect.x;g_rect.height y - g_rect.y;}break;}// 鼠标左键松开事件case EVENT_LBUTTONUP:{// 标记鼠标已松开g_bDrawingBox false;// 如果矩形框的宽度和高度为正绘制矩形框到图像上if (g_rect.width 0 g_rect.height 0){rectangle(image, g_rect, Scalar(0, 255, 0));}break;}} }int read_coco_yaml(DCSP_CORE *p) {// Open the YAML filestd::ifstream file(coco.yaml);if (!file.is_open()) {std::cerr Failed to open file std::endl;return 1;}// Read the file line by linestd::string line;std::vectorstd::string lines;while (std::getline(file, line)) {lines.push_back(line);}// Find the start and end of the names sectionstd::size_t start 0;std::size_t end 0;for (std::size_t i 0; i lines.size(); i) {if (lines[i].find(names:) ! std::string::npos) {start i 1;} else if (start 0 lines[i].find(:) std::string::npos) {end i;break;}}// Extract the namesstd::vectorstd::string names;for (std::size_t i start; i end; i) {std::stringstream ss(lines[i]);std::string name;std::getline(ss, name, :); // Extract the number before the delimiterstd::getline(ss, name); // Extract the string after the delimiternames.push_back(name);}p-classes names;return 0; }int main(int argc, char* argv[]) {// 读取原始图像// Mat src imread(argv[1]);DCSP_CORE *yoloDetector new DCSP_CORE;//std::string model_path yolov8n.onnx;std::string model_path argv[1];read_coco_yaml(yoloDetector); #ifdef USE_CUDA// GPU FP32 inferenceDCSP_INIT_PARAM params{ model_path, YOLO_ORIGIN_V8, {640, 640}, 0.1, 0.5, true };// GPU FP16 inference// DCSP_INIT_PARAM params{ model_path, YOLO_ORIGIN_V8_HALF, {640, 640}, 0.1, 0.5, true }; #else// CPU inferenceDCSP_INIT_PARAM params{model_path, YOLO_ORIGIN_V8, {640, 640}, 0.1, 0.5, false}; #endifyoloDetector-CreateSession(params);cv::VideoCapture vc;vc.open(argv[2]);if(vc.isOpened()){cv::Mat frame;vc frame;if(!frame.empty()){// 创建一个副本图像用于显示框选过程Mat temp;frame.copyTo(temp);// 创建一个窗口显示图像namedWindow(image);// 设置鼠标回调函数传入副本图像作为参数setMouseCallback(image, on_MouseHandle, (void*)temp);while (1){// 如果鼠标正在框选绘制一个虚线矩形框到副本图像上并显示框的大小和坐标if (g_bDrawingBox){temp.copyTo(frame);rectangle(frame, g_rect, Scalar(0, 255, 0), 1, LINE_AA);char text[32];sprintf(text, w%d, h%d, g_rect.width, g_rect.height);putText(frame, text, Point(g_rect.x 5, g_rect.y - 5), FONT_HERSHEY_SIMPLEX, 0.5, Scalar(0, 255, 0));}// 显示副本图像imshow(image, frame);// 等待按键如果按下ESC键退出循环if (waitKey(10) 27){break;}}while(!frame.empty()){std::vectorDCSP_RESULT res;yoloDetector-RunSession(frame, res);for (int i 0; i res.size(); i){DCSP_RESULT detection res[i];cv::Rect box detection.box;cv::RNG rng(cv::getTickCount());cv::Scalar color(rng.uniform(0, 256), rng.uniform(0, 256), rng.uniform(0, 256));;// Detection boxcv::rectangle(frame, box, color, 2);// Detection box textstd::string classString yoloDetector-classes[detection.classId] std::to_string(detection.confidence).substr(0, 4);cv::Size textSize cv::getTextSize(classString, cv::FONT_HERSHEY_DUPLEX, 1, 2, 0);cv::Rect textBox(box.x, box.y - 40, textSize.width 10, textSize.height 20);cv::rectangle(frame, textBox, color, cv::FILLED);cv::putText(frame, classString, cv::Point(box.x 5, box.y - 10), cv::FONT_HERSHEY_DUPLEX, 1, cv::Scalar(0, 0, 0), 2, 0);}cv::rectangle(frame, g_rect, Scalar(0, 255, 0), 3, cv::LINE_AA);cv::imshow(image, frame);cv::waitKey(1);vc frame;}}}return 0; }计算预警区域和目标框重合度 double calIou(const cv::Rect rc1, const cv::Rect rc2) {cv::Rect intersection rc1 rc2;if (!intersection.empty()) {double intersectionArea intersection.width * intersection.height;double rect1Area rc1.width * rc1.height;double rect2Area rc2.width * rc2.height;// 计算IOUdouble iou intersectionArea / (rect1Area rect2Area - intersectionArea);return iou;} else {// 没有重叠IOU为0return 0.0;} } 跟踪实现 不断的去循环激活的目标来过滤掉重复的代码这块以后实现 完整代码 #include opencv2/opencv.hpp #include fstream #include inference.husing namespace cv;// 定义一个全局变量用于存放鼠标框选的矩形区域 Rect g_rect; // 定义一个全局变量用于标记鼠标是否按下 bool g_bDrawingBox false;// 定义一个回调函数用于处理鼠标事件 void on_MouseHandle(int event, int x, int y, int flags, void* param) {// 将param转换为Mat类型的指针Mat image *(Mat*) param;// 根据不同的鼠标事件进行处理switch (event){// 鼠标左键按下事件case EVENT_LBUTTONDOWN:{// 标记鼠标已按下g_bDrawingBox true;// 记录矩形框的起始点g_rect.x x;g_rect.y y;break;}// 鼠标移动事件case EVENT_MOUSEMOVE:{// 如果鼠标已按下更新矩形框的宽度和高度if (g_bDrawingBox){g_rect.width x - g_rect.x;g_rect.height y - g_rect.y;}break;}// 鼠标左键松开事件case EVENT_LBUTTONUP:{// 标记鼠标已松开g_bDrawingBox false;// 如果矩形框的宽度和高度为正绘制矩形框到图像上if (g_rect.width 0 g_rect.height 0){rectangle(image, g_rect, Scalar(0, 255, 0));}break;}} }int read_coco_yaml(DCSP_CORE *p) {// Open the YAML filestd::ifstream file(coco.yaml);if (!file.is_open()) {std::cerr Failed to open file std::endl;return 1;}// Read the file line by linestd::string line;std::vectorstd::string lines;while (std::getline(file, line)) {lines.push_back(line);}// Find the start and end of the names sectionstd::size_t start 0;std::size_t end 0;for (std::size_t i 0; i lines.size(); i) {if (lines[i].find(names:) ! std::string::npos) {start i 1;} else if (start 0 lines[i].find(:) std::string::npos) {end i;break;}}// Extract the namesstd::vectorstd::string names;for (std::size_t i start; i end; i) {std::stringstream ss(lines[i]);std::string name;std::getline(ss, name, :); // Extract the number before the delimiterstd::getline(ss, name); // Extract the string after the delimiternames.push_back(name);}p-classes names;return 0; }double calIou(const cv::Rect rc1, const cv::Rect rc2) {cv::Rect intersection rc1 rc2;if (!intersection.empty()) {double intersectionArea intersection.width * intersection.height;double rect1Area rc1.width * rc1.height;double rect2Area rc2.width * rc2.height;// 计算IOUdouble iou intersectionArea / (rect1Area rect2Area - intersectionArea);return iou;} else {// 没有重叠IOU为0return 0.0;} }int main(int argc, char* argv[]) {// 读取原始图像// Mat src imread(argv[1]);DCSP_CORE *yoloDetector new DCSP_CORE;//std::string model_path yolov8n.onnx;std::string model_path argv[1];read_coco_yaml(yoloDetector); #ifdef USE_CUDA// GPU FP32 inferenceDCSP_INIT_PARAM params{ model_path, YOLO_ORIGIN_V8, {640, 640}, 0.1, 0.5, true };// GPU FP16 inference// DCSP_INIT_PARAM params{ model_path, YOLO_ORIGIN_V8_HALF, {640, 640}, 0.1, 0.5, true }; #else// CPU inferenceDCSP_INIT_PARAM params{model_path, YOLO_ORIGIN_V8, {640, 640}, 0.1, 0.5, false}; #endifyoloDetector-CreateSession(params);cv::VideoCapture vc;vc.open(argv[2]);if(vc.isOpened()){cv::Mat frame;vc frame;if(!frame.empty()){// 创建一个副本图像用于显示框选过程Mat temp;frame.copyTo(temp);// 创建一个窗口显示图像namedWindow(image);// 设置鼠标回调函数传入副本图像作为参数setMouseCallback(image, on_MouseHandle, (void*)temp);while (1){// 如果鼠标正在框选绘制一个虚线矩形框到副本图像上并显示框的大小和坐标if (g_bDrawingBox){temp.copyTo(frame);rectangle(frame, g_rect, Scalar(0, 255, 0), 1, LINE_AA);char text[32];sprintf(text, w%d, h%d, g_rect.width, g_rect.height);putText(frame, text, Point(g_rect.x 5, g_rect.y - 5), FONT_HERSHEY_SIMPLEX, 0.5, Scalar(0, 255, 0));}// 显示副本图像imshow(image, frame);// 等待按键如果按下ESC键退出循环if (waitKey(10) 27){break;}}while(!frame.empty()){std::vectorDCSP_RESULT res;yoloDetector-RunSession(frame, res);for (int i 0; i res.size(); i){DCSP_RESULT detection res[i];cv::Rect box detection.box;cv::RNG rng(cv::getTickCount());cv::Scalar color(rng.uniform(0, 256), rng.uniform(0, 256), rng.uniform(0, 256));;// Detection boxcv::rectangle(frame, box, color, 2);// Detection box textstd::string classString yoloDetector-classes[detection.classId] std::to_string(detection.confidence).substr(0, 4);cv::Size textSize cv::getTextSize(classString, cv::FONT_HERSHEY_DUPLEX, 1, 2, 0);cv::Rect textBox(box.x, box.y - 40, textSize.width 10, textSize.height 20);cv::rectangle(frame, textBox, color, cv::FILLED);cv::putText(frame, classString, cv::Point(box.x 5, box.y - 10), cv::FONT_HERSHEY_DUPLEX, 1, cv::Scalar(0, 0, 0), 2, 0);double iou calIou(g_rect, box);if(iou 0)std::cout iou: iou std::endl;}cv::rectangle(frame, g_rect, Scalar(0, 255, 0), 3, cv::LINE_AA);cv::imshow(image, frame);cv::waitKey(1);vc frame;}}}return 0; }参考 yolov8

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/910919.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

网站开发获客渠道做企业网站备案都需要什么资料

文章目录 前言一、题意描述输入描述:输出描述: 二、代码1.代码的实现2.读入数据 总结 前言 在python基础知识的学习中,我们很多时候会遇见让我们把数字拆分成各个位数的题,下面这道就是经典的数字拆分的l例题 一、题意 描述 牛…

学网站建设设计要钱吗wordpress wampsever

前些天发现了一个巨牛的人工智能学习网站,通俗易懂,风趣幽默,忍不住分享一下给大家。点击跳转到教程。 shell脚本中echo显示内容带颜色显示,echo显示带颜色,需要使用参数 -e 格式如下: echo -e "\033[字背景颜…

优质外贸网站海南美容网站建设

letconst解构赋值字符串数组函数对象SymbolSetWeakSetMapWeakMapProxyreflectProxy与Reflex结合实例classpromiseiteratorGerneratorDecorators模块学习资料 let /* let 声明变量 *//* es6相对于es5的全局和局部作用域,多了一个块作用域,块作用域里声明的…

修改备案网站信息广东外贸网站定制

Domain-Oriented Knowledge Transfer for Cross-Domain Recommendation IEEE(CCF B.SCI 1)-Guoshuai Zhao, Xiaolong Zhang, Hao Tang, Jialie Shen, and Xueming Qian-2024 思路 在CDR中,构建连接两个域的桥梁是实现跨域推荐的基础。然而现在的CDR方法往往在连接两个域时忽…

聊城网站开发个人网页传奇世界翅膀升级

来源:机器人圈概要:AI可以帮助人们预测就业市场接下来的变动,发现(并满足)新的培训劳动力的需求,以此缓冲它自身及其他因素造成的影响。人们对人工智能(AI)抱有极高的期待&#xff0…

做网站与运营一般多少钱专业定制网站开发公司

Vuex 是什么 Vuex有几个属性及作用注意事项vuex 使用举例Vuex3和Vuex4有哪些区别 创建 Store 的方式在组件中使用 Store辅助函数的用法响应式的改进Vuex4 支持多例模式 Vuex 是什么 Vuex是一个专门为Vue.js应用设计的状态管理构架,它统一管理和维护各个Vue组件的可…

网站备案中商城服务性质是什么个人能进行网站开发

文章目录 前言一、版本要求1. SpringBoot版本2. 其他2.1 System Requirements2.2 Servlet Containers2.3 GraalVM Native Images 3. 版本定型 二、新建工程1.IDEA创建 ( 推荐 ) \color{#00FF00}{(推荐)} (推荐)2. 官方创建 三、第一个SpringBoot程序1. 引入web2. 启动类3. 启动…

如何查看网站模板广州营销网站建设

文件不到70kb,加载非常快 无配置,没有详情页,上传就可以直接使用 使用教程:上传到网站template目录并解压、进入网站后台选择模板 注意:默认调用ID为1的数据和扩展分类,建议新建站使用 源码下载&#xf…

电子商务网站开发的流程图网站设计哪家比较好

现如今,计算机科学、人工智能、数据科学已成为技术发展的主要推动力。无论是要翻阅这些领域的文章,还是要参与相关任务,你马上就会遇到一些拦路虎:想过滤垃圾邮件,不具备概率论中的贝叶斯思维恐怕不行;想试…

网站布局模式wordpress 百度网盘插件

目标 探索特征工程和多项式回归,使用线性回归来拟合非常复杂甚至非线性的函数。 1.为什么线性回归能拟合非线性函数? fxw*xb,属于线性回归的扩展,这个公式在数学中不属于线性,因为有x,而在机器学习中属于…

什么网站可以免费做试卷网站后台查找软件

github上的开源项目,看介绍可以将设计ui图片转换为 HTML 和 CSS 源码地址: GitCode - 开发者的代码家园 我的mac安装了2.7和3.11,就用3吧直接上代码 安装 pip3 install keras tensorflow pillow h5py jupyter 报错 ERROR: Could not in…

网站建设juxinghulian营销推广平台都干什么的

或者HMster开启后几秒消失问题解决 报错如图: 首先jps命令查看当前运行的内容有没有HMaster,如果没有,开启一下hbase,稍微等一会儿,再看一下HMaster,如果仍和下图一样没有,就基本找到问题了 本人问题原因:hbase-site…

杭州制作网站的公司视频怎么到wordpress

简介: CSDN博客专家,专注Android/Linux系统,分享多mic语音方案、音视频、编解码等技术,与大家一起成长! 优质专栏:Audio工程师进阶系列【原创干货持续更新中……】🚀 优质专栏:多媒…

基本的网站建设知识全国网站联盟

8 Linux实操篇-用户管理 文章目录 8 Linux实操篇-用户管理8.1 添加用户8.2 指定/修改密码8.3 删除用户8.4 切换用户8.5 查询用户信息/查看用户8.6 用户组8.7 用户和组相关文件 学习视频来自于B站【小白入门 通俗易懂】2021韩顺平 一周学会Linux。可能会用到的资料有如下所示&am…

网站制作 手机版长春紧急通知

1.面向过程和面向对象(面向对象三大特性:封装 继承 多态)面向对象编程:分析解决问题组成的对象,从中抽象出类,调用方法(协调对象间的联系与通信),解决问题.面向过程编程:分析解决问题的步骤,实现函数,一次调用2类和对象:类和对象是面向对象的核心类:具有相同特征和行为的事物的…

商城网站建设哪家好asp.net 知名网站

Excel双向柱状图在绘制增减比较的时候经常用到,叫法繁多,双向柱状图、上下柱状图、增减柱状图都有。 这里主要介绍一下Excel的基础绘制方法和复杂一点的双向柱状图的绘制 基础双向柱状图的绘制 首先升降的数据如下: 月份上升下降20220359-…

遵义市和城乡建设局网站网站建设规划设计方案

1、漏洞理解 点击劫持(Click Jacking)是一种视觉上的欺骗手段,攻击者通过使用一个透明的iframe,覆盖在一个网页上,然后诱使用户在该页面上进行操作,通过调整iframe页面的位置,可以使得伪造的页面…

网站一年得多少钱网站你懂我意思正能量app

共享顺序栈:内部也是一个数组 将两个栈放在数组的两端,一个从数组首端开始压栈,一个从数组尾部开始压栈,等到两边栈顶在中间相遇时,栈满。 共享顺序栈在某些情况下可以节省空间。 头文件 sharingStack.h //共享顺序…

企业建网站好手机app网页制作

我们在安装一些包的时候,比如TensorFlow等等,如果直接使用: pip install tensorflow 这句命令来进行安装的时候,我们会发现此时安装的速度不仅非常慢,而且还有可能出现网络超时的情况,比如如下问题: Trac…

什么网站做品牌特卖做任务换流量的网站

操作系统复习 第一章(操作系统引论)计算机操作系统包括:操作系统的目标:操作系统的作用:未配置操作系统的计算机系统:单道批处理系统:缺点: 多道批处理系统:优点&#xf…