使用opencv實現對Mask_Rcnn的調用(C++/python)

版權所有,翻版必究。

運行環境:WIN10,pycharm,相應的CUDA,CUDNN,tensorflow1.15.0,tensorflow-gpu-1.14.0,Anaconda3

(很多問題呢都出現在環境的配置上面,所以可以的話開個虛擬環境進行訓練處理)

使用python或者C++調用接口來處理,其中python可以看我之前的版本。調用.h5文件即可。本文中主要介紹一個嗶哩嗶哩大佬使用.pb和.pbtxt來完成調用。主要講解的是C++和python調用的.pb文件和.pbtxt文件的生成問題。後續調用,看代碼即可。(稍安毋昭,看下文)

鏈接在此:https://www.bilibili.com/video/BV1jJ411u7A5

大家可以去看這個人的視頻,很詳細。我這裏主要是用於記錄和自己學習,也歡迎大家一起學習。

https://www.learnopencv.com/deep-learning-based-object-detection-and-instance-segmentation-using-mask-r-cnn-in-opencv-python-c/ (這裏放的是另外一個大佬對於此類問題的分析)

下載文件:

鏈接:https://pan.baidu.com/s/1tI-_S-GJSW3WcMKsdHTBkQ 
提取碼:xk8p

打開後爲:

第一步配置虛擬環境:

打開anoconda下的:

輸入命令:(配置tensorflow) conda create --name tensorflow python=3.7回車即可。我都是因爲已經裝好了,所以不需要再裝虛擬環境。

你們應該會出現這種樣子:輸入y即可。

然後會出現提示:

激活該環境的命令就在其中,使用conda activate tensorflow即可激活環境。然後你們的命令行會變成這樣:

表明已經激活了。

虛擬環境配置好了之後就需要配置安裝包。看你的電腦屬於那種,選擇其中一種進行配置。

//CPU
conda install tensorflow=1.14.0

//GPU
conda install tensorflow-gpu=1.14.0

配置opencv opencv ipython cython pillow:conda install opencv ipython cython pillow

第二步:環境配置

#環境配置
在你安裝的(Anacondal路徑下).\Anaconda3\envs\tensorflow\Lib\site-packages
新建tensorflow.pth ,添加
.\models-master\research
.\models-master\research\slim
這兩個文件的目錄。(需要看你的壓縮文件放在哪裏了!!!)

#cocoapi
cd cocoapi/PythonAPI
python setup.py build_ext install

(需要配置PythonAPI目錄下的文件,裏面放置的是一些依賴庫和文件)

第三步:轉換數據

python create_tf_record.py  --images_dir=./datasets/train/image  --annotations_json_dir=./datasets/train/json  --label_map_path=./datasets/label.pbtxt  --output_path=./output/train.record
python create_tf_record.py  --images_dir=./datasets/val/image  --annotations_json_dir=./datasets/val/json  --label_map_path=./datasets/label.pbtxt  --output_path=./output/val.record

第四步:訓練

#訓練,修改mask_rcnn_inception_v2_coco.config裏面標註有Need Modified
python ./research/object_detection/model_main.py --model_dir=./output --pipeline_config_path=./finetune_model/mask_rcnn_inception_v2_coco.config
 

第五步:轉換模型(生成.pb文件和.pbtxt文件)

#轉換模型,按需要改路徑名字和文件名字
python ./research/object_detection/export_inference_graph.py --input_type image_tensor  --pipeline_config_path ./finetune_model/mask_rcnn_inception_v2_coco.config --trained_checkpoint_prefix ./output/model.ckpt-1000 --output_directory ./output
python tf_text_graph_mask_rcnn.py  --input  ./output/frozen_inference_graph.pb  --output ./output/mask_rcnn.pbtxt  --config ./finetune_model/mask_rcnn_inception_v2_coco.config
python mask_rcnn_predict.py
 

重頭戲在他的視頻中使用C++的opencv來調用這塊,給了我很大的啓發。代碼在他的這個目錄下:

我會添加一些自己的理解在其中,覺得有問題的歡迎說明討論!(不喜勿噴謝謝!)

主程序:

#include "stdafx.h"
#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;

String textGraph = "mask_rcnn.pbtxt";
String modelWeights = "frozen_inference_graph.pb";
string classesFile = "mscoco_labels.names";
string colorsFile = "colors.txt";

float confThreshold = 0.7; 
float maskThreshold = 0.3;

int ImgWidth = 224;
int ImgHight = 224;

vector<string> classes;
vector<Scalar> colors;
Mat frame, blob, m_DstMat;
float m_fWidthScale;
float m_fHeighScale;

