凯发真人娱乐

[opencv实战]13 opencv中使用mask r-凯发真人娱乐

2023-08-17,,

目录

1 背景介绍

1.1 什么是图像分割实例分割

1.2 mask-rcnn原理

2 mask-rcnn在opencv中的使用

2.1 模型下载

2.2 模型初始化

2.3 模型加载

2.4 输出结果处理

2.5 画图

3 结果和代码

3.1 结果

3.2 代码

4 参考


mask r-cnn具体内容见:

https://arxiv.org/pdf/1703.06870.pdf

mask r-cnn最初于2017年11月由facebook的ai研究团队使用python和caffe2推出。工程代码见:

https://github.com/facebookresearch/detectron

后来mask r-cnn被移植到tensorflow,并且在共享了几个预先训练的模型,这些模型具有不同的训练架构,如inceptionv2,resnet50,resnet101和inception-resnetv2 。它们还为您提供培训自己模型的工具。

https://github.com/tensorflow/models/blob/master/research/object_detection/g3doc/detection_model_zoo.md

https://github.com/tensorflow/models/blob/master/research/object_detection/g3doc/instance_segmentation.md

基于inception训练的mask r-cnn速度最快,甚至可以在cpu上试用它,因此我们在本教程中选择了它。该模型在mscoco数据集上进行了训练。我们将共享opencv(opencv 3.43以上版本)代码以在c 和python中加载和使用该模型。

1.1 什么是图像分割和实例分割

在计算机视觉中,术语“图像分割”或简称“分割”意味着基于某些标准将图像分成像素区域。您可以根据颜色,纹理或您已决定的其他一些条件进行分割。这些区域有时也称为超像素区域。

进行图像分割有多种方法比如实例分割,语义分割,全景分割等。

具体区别见:

https://zhuanlan.zhihu.com/p/50996404

在实例分割中,目标是检测图像中的特定对象并在感兴趣的对象周围创建掩模。实例分割也可以被认为是对象检测,其输出是掩码而不仅仅是边界框。与尝试对图像中的每个像素进行分类的语义分割不同,实例分割不仅仅在标记图像中的每个像素,还区分各个单体。下面我们看一个在非常相似的彩色背景上的两只绵羊的实例分割的例子。

1.2 mask-rcnn原理

mask-rcnn是对原始r-cnn论文的一系列改进结果,用于物体检测。r-cnn基于选择性搜索的方法生成候选框,然后使用卷积网络一次一个地处理每个候选框区域以输出对象标签及其边界框。

r-cnn具体见:

https://arxiv.org/abs/1311.2524

fast r-cnn通过使用roipool层在其cnn中一起处理所有提出的候选框区域,使得r-cnn算法更快。

fast r-cnn具体见:

https://arxiv.org/pdf/1504.08083.pdf

faster r-cnn通过提取候选区域的网络rpn,代替了费时的选择性搜索,使得检测速度大幅提高。

faster r-cnn具体见:

https://arxiv.org/pdf/1506.01497.pdf

上述r-cnn及其优化版本简要原理见:

https://www.cnblogs.com/skyfsm/p/6806246.html

mask r-cnn是对faster rcnn的一种改进,它包括掩码预测与标签预测和边界框预测两个输出,如下图所示:

mask-rcnn网络有两个主要部分。

第一个是候选区域生成网络,每个图像生成大约300个候选区域。在训练期间,这些候选区域(roi)中的每一个都通过第二部分,即目标检测和掩模预测网络,如上所示。注意,由于掩模预测分支与分类框预测分支并行运行,因此对于每个给定的roi,网络预测可能会获得属于任何类别的掩模。

在推理期间,候选区域会用非最大抑制性方法进行筛选,并且掩模预测分支仅处理最高得分100检测框。因此,对于100个roi和90个对象类,网络的掩模预测部分输出尺寸为100x90x15x15的4d张量,其中每个掩模的大小为15×15。

对于上面显示的绵羊图像,网络检测到两个对象。对于每个对象,它输出一个数组,其中包含预测的类分数(表示对象属于预测类的概率),检测到的对象的边界框的左,上,右和下位置。从掩码预测分支的输出中提取相应分类的掩码。检测到的两个对象的掩码如下所示:

与faster r-cnn一样,mask r-cnn所用架构网络也很灵活。我们之所以选择inceptionv2是因为速度更快,但正如mask r-cnn论文的作者所指出的那样,人们可以通过resnext-101这样的更好的架构获得更好的结果。

