1 // Copyright 2013 Yangqing Jia
3 #include <stdint.h>
4 #include <opencv2/core/core.hpp>
5 #include <opencv2/highgui/highgui.hpp>
7 #include <algorithm>
8 #include <string>
10 #include "caffe/common.hpp"
11 #include "caffe/util/io.hpp"
12 #include "caffe/proto/caffe.pb.h"
14 using cv::Mat;
15 using cv::Vec3b;
16 using std::max;
17 using std::string;
19 namespace caffe {
21 void ReadImageToProto(const string& filename, BlobProto* proto) {
22 Mat cv_img;
23 cv_img = cv::imread(filename, CV_LOAD_IMAGE_COLOR);
24 CHECK(cv_img.data) << "Could not open or find the image.";
25 DCHECK_EQ(cv_img.channels(), 3);
26 proto->set_num(1);
27 proto->set_channels(3);
28 proto->set_height(cv_img.rows);
29 proto->set_width(cv_img.cols);
30 proto->clear_data();
31 proto->clear_diff();
32 for (int c = 0; c < 3; ++c) {
33 for (int h = 0; h < cv_img.rows; ++h) {
34 for (int w = 0; w < cv_img.cols; ++w) {
35 proto->add_data(static_cast<float>(cv_img.at<Vec3b>(h, w)[c]) / 255.);
36 }
37 }
38 }
39 }
41 void WriteProtoToImage(const string& filename, const BlobProto& proto) {
42 CHECK_EQ(proto.num(), 1);
43 CHECK(proto.channels() == 3 || proto.channels() == 1);
44 CHECK_GT(proto.height(), 0);
45 CHECK_GT(proto.width(), 0);
46 Mat cv_img(proto.height(), proto.width(), CV_8UC3);
47 for (int c = 0; c < 3; ++c) {
48 int source_c = max(c, proto.channels() - 1);
49 for (int h = 0; h < cv_img.rows; ++h) {
50 for (int w = 0; w < cv_img.cols; ++w) {
51 cv_img.at<Vec3b>(h, w)[c] =
52 uint8_t(proto.data((source_c * cv_img.rows + h) * cv_img.cols + w)
53 * 255.);
54 }
55 }
56 }
57 CHECK(cv::imwrite(filename, cv_img));
58 }
61 } // namespace caffe