void Predect(string path);
void LoadLabelAndColor();
void drawBox(Mat& frame, int classId, float conf, Rect box, Mat& objectMask);
void postprocess(Mat& frame, const vector<Mat>& outs);

int main(int argc, char** argv)
{
	LoadLabelAndColor();
	Predect("1.jpg");
	return 0;
}

void Predect(string path) {
	// Load the network
	Net net = readNetFromTensorflow(modelWeights, textGraph);
	net.setPreferableBackend(DNN_BACKEND_OPENCV);
	net.setPreferableTarget(DNN_TARGET_CPU);


	frame = imread(path);
	m_DstMat = frame.clone();
	resize(frame, frame, Size(ImgWidth, ImgHight));

	m_fWidthScale = m_DstMat.cols*1.0 / frame.cols;
	m_fHeighScale = m_DstMat.rows*1.0 / frame.rows;


	// Stop the program if reached end of video
	if (frame.empty()) {
		return ;
	}
	// Create a 4D blob from a frame.
	blobFromImage(frame, blob, 1.0, Size(frame.cols, frame.rows), Scalar(), true, false);
	//blobFromImage(frame, blob);

	net.setInput(blob);

	std::vector<String> outNames(2);
	outNames[0] = "detection_out_final";
	outNames[1] = "detection_masks";
	vector<Mat> outs;
	net.forward(outs, outNames);

	postprocess(frame, outs);

	vector<double> layersTimes;
	double freq = getTickFrequency() / 1000;
	double t = net.getPerfProfile(layersTimes) / freq;
	string label = format("Inference time for a frame : %0.0f ms", t);
	putText(m_DstMat, label, Point(0, 15), FONT_HERSHEY_SIMPLEX, 0.5, Scalar(0, 0, 0));

	imshow("Result", m_DstMat);
	waitKey(0);

}

此處主程序沒有寫python版本,但是要弄python版本的話也就是改成對應的語句,難度不大。想嘗試的可以試試。我這篇博客主要用於自己學習記錄。

//此處就是利用程序預測出來的邊框點進行圖像的繪製。當然也會設置閾值對結果進行一定程度的把控!
// For each frame, extract the bounding box and mask for each detected object
void 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 shape
	const int numDetections = outDetections.size[2];
	const int numClasses = outMasks.size[1];

	cout<< "numClasses: "<<numDetections << "numClasses: "<<numClasses <<endl;
	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 box
			int 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);

			/************************************************/
			box.x = round(box.x*m_fWidthScale);
			box.y = round(box.y*m_fHeighScale);
			box.width = round(box.width*m_fWidthScale);
			box.height = round(box.height*m_fHeighScale);
			/************************************************/

			// Extract the mask for the object
			Mat objectMask(outMasks.size[2], outMasks.size[3], CV_32F, outMasks.ptr<float>(i, classId));

			// Draw bounding box, colorize and show the mask on the image
			drawBox(m_DstMat, classId, score, box, objectMask);

		}
	}
}

python版本:

# 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)

 

//這一塊的主要目的是在輸入圖像上,利用預測的掩模圖以及邊框點信息進行圖像的繪製。

// 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 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<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);

}

python版本:

# 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)
    im2, 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)

 

//這一塊的本質並不複雜,就是將文件中的內容讀取出來,讓其符合C++使用的規則。
//第一步讀取文件  
//第二步讀取文件中的內容
//第三步放置到你需要存儲的地方。比如此段代碼中放置的位置爲classes和colors
//這也是爲了後面畫圖的時候,用顏色區分來進行提前準備的
void LoadLabelAndColor()
{
    ifstream ifs(classesFile.c_str());
    string line;
    while (getline(ifs, line)) classes.push_back(line);

    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));
    }
}

對應的python代碼爲:

# Load names of classes
classesFile = "mscoco_labels.names";
classes = None
with open(classesFile, 'rt') as f:
   classes = f.read().rstrip('\n').split('\n')


# Load the colors
colorsFile = "colors.txt";
with open(colorsFile, 'rt') as f:
    colorsStr = f.read().rstrip('\n').split('\n')

colors = []
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)

stdafx.cpp中存放的東西如下所示:

// stdafx.cpp : 只包括標準包含文件的源文件
// MaskRCNNCPP.pch 將作爲預編譯頭
// stdafx.obj 將包含預編譯類型信息

#include "stdafx.h"

// TODO: 在 STDAFX.H 中引用任何所需的附加頭文件,
//而不是在此文件中引用

附一張結果圖:

參考了很多大佬的文章,盡情期待我都下一篇文章。該文章主要是說明,如何在C#中使用opencvsharp使用該模型!!!((●'◡'●)這纔是博主的本來目的)。這邊主要也是給予大家一點好多文章。day day up!

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章