与其他物体探测器(如yolov3)相比,mask-rcnn网络可在更大的图像上运行。网络调整输入图像的大小,使得较小的边是800像素。下面我们将详细介绍获取实例分段结果所需的步骤。为了简化和清晰可视化,我们使用相同的颜色来表示同一类的对象,

mask r-cnn简要理解见:

https://www.cnblogs.com/wangyong/p/9305347.html

2.1 模型下载

模型下载地址:

http://download.tensorflow.org/models/object_detection/mask_rcnn_inception_v2_coco_2018_01_28.tar.gz

2.2 模型初始化

mask-rcnn算法输出生成为边界框。每个边界框与置信度分数相关联。置信度阈值参数以下的都将被忽略。从网络输出的对象掩码是灰度图像。由于我们在本教程中使用二值掩码,因此我们使用maskthreshold参数来阈值灰色掩码图像。降低其值将获取更大的掩模。有时这有助于包括在边界附近遗漏的部分,但同时,它还可能包括更尖的边界区域处的背景像素。

文件mscoco_labels.names包含训练模型的所有预测对象。colors.txt文件包含用于标记各种类对象的所有颜色。

接下来,我们使用这两个文件加载网络

mask_rcnn_inception_v2_coco.pb:预先训练的权重;

mask_rcnn_inception_v2_coco.pbtxt:模型结构文件;

下载后的文件有个frozen_inference_graph.pb文件,我改成了mask_rcnn_inception_v2_coco.pb。

我们在这里将dnn后端设置为opencv,将目标设置为cpu。您可以尝试将首选目标设置为cv.dnn.dnn_target_opencl以在gpu上运行它。当前opencv版本中的dnn模块仅使用英特尔的gpu进行测试。我们将读取图像,视频流或网络摄像头进行检测。

c 代码如下:

	//0-image,1-video,2-camera
int read_file = 0;
// load names of classes 导入分类名文件
string classesfile = "./model/mscoco_labels.names";
ifstream ifs(classesfile.c_str());
string line;
while (getline(ifs, line))
{
classes.push_back(line);
} // load the colors 导入颜色类文件
string colorsfile = "./model/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 model
string textgraph = "./model/mask_rcnn_inception_v2_coco.pbtxt";
string modelweights = "./model/mask_rcnn_inception_v2_coco.pb";

2.3 模型加载

神经网络的输入图像需要采用称为blob的特定格式。这一点类似于其他opencv调用深度学习网络的架构。但是用于我们调用的是tensorflow的模型,所以swaprgb参数设置为true。caffe模型就不需要。

然后将blob作为其输入传递到网络,但是我们需要事先设定获取网络的输出层名字。因为输出有两个。这个模型有detection_out_final和detection_masks两个输出层。 这两个输出层分别为预测框的输出结果层和掩模的输出结果层。我们将在下一节中滤除低置信度分数的框。

c 代码如下:

	// load the network 导入网络
