OpenCV DNN模块教程(四)Mask-RCNN实例分割

news/2024/12/22 18:14:17/

    本文为OpenCV DNN模块官方教程的扩展,介绍如何使用OpenCV加载TensorFlow Object Detection API训练的模型做实例分割,以Mask-RCNN为例来检测缺陷。TensorFlow Object Detection API的github链接地址如下:https://github.com/tensorflow/models/tree/master/research/object_detection

    本文以TensorFlow 1.x为例(TF2.x等后续稳定支持OpenCV后介绍),介绍OpenCV DNN模块调用Mask-RCNN模型做实例分割的步骤如下:

    (1) 下载或自己训练生成 .pb 格式的模型文件。本文以自己训练好的缺陷检测模型frozen_inference_graph.pb为例:

    (2) 使用指令用.pb文件生成.pbtxt文件, Mask-RCNN使用tf_text_graph_mask_rcnn.py,指令如下:

 

主要参数三个:

    --input 输入.pb模型文件完整路径;

    --output 输出.pbtxt文件完整路径;

    --config 输入config文件完整路径

完整指令:

python tf_text_graph_mask_rcnn.py --input E:\Practice\TensorFlow\DataSet\mask_defects2\model\export\frozen_inference_graph.pb --output E:\Practice\TensorFlow\DataSet\mask_defects2\model\export\frozen_inference_graph.pbtxt --config E:\Practice\TensorFlow\DataSet\mask_defects2\model\train\mask_rcnn_inception_v2_coco.config

运行结果:

    (3) 配置OpenCV4.4,加载图片测试 ,代码如下:

