基于Caffe实现的UNET的Segmentation代码


#pragma once
//#include "stdafx.h"
#include <caffe/caffe.hpp>

#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>

//#include <opencv/cv.hpp>

#include <algorithm>
#include <iomanip>
#include <iosfwd>
#include <memory>
#include <string>
#include <utility>
#include <vector>
#include <iostream>
#include <iostream>
#include <time.h>
#include <tchar.h>
//#include "datamatrix_location.h"

//#include "ExportsDef.h"
//#include "ParseBarcodeInterface.h"
//#include <stdio.h>

using namespace caffe;

//定义分割器
class Segmentation {
public:
    Segmentation(void);
    ~Segmentation(void);
    void Segmentinit(const string& model_file_seg,
        const string& weights_file_seg,
        const string& mean_file_seg,
        const string& mean_value_seg);

    bool Segment(const cv::Mat& img, cv::Mat& result_img);

private:
    void SetMean(const string& mean_file_seg, const string& mean_value_seg);

    void WrapInputLayer(std::vector<cv::Mat>* input_channels);

    void Preprocess(const cv::Mat& img,
        std::vector<cv::Mat>* input_channels);

private:
    shared_ptr<Net<float> > net_seg;
    cv::Size input_geometry_seg;
    int num_channels_seg;
    cv::Mat mean_seg;
};
Segmentation::Segmentation(void)
{
}

Segmentation::~Segmentation(void)
{
}

void Segmentation::Segmentinit(const string& model_file_seg,
    const string& weights_file_seg,
    const string& mean_file_seg,
    const string& mean_value_seg) {
#ifdef CPU_ONLY
    Caffe::set_mode(Caffe::CPU);
#else
    Caffe::set_mode(Caffe::GPU);
#endif

    /* Load the network. */
    net_seg.reset(new Net<float>(model_file_seg, TEST));
    net_seg->CopyTrainedLayersFrom(weights_file_seg);

    CHECK_EQ(net_seg->num_inputs(), 1) << "Network should have exactly one input.";
    CHECK_EQ(net_seg->num_outputs(), 1) << "Network should have exactly one output.";

    Blob<float>* input_layer = net_seg->input_blobs()[0];
    num_channels_seg = input_layer->channels();
    CHECK(num_channels_seg == 3 || num_channels_seg == 1)
        << "Input layer should have 1 or 3 channels.";
    input_geometry_seg = cv::Size(input_layer->width(), input_layer->height());

    /* Load the binaryproto mean file. */
    SetMean(mean_file_seg, mean_value_seg);
}

bool Segmentation::Segment(const cv::Mat& img, cv::Mat& result_img) {
    Blob<float>* input_layer = net_seg->input_blobs()[0];
    input_layer->Reshape(1, num_channels_seg,
        input_geometry_seg.height, input_geometry_seg.width);
    /* Forward dimension change to all layers. */
    net_seg->Reshape();

    std::vector<cv::Mat> input_channels;
    WrapInputLayer(&input_channels);

    Preprocess(img, &input_channels);

    net_seg->Forward();

    /* Copy the output layer to a std::vector */
    Blob<float>* result_blob = net_seg->output_blobs()[0];
    const float* result = result_blob->cpu_data();

    //获取data中的数据转换成图像
    const int h = result_blob->shape(2);
    const int w = result_blob->shape(3);
    //定义unet_result用于存放概率图
    cv::Mat unet_result = cv::Mat(h, w, CV_8UC1);
    int index = 0;
    for (int r = 0; r < h; r++)
    {
        for (int c = 0; c < w; c++)
        {
            index = r * w + c;
            int temp = static_cast<int>(result[index] * 255);
            //std::cout << "(" << r << "," << c << "): " << temp << std::endl;
            unet_result.at<uchar>(r, c) = (unsigned char)temp;
            //std::cout << "(" << r << "," << c << "): " << result[index] << std::endl;
        }
    }

    if (unet_result.data)
    {
        result_img = unet_result.clone();
        return true;
    }
    else
    {
        std::cout << "Abnormal!!!!" << std::endl;
        return false;
    }

}

/* Load the mean file in binaryproto format. */
void Segmentation::SetMean(const string& mean_file_seg, const string& mean_value_seg) {
    cv::Scalar channel_mean;
    if (!mean_file_seg.empty()) {
        CHECK(mean_value_seg.empty()) <<
            "Cannot specify mean_file_seg and mean_value_seg at the same time";
        BlobProto blob_proto;
        ReadProtoFromBinaryFileOrDie(mean_file_seg.c_str(), &blob_proto);

        /* Convert from BlobProto to Blob<float> */
        Blob<float> mean_blob;
        mean_blob.FromProto(blob_proto);
        CHECK_EQ(mean_blob.channels(), num_channels_seg)
            << "Number of channels of mean file doesn't match input layer.";

        /* The format of the mean file is planar 32-bit float BGR or grayscale. */
        std::vector<cv::Mat> channels;
        float* data = mean_blob.mutable_cpu_data();
        for (int i = 0; i < num_channels_seg; ++i) {
            /* Extract an individual channel. */
            cv::Mat channel(mean_blob.height(), mean_blob.width(), CV_32FC1, data);
            channels.push_back(channel);
            data += mean_blob.height() * mean_blob.width();
        }

        /* Merge the separate channels into a single image. */
        cv::Mat mean;
        cv::merge(channels, mean);

        /* Compute the global mean pixel value and create a mean image
        * filled with this value. */
        channel_mean = cv::mean(mean);
        mean_seg = cv::Mat(input_geometry_seg, mean.type(), channel_mean);
    }
    if (!mean_value_seg.empty()) {
        CHECK(mean_file_seg.empty()) <<
            "Cannot specify mean_file_seg and mean_value_seg at the same time";
        stringstream ss(mean_value_seg);
        vector<float> values;
        string item;
        while (getline(ss, item, ',')) {
            float value = std::atof(item.c_str());
            values.push_back(value);
        }
        CHECK(values.size() == 1 || values.size() == num_channels_seg) <<
            "Specify either 1 mean_value_seg or as many as channels: " << num_channels_seg;

        std::vector<cv::Mat> channels;
        for (int i = 0; i < num_channels_seg; ++i) {
            /* Extract an individual channel. */
            cv::Mat channel(input_geometry_seg.height, input_geometry_seg.width, CV_32FC1,
                cv::Scalar(values[i]));
            channels.push_back(channel);
        }
        cv::merge(channels, mean_seg);
    }
}