net net = readnetfromtensorflow(modelweights, textgraph);
net.setpreferablebackend(dnn_backend_opencv);
//只使用cpu
net.setpreferabletarget(dnn_target_cpu); // open a video file or an image file or a camera stream.
string str, outputfile;
videocapture cap;
videowriter video;
mat frame, blob; try
{
//输出文件,默认是视频
outputfile = "mask_rcnn_out_cpp.avi";
if (read_file == 0)
{
// open the image file 打开图像文件
str = "image/cars.jpg";
//cout << "image file input : " << str << endl;
ifstream ifile(str);
if (!ifile)
{
throw("error");
}
frame = imread(str);
str.replace(str.end() - 4, str.end(), "_mask_rcnn_out.jpg");
outputfile = str;
}
else if (read_file == 1)
{
// open the video file 打开视频文件
str = "./image/cars.mp4";
ifstream ifile(str);
if (!ifile)
{
throw("error");
}
cap.open(str);
str.replace(str.end() - 4, str.end(), "_mask_rcnn_out.avi");
outputfile = str;
}
// open the webcam 打开摄像头
else
{
cap.open(0);
}
}
catch (...)
{
cout << "could not open the input image/video stream" << endl;
return 0;
} // get the video writer initialized to save the output video 如果读入的不是图像,生成输出视频
if (read_file != 0)
{
video.open(outputfile, videowriter::fourcc('m', 'j', 'p', 'g'), 28,
size(cap.get(cap_prop_frame_width), cap.get(cap_prop_frame_height)));
} // create a window 显示窗口
static const string kwinname = "deep learning object detection in opencv"; //process frames 处理图像
while (waitkey(1) < 0)
{
//如果是视频
if (read_file != 0)
{
// get frame from the video 获取单帧图像
cap >> frame;
} // stop the program if reached end of video 如果图像不存在
if (frame.empty())
{
cout << "done processing !!!" << endl;
cout << "output file is stored as " << outputfile << endl;
waitkey(0);
break;
} // create a 4d blob from a frame 获得深度学习的输入图像
blobfromimage(frame, blob, 1.0, size(frame.cols, frame.rows), scalar(), true, false);
//blobfromimage(frame, blob); //sets the input to the network 设置输入
net.setinput(blob); // runs the forward pass to get output from the output layers 获得输出层
std::vector outnames(2);
outnames[0] = "detection_out_final";
outnames[1] = "detection_masks";
vector outs;
net.forward(outs, outnames); // extract the bounding box and mask for each of the detected objects 提取预测框和掩模
postprocess(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 layerstimes;
double freq = gettickfrequency() / 1000;
double t = net.getperfprofile(layerstimes) / freq;
string label = format("mask-rcnn inference time for a frame : %0.0f ms", t);
puttext(frame, label, point(0, 15), font_hershey_simplex, 0.5, scalar(0, 0, 0)); // write the frame with the detection boxes 保存结果
mat detectedframe;
frame.convertto(detectedframe, cv_8u);
namedwindow(kwinname, window_normal);
imshow(kwinname, frame);
//enter退出
if (waitkey(1000) == 27)
{
break;
}
if (read_file == 0)
{
imwrite(outputfile, detectedframe);
break;
}
else
{
video.write(detectedframe);
}
}

2.4 输出结果处理

网络的输出掩码对象是一个四维对象,其中第一维表示帧中检测到的框的数量,第二维表示模型中的类数,第三维和第四维表示掩模形状(15× 15)。如果框的置信度小于给定阈值,则删除边界框并且不考虑进行进一步处理。

c 代码如下:

/**
* @brief for each frame, extract the bounding box and mask for each detected object 提取每张图像的预测框和掩模
*
* @param frame
* @param outs
*/
void postprocess(mat &frame, const vector &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 shape
//预测的框个数
const 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(i, 2);
//超过阈值
if (score > confthreshold)
{
// extract the bounding box
//类别
int classid = static_cast(outdetections.at(i, 1));
int left = static_cast(frame.cols * outdetections.at(i, 3));
int top = static_cast(frame.rows * outdetections.at(i, 4));
int right = static_cast(frame.cols * outdetections.at(i, 5));
int bottom = static_cast(frame.rows * outdetections.at(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 object 提取掩模
mat objectmask(outmasks.size[2], outmasks.size[3], cv_32f, outmasks.ptr(i, classid)); // draw bounding box, colorize and show the mask on the image
drawbox(frame, classid, score, box, objectmask);
}
}
}

2.5 画图

最后,我们在输入图像上绘制通过滤后的框,其中包含指定的类标签和置信度分数。我们还将彩色掩模与其物体轮廓叠加在框内。在此代码中,我们对属于同一类的所有对象使用相同的颜色,但您也可以对不同的实例进行不同的着色。

c 代码如下:

/**
* @brief draw the predicted bounding box, colorize and show the mask on the image 画图
*
* @param frame
* @param classid
* @param conf
* @param box
* @param objectmask
*/
void drawbox(mat &frame, int classid, float conf, rect box, mat &objectmask)
{
//draw a rectangle displaying the bounding box 画预测框
rectangle(frame, point(box.x, box.y), point(box.x box.width, box.y box.height), scalar(255, 178, 50), 3); //get the label for the class name and its confidence
//置信度获取
string 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 box
int 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, 0, 0), 1);
//填充颜色
scalar color = colors[classid % colors.size()]; // resize the mask, threshold, color and apply it on the image 重置大小
resize(objectmask, objectmask, size(box.width, box.height));
mat mask = (objectmask > maskthreshold);
//叠加获得颜色掩模
mat coloredroi = (0.3 * color 0.7 * frame(box));
coloredroi.convertto(coloredroi, cv_8uc3); // draw the contours on the image 画轮廓
vector 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);
}

3.1 结果