#include <fstream>
#include <sstream>
#include <iostream>
#include <string.h>#include <opencv2/dnn.hpp>
#include <opencv2/imgproc.hpp>
#include <opencv2/highgui.hpp>using namespace cv;
using namespace dnn;
using namespace std;// Initialize the parameters
float confThreshold = 0.4; // Confidence threshold
float maskThreshold = 0.5; // Mask thresholdvector<string> classes;
vector<Scalar> colors;// Draw the predicted bounding box, colorize and show the mask on the image
void drawBox(Mat& frame, int classId, float conf, Rect box, Mat& objectMask)
{//Draw a rectangle displaying the bounding boxrectangle(frame, Point(box.x, box.y), Point(box.x + box.width, box.y + box.height), Scalar(255, 178, 50), 5);//Get the label for the class name and its confidencestring label = format("%.2f", conf);if (!classes.empty()){CV_Assert(classId < (int)classes.size());label = classes[classId] + ":" + label;}//Display the label at the top of the bounding boxint baseLine;Size labelSize = getTextSize(label, FONT_HERSHEY_SIMPLEX, 0.5, 1, &baseLine);box.y = max(box.y, labelSize.height);//rectangle(frame, Point(box.x, box.y - round(1.5*labelSize.height)), Point(box.x + round(1.5*labelSize.width), box.y + baseLine), Scalar(255, 255, 255), FILLED);putText(frame, label, Point(box.x, box.y), FONT_HERSHEY_SIMPLEX, 0.75, Scalar(0, 255, 0), 2);Scalar color = colors[classId%colors.size()];// Resize the mask, threshold, color and apply it on the imageresize(objectMask, objectMask, Size(box.width, box.height));Mat mask = (objectMask > maskThreshold);Mat coloredRoi = (0.5 * color + 0.7 * frame(box));coloredRoi.convertTo(coloredRoi, CV_8UC3);// Draw the contours on the imagevector<Mat> contours;Mat hierarchy;mask.convertTo(mask, CV_8U);findContours(mask, contours, hierarchy, RETR_CCOMP, CHAIN_APPROX_SIMPLE);drawContours(coloredRoi, contours, -1, color, 5, LINE_8, hierarchy, 100);coloredRoi.copyTo(frame(box), mask);}
// For each frame, extract the bounding box and mask for each detected objectvoid postprocess(Mat& frame, const vector<Mat>& outs)
{Mat outDetections = outs[0];Mat outMasks = outs[1];// Output size of masks is NxCxHxW where// N - number of detected boxes// C - number of classes (excluding background)// HxW - segmentation shapeconst int numDetections = outDetections.size[2];const int numClasses = outMasks.size[1];outDetections = outDetections.reshape(1, outDetections.total() / 7);for (int i = 0; i < numDetections; ++i){float score = outDetections.at<float>(i, 2);if (score > confThreshold){// Extract the bounding boxint classId = static_cast<int>(outDetections.at<float>(i, 1));int left = static_cast<int>(frame.cols * outDetections.at<float>(i, 3));int top = static_cast<int>(frame.rows * outDetections.at<float>(i, 4));int right = static_cast<int>(frame.cols * outDetections.at<float>(i, 5));int bottom = static_cast<int>(frame.rows * outDetections.at<float>(i, 6));left = max(0, min(left, frame.cols - 1));top = max(0, min(top, frame.rows - 1));right = max(0, min(right, frame.cols - 1));bottom = max(0, min(bottom, frame.rows - 1));Rect box = Rect(left, top, right - left + 1, bottom - top + 1);// Extract the mask for the objectMat objectMask(outMasks.size[2], outMasks.size[3], CV_32F, outMasks.ptr<float>(i, classId));// Draw bounding box, colorize and show the mask on the imagedrawBox(frame, classId, score, box, objectMask);}}
}/***************Image Test****************/
int main()
{// Load names of classesstring classesFile = "./model2/label.names";ifstream ifs(classesFile.c_str());string line;while (getline(ifs, line)) classes.push_back(line);// Load the colorsstring colorsFile = "./model2/colors.txt";ifstream colorFptr(colorsFile.c_str());while (getline(colorFptr, line)){char* pEnd;double r, g, b;r = strtod(line.c_str(), &pEnd);g = strtod(pEnd, NULL);b = strtod(pEnd, NULL);Scalar color = Scalar(r, g, b, 255.0);colors.push_back(Scalar(r, g, b, 255.0));}// Give the configuration and weight files for the modelString textGraph = "./model2/defect_label.pbtxt";String modelWeights = "./model2/frozen_inference_graph.pb";// Load the networkNet net = readNetFromTensorflow(modelWeights, textGraph);// Open a video file or an image file or a camera stream.string str, outputFile;Mat frame, blob;// Create a windowstatic const string kWinName = "OpenCV DNN Mask-RCNN Demo";// Process frames.frame = imread("./imgs/4.jpg");// Create a 4D blob from a frame.//blobFromImage(frame, blob, 1.0, Size(frame.cols, frame.rows), Scalar(), true, false);//blobFromImage(frame, blob, 1.0, Size(1012, 800), Scalar(), true, false);blobFromImage(frame, blob, 1.0, Size(800, 800), Scalar(), true, false);//blobFromImage(frame, blob);//Sets the input to the networknet.setInput(blob);// Runs the forward pass to get output from the output layersstd::vector<String> outNames(2);cout << outNames[0] << endl;cout << outNames[1] << endl;outNames[0] = "detection_out_final";outNames[1] = "detection_masks";vector<Mat> outs;net.forward(outs, outNames);// Extract the bounding box and mask for each of the detected objectspostprocess(frame, outs);// Put efficiency information. The function getPerfProfile returns the overall time for inference(t) and the timings for each of the layers(in layersTimes)vector<double> layersTimes;double freq = getTickFrequency() / 1000;double t = net.getPerfProfile(layersTimes) / freq;string label = format("test use time: %0.0f ms", t);putText(frame, label, Point(10, 20), FONT_HERSHEY_SIMPLEX, 0.8, Scalar(0, 0, 255), 2);// Write the frame with the detection boxesMat detectedFrame;frame.convertTo(detectedFrame, CV_8U);imwrite("result.jpg", frame);//resize(frame, frame, Size(frame.cols / 3, frame.rows / 3));imshow(kWinName, frame);waitKey(0);return 0;
}

   测试图像:

    运行结果:

更多OpenCV/Halcon等相关资讯请关注公众号:OpenCV与AI深度学习


http://www.ppmy.cn/news/648363.html

相关文章

基于ChatGLM2和langchain的本地知识库问答的实战方案

大家好,我是herosunly。985院校硕士毕业,现担任算法研究员一职,热衷于机器学习算法研究与应用。曾获得阿里云天池比赛第一名,CCF比赛第二名,科大讯飞比赛第三名。拥有多项发明专利。对机器学习和深度学习拥有自己独到的见解。曾经辅导过若干个非计算机专业的学生进入到算法…

Spring 的依赖注入(DI)

前言 欢迎来到本篇文章&#xff0c;书接上回&#xff0c;本篇说说 Spring 中的依赖注入&#xff0c;包括注入的方式&#xff0c;写法&#xff0c;该选择哪个注入方式以及可能出现的循环依赖问题等内容。 如果正在阅读的朋友还不清楚什么是「依赖」&#xff0c;建议先看看我第一…

一张SSL证书支持绑定多个域名吗?

一张SSL证书可支持绑定多个不同类型的域名&#xff0c;选择多域名SSL证书&#xff08;SAN SSL&#xff09;或通配符SSL证书&#xff08;Wildcard SSL&#xff09;类型&#xff0c;就可以实现一张SSL证书绑定多个域名&#xff0c;但绑定的域名类型有些不同。 1、多域名SSL证书&a…

如何查看k8s中kube-proxy的模式是ipvs还是iptables

要查看 Kubernetes 中 kube-proxy 的模式&#xff08;IPVS 还是 iptables&#xff09;&#xff0c;可以使用以下方法之一&#xff1a; 1. 通过 kubectl 命令查看 kube-proxy 的配置&#xff1a; kubectl get configmap kube-proxy -n kube-system -o yaml | grep mode这将显示…

win7旗舰版64位安装SQL2000无响应

1、确保计算机名称为大写字母&#xff0c;暂时关闭各类防护软件 2、确定SQL安装包在英文目录下 3、安装目录下的SETUP文件右键&#xff0c;属性设置兼容性 4、注册表 HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager 下增加SafeDllSearchMode键&…

IDEA旗舰版下载安装 Java编程工具首选利器。

一、简单介绍下社区版(Community)和旗舰版(Ultimate)的不同之处&#xff1a; 1.旗舰版支持企业级开发 &#xff08;JAVAEE&#xff09;还有就是收费。稍后介绍如何破解哦。 2.社区版&#xff0c;免费的、开源的&#xff0c;但功能较少&#xff0c;相比旗舰版功能少。 二、软件…

Visual Studio Ultimate 2013(VS2013旗舰版 下载地址及哈希校验)

微软官方Visual Studio 2013 ISO 文件下载及其哈希校验 Visual Studio Ultimate 2013 计算已下载 ISO 文件的 SHA-1 哈希后&#xff0c;将其与下表中所下载文件的预期哈希进行对比&#xff0c;验证下载文件的完整性。 如果哈希不匹配&#xff0c;则下载文件可能已损坏&#x…

VisualStdio2013旗舰版激活码-注册码.

VisualStdio2013旗舰版 2013-VS旗舰版激活码&#xff1a; Visual Studio 2013旗舰版KEY: BWG7X-J98B3-W34RT-33B3R-JVYW9 Visual Studio 2013 Professional:XDM3T-W3T3V-MGJWK-8BFVD-GVPKY 但是我建议安装完整的updata更新包&#xff0c;推荐updata4&#xff0c;用过的都懂。…