/* Wrap the input layer of the network in separate cv::Mat objects
* (one per channel). This way we save one memcpy operation and we
* don't need to rely on cudaMemcpy2D. The last preprocessing
* operation will write the separate channels directly to the input
* layer. */
void Segmentation::WrapInputLayer(std::vector<cv::Mat>* input_channels) {
    Blob<float>* input_layer = net_seg->input_blobs()[0];

    int width = input_layer->width();
    int height = input_layer->height();
    float* input_data = input_layer->mutable_cpu_data();
    for (int i = 0; i < input_layer->channels(); ++i) {
        cv::Mat channel(height, width, CV_32FC1, input_data);
        input_channels->push_back(channel);
        input_data += width * height;
    }
}

void Segmentation::Preprocess(const cv::Mat& img,
    std::vector<cv::Mat>* input_channels) {
    /* Convert the input image to the input image format of the network. */
    cv::Mat sample;
    if (img.channels() == 3 && num_channels_seg == 1)
        cv::cvtColor(img, sample, cv::COLOR_BGR2GRAY);
    else if (img.channels() == 4 && num_channels_seg == 1)
        cv::cvtColor(img, sample, cv::COLOR_BGRA2GRAY);
    else if (img.channels() == 4 && num_channels_seg == 3)
        cv::cvtColor(img, sample, cv::COLOR_BGRA2BGR);
    else if (img.channels() == 1 && num_channels_seg == 3)
        cv::cvtColor(img, sample, cv::COLOR_GRAY2BGR);
    else
        sample = img;

    cv::Mat sample_resized;
    if (sample.size() != input_geometry_seg)
        cv::resize(sample, sample_resized, input_geometry_seg);
    else
        sample_resized = sample;

    cv::Mat sample_float;
    if (num_channels_seg == 3)
        sample_resized.convertTo(sample_float, CV_32FC3);
    else
        sample_resized.convertTo(sample_float, CV_32FC1);

    cv::Mat sample_normalized;
    cv::subtract(sample_float, mean_seg, sample_normalized);

    /* This operation will write the separate BGR planes directly to the
    * input layer of the network because it is wrapped by the cv::Mat
    * objects in input_channels. */
    cv::split(sample_normalized, *input_channels);

    CHECK(reinterpret_cast<float*>(input_channels->at(0).data)
        == net_seg->input_blobs()[0]->cpu_data())
        << "Input channels are not wrapping the input layer of the network.";
}

DEFINE_string(mean_file_seg, "",
    "The mean file used to subtract from the input image.");
DEFINE_string(mean_value_seg, "104,117,123",
    "If specified, can be one value or can be same as image channels"
    " - would subtract from the corresponding channel). Separated by ','."
    "Either mean_file_seg or mean_value_seg should be provided, not both.");

//用于初始化分割器
int init_segment_model(Segmentation& segmentation, const string& model_path, const string& weights_path)
{
    const string model_file_seg = model_path;
    const string weights_file_seg = weights_path;
    const string& mean_file_seg = FLAGS_mean_file_seg;
    const string& mean_value_seg = FLAGS_mean_value_seg;

    // Initialize the unet_network.
    segmentation.Segmentinit(model_file_seg, weights_file_seg, mean_file_seg, mean_value_seg);
    return 1;
}


int main(int argc, char** argv)

{
    const string& model_file_seg = "segmentation.prototxt";
    const string& weights_file_seg = "segmentation.caffemodel";
    Segmentation segmentation;
    int segment_init = init_segment_model(segmentation, model_file_seg, weights_file_seg);
    // load original images of dataMatrix

    std::string strOrgImg_Path = "test.jpg";

    cv::Mat img_seg = cv::imread(strOrgImg_Path, -1);
    if (!img_seg.data)
    {
        return -1;
    }
    cv::Mat seg_result = cv::Mat(img_seg.rows, img_seg.cols, CV_8UC1);
    bool segment_flag = segmentation.Segment(img_seg, seg_result);
    if (segment_flag)
    {
        cv::namedWindow("unet_result");
        cv::imshow("unet_result", seg_result);
        cv::moveWindow("unet_result", 700, 0);
        cv::waitKey(0);
        cv::destroyWindow("unet_result");
    }
    
    return 0;
}

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值