mask r-cnn精度不错,但是速度很慢。不过未来的应用趋势吧。下图是原图和结果,但是结果是debug模式下跑的,实际快很多。cpui5标压无gpu下差不多5000ms一帧。

原图:

检测结果图像:

3.2 代码

代码地址:

https://github.com/luohenyueji/opencv-practical-exercise

c 版本代码:

// mask r-cnn in opencv.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
// #include "pch.h"
#include #include
#include
#include
#include #include
#include
#include using namespace cv;
using namespace dnn;
using namespace std; // initialize the parameters
// confidence threshold 置信度阈值
float confthreshold = 0.5;
// mask threshold 掩模阈值
float maskthreshold = 0.3; vector classes;
vector colors; // draw the predicted bounding box
void drawbox(mat &frame, int classid, float conf, rect box, mat &objectmask); // postprocess the neural network's output for each frame
void postprocess(mat &frame, const vector &outs); int main()
{
//0-image,1-video,2-camera
int read_file = 0;
// load names of classes 导入分类名文件
string classesfile = "./model/mscoco_labels.names";
ifstream ifs(classesfile.c_str());
string line;
while (getline(ifs, line))
{
classes.push_back(line);
} // load the colors 导入颜色类文件
string colorsfile = "./model/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 model
string textgraph = "./model/mask_rcnn_inception_v2_coco.pbtxt";
string modelweights = "./model/mask_rcnn_inception_v2_coco.pb"; // load the network 导入网络
net net = readnetfromtensorflow(modelweights, textgraph);
net.setpreferablebackend(dnn_backend_opencv);
//只使用cpu
net.setpreferabletarget(dnn_target_cpu); // open a video file or an image file or a camera stream.
string str, outputfile;
videocapture cap;
videowriter video;
mat frame, blob; try
{
//输出文件,默认是视频
outputfile = "mask_rcnn_out_cpp.avi";
if (read_file == 0)
{
// open the image file 打开图像文件
str = "image/cars.jpg";
//cout << "image file input : " << str << endl;
ifstream ifile(str);
if (!ifile)
{
throw("error");
}
frame = imread(str);
str.replace(str.end() - 4, str.end(), "_mask_rcnn_out.jpg");
outputfile = str;
}
else if (read_file == 1)
{
// open the video file 打开视频文件
str = "./image/cars.mp4";
ifstream ifile(str);
if (!ifile)
{
throw("error");
}
cap.open(str);
str.replace(str.end() - 4, str.end(), "_mask_rcnn_out.avi");
outputfile = str;
}
// open the webcam 打开摄像头
else
{
cap.open(0);
}
}
catch (...)
{
cout << "could not open the input image/video stream" << endl;
return 0;
} // get the video writer initialized to save the output video 如果读入的不是图像,生成输出视频
if (read_file != 0)
{
video.open(outputfile, videowriter::fourcc('m', 'j', 'p', 'g'), 28,
size(cap.get(cap_prop_frame_width), cap.get(cap_prop_frame_height)));
} // create a window 显示窗口
static const string kwinname = "deep learning object detection in opencv"; //process frames 处理图像
while (waitkey(1) < 0)
{
//如果是视频
if (read_file != 0)
{
// get frame from the video 获取单帧图像
cap >> frame;
} // stop the program if reached end of video 如果图像不存在
if (frame.empty())
{
cout << "done processing !!!" << endl;
cout << "output file is stored as " << outputfile << endl;
waitkey(0);
break;
} // create a 4d blob from a frame 获得深度学习的输入图像
blobfromimage(frame, blob, 1.0, size(frame.cols, frame.rows), scalar(), true, false);
//blobfromimage(frame, blob); //sets the input to the network 设置输入
net.setinput(blob); // runs the forward pass to get output from the output layers 获得输出层
std::vector outnames(2);
outnames[0] = "detection_out_final";
outnames[1] = "detection_masks";
vector outs;
net.forward(outs, outnames); // extract the bounding box and mask for each of the detected objects 提取预测框和掩模
postprocess(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 layerstimes;
double freq = gettickfrequency() / 1000;
double t = net.getperfprofile(layerstimes) / freq;
string label = format("mask-rcnn inference time for a frame : %0.0f ms", t);
puttext(frame, label, point(0, 15), font_hershey_simplex, 0.5, scalar(0, 0, 0)); // write the frame with the detection boxes 保存结果
mat detectedframe;
frame.convertto(detectedframe, cv_8u);
namedwindow(kwinname, window_normal);
imshow(kwinname, frame);
//enter退出
if (waitkey(1000) == 27)
{
break;
}
if (read_file == 0)
{
imwrite(outputfile, detectedframe);
break;
}
else
{
video.write(detectedframe);
}
} cap.release();
//释放生成的视频
if (read_file != 0)
{
video.release();
} return 0;
} /**
* @brief for each frame, extract the bounding box and mask for each detected object 提取每张图像的预测框和掩模
*
* @param frame
* @param outs
*/
void postprocess(mat &frame, const vector &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 shape
//预测的框个数
const 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(i, 2);
//超过阈值
if (score > confthreshold)
{
// extract the bounding box
//类别
int classid = static_cast(outdetections.at(i, 1));
int left = static_cast(frame.cols * outdetections.at(i, 3));
int top = static_cast(frame.rows * outdetections.at(i, 4));
int right = static_cast(frame.cols * outdetections.at(i, 5));
int bottom = static_cast(frame.rows * outdetections.at(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 object 提取掩模
mat objectmask(outmasks.size[2], outmasks.size[3], cv_32f, outmasks.ptr(i, classid)); // draw bounding box, colorize and show the mask on the image
drawbox(frame, classid, score, box, objectmask);
}
}
} /**
* @brief draw the predicted bounding box, colorize and show the mask on the image 画图
*
* @param frame
* @param classid
* @param conf
* @param box
* @param objectmask
*/
void drawbox(mat &frame, int classid, float conf, rect box, mat &objectmask)
{
//draw a rectangle displaying the bounding box 画预测框
rectangle(frame, point(box.x, box.y), point(box.x box.width, box.y box.height), scalar(255, 178, 50), 3); //get the label for the class name and its confidence
//置信度获取
string 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 box
int 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, 0, 0), 1);
//填充颜色
scalar color = colors[classid % colors.size()]; // resize the mask, threshold, color and apply it on the image 重置大小
resize(objectmask, objectmask, size(box.width, box.height));
mat mask = (objectmask > maskthreshold);
//叠加获得颜色掩模
mat coloredroi = (0.3 * color 0.7 * frame(box));
coloredroi.convertto(coloredroi, cv_8uc3); // draw the contours on the image 画轮廓
vector 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);
}

