FCN是什么?中文名称是“全卷积网络”,它将传统CNN中的全连接层转化成一个个的卷积层。在传统的CNN结构中,前5层是卷积层,第6层和第7层分别是一个长度为4096的一维向量,第8层是长度为1000的一维向量,分别对应1000个类别的概率。如下图所示:
实例:
#include
#include
#include
using namespace cv;
using namespace std;
using namespace cv::dnn;
const size_t width = 500;
const size_t height = 500;//定义图像文件宽高
vector labels_color();
string label_file = "D:/test/dnn/fcn/labelmap.txt";
string deploy_file = "D:/test/dnn/fcn/fcn8s-heavy-pascal.prototxt";
string model_file = "D:/test/dnn/fcn/fcn8s-heavy-pascal.caffemodel";
int main(int argc, char **argv)
{
Mat src = imread("D:/test/person_bike.jpg");
if (!src.data)
{
cout << "图像文件未找到!!!" << endl;
return -1;
}
resize(src, src, Size(500, 500), 0, 0);
vectorcolors = labels_color();
Net net;
net = readNetFromCaffe(deploy_file, model_file);//读取二进制文件和描述文件
float t1 = getTickCount();
Mat inputblob = blobFromImage(src);
net.setInput(inputblob, "data");
Mat score=net.forward("score");
float t2 = getTickCount();
float t = (t2 - t1) / getTickFrequency();
cout << "运行时间:" <
const int rows = score.size[2]; //图像的高
const int cols = score.size[3]; //图像的宽
const int chns = score.size[1]; //图像的通道数
Mat maxCl(rows, cols, CV_8UC1);
Mat maxVal(rows, cols, CV_32FC1);
for (int c = 0; c < chns; c++) {
for (int row = 0; row < rows; row++) {
const float *ptrScore = score.ptr(0, c, row);
uchar *ptrMaxCl = maxCl.ptr(row);
float *ptrMaxVal = maxVal.ptr(row);
for (int col = 0; col < cols; col++) {
if (ptrScore[col] > ptrMaxVal[col]) {
ptrMaxVal[col] = ptrScore[col];
ptrMaxCl[col] = (uchar)c;
}
}
}
}
// look up colors
Mat result = Mat::zeros(rows, cols, CV_8UC3);
for (int row = 0; row < rows; row++) {
const uchar *ptrMaxCl = maxCl.ptr(row);
Vec3b *ptrColor = result.ptr(row);
for (int col = 0; col < cols; col++) {
ptrColor[col] = colors[ptrMaxCl[col]];
}
}
Mat dst;
addWeighted(src, 0.3, result, 0.7, 0, dst); //图像合并
imshow("FCN-demo