python版本代码:

import cv2 as cv
import numpy as np
import os.path
import sys
import random # initialize the parameters
confthreshold = 0.5 # confidence threshold
maskthreshold = 0.3 # mask threshold # draw the predicted bounding box, colorize and show the mask on the image
def drawbox(frame, classid, conf, left, top, right, bottom, classmask):
# draw a bounding box.
cv.rectangle(frame, (left, top), (right, bottom), (255, 178, 50), 3) # print a label of class.
label = '%.2f' % conf
if classes:
assert(classid < len(classes))
label = '%s:%s' % (classes[classid], label) # display the label at the top of the bounding box
labelsize, baseline = cv.gettextsize(label, cv.font_hershey_simplex, 0.5, 1)
top = max(top, labelsize[1])
cv.rectangle(frame, (left, top - round(1.5*labelsize[1])), (left round(1.5*labelsize[0]), top baseline), (255, 255, 255), cv.filled)
cv.puttext(frame, label, (left, top), cv.font_hershey_simplex, 0.75, (0,0,0), 1) # resize the mask, threshold, color and apply it on the image
classmask = cv.resize(classmask, (right - left 1, bottom - top 1))
mask = (classmask > maskthreshold)
roi = frame[top:bottom 1, left:right 1][mask] # color = colors[classid%len(colors)]
# comment the above line and uncomment the two lines below to generate different instance colors
colorindex = random.randint(0, len(colors)-1)
color = colors[colorindex] frame[top:bottom 1, left:right 1][mask] = ([0.3*color[0], 0.3*color[1], 0.3*color[2]] 0.7 * roi).astype(np.uint8) # draw the contours on the image
mask = mask.astype(np.uint8)
contours, hierarchy = cv.findcontours(mask,cv.retr_tree,cv.chain_approx_simple)
cv.drawcontours(frame[top:bottom 1, left:right 1], contours, -1, color, 3, cv.line_8, hierarchy, 100) # for each frame, extract the bounding box and mask for each detected object
def postprocess(boxes, masks):
# output size of masks is nxcxhxw where
# n - number of detected boxes
# c - number of classes (excluding background)
# hxw - segmentation shape
numclasses = masks.shape[1]
numdetections = boxes.shape[2] frameh = frame.shape[0]
framew = frame.shape[1] for i in range(numdetections):
box = boxes[0, 0, i]
mask = masks[i]
score = box[2]
if score > confthreshold:
classid = int(box[1]) # extract the bounding box
left = int(framew * box[3])
top = int(frameh * box[4])
right = int(framew * box[5])
bottom = int(frameh * box[6]) left = max(0, min(left, framew - 1))
top = max(0, min(top, frameh - 1))
right = max(0, min(right, framew - 1))
bottom = max(0, min(bottom, frameh - 1)) # extract the mask for the object
classmask = mask[classid] # draw bounding box, colorize and show the mask on the image
drawbox(frame, classid, score, left, top, right, bottom, classmask) # load names of classes
classesfile = "./model/mscoco_labels.names";
classes = none
with open(classesfile, 'rt') as f:
classes = f.read().rstrip('\n').split('\n') # give the textgraph and weight files for the model
textgraph = "./model/mask_rcnn_inception_v2_coco.pbtxt";
modelweights = "./model/mask_rcnn_inception_v2_coco.pb"; # load the network
net = cv.dnn.readnetfromtensorflow(modelweights, textgraph);
net.setpreferablebackend(cv.dnn.dnn_backend_opencv)
net.setpreferabletarget(cv.dnn.dnn_target_cpu) # load the classes
colorsfile = "./model/colors.txt";
with open(colorsfile, 'rt') as f:
colorsstr = f.read().rstrip('\n').split('\n')
colors = [] #[0,0,0]
for i in range(len(colorsstr)):
rgb = colorsstr[i].split(' ')
color = np.array([float(rgb[0]), float(rgb[1]), float(rgb[2])])
colors.append(color) winname = 'mask-rcnn object detection and segmentation in opencv'
cv.namedwindow(winname, cv.window_normal) #image,video,none
input_file="image"
input_file_name="./image/cars.jpg"
outputfile = "mask_rcnn_out_py.avi"
if (input_file is "image"):
# open the image file
if not os.path.isfile(input_file_name):
print("input image file ", input_file_name, " doesn't exist")
sys.exit(1)
cap = cv.videocapture(input_file_name)
outputfile = input_file_name[:-4] '_mask_rcnn_out_py.jpg'
elif (input_file is "video"):
# open the video file
if not os.path.isfile(input_file_name):
print("input video file ", input_file_name, " doesn't exist")
sys.exit(1)
cap = cv.videocapture(input_file_name)
outputfile = input_file_name[:-4] '_mask_rcnn_out_py.avi'
else:
# webcam input
cap = cv.videocapture(0) # get the video writer initialized to save the output video
if (input_file is not "image"):
vid_writer = cv.videowriter(outputfile, cv.videowriter_fourcc('m','j','p','g'), 28, (round(cap.get(cv.cap_prop_frame_width)),round(cap.get(cv.cap_prop_frame_height)))) while cv.waitkey(1) < 0: # get frame from the video
hasframe, frame = cap.read() # stop the program if reached end of video
if not hasframe:
print("done processing !!!")
print("output file is stored as ", outputfile)
cv.waitkey(3000)
break # create a 4d blob from a frame.
blob = cv.dnn.blobfromimage(frame, swaprb=true, crop=false) # set the input to the network
net.setinput(blob) # run the forward pass to get output from the output layers
boxes, masks = net.forward(['detection_out_final', 'detection_masks']) # extract the bounding box and mask for each of the detected objects
postprocess(boxes, masks) # put efficiency information.
t, _ = net.getperfprofile()
label = 'inference time for a frame : %0.0f ms' % abs(t * 1000.0 / cv.gettickfrequency())
cv.puttext(frame, label, (0, 15), cv.font_hershey_simplex, 0.5, (0, 0, 0)) # write the frame with the detection boxes
if (input_file is "image"):
cv.imwrite(outputfile, frame.astype(np.uint8));
else:
vid_writer.write(frame.astype(np.uint8)) cv.imshow(winname, frame)

https://www.learnopencv.com/deep-learning-based-object-detection-and-instance-segmentation-using-mask-r-cnn-in-opencv-python-c/

[opencv]13 opencv中使用mask r-cnn进行对象检测和实例分割的相关教程结束。

网站地图