| 18 | class IOTest : public ::testing::Test {}; |
| 19 | |
| 20 | bool ReadImageToDatumReference(const string& filename, const int label, |
| 21 | const int height, const int width, const bool is_color, Datum* datum) { |
| 22 | cv::Mat cv_img; |
| 23 | int cv_read_flag = (is_color ? CV_LOAD_IMAGE_COLOR : |
| 24 | CV_LOAD_IMAGE_GRAYSCALE); |
| 25 | |
| 26 | cv::Mat cv_img_origin = cv::imread(filename, cv_read_flag); |
| 27 | if (!cv_img_origin.data) { |
| 28 | LOG(ERROR) << "Could not open or find file " << filename; |
| 29 | return false; |
| 30 | } |
| 31 | if (height > 0 && width > 0) { |
| 32 | cv::resize(cv_img_origin, cv_img, cv::Size(width, height)); |
| 33 | } else { |
| 34 | cv_img = cv_img_origin; |
| 35 | } |
| 36 | |
| 37 | int num_channels = (is_color ? 3 : 1); |
| 38 | datum->set_channels(num_channels); |
| 39 | datum->set_height(cv_img.rows); |
| 40 | datum->set_width(cv_img.cols); |
| 41 | datum->set_label(label); |
| 42 | datum->clear_data(); |
| 43 | datum->clear_float_data(); |
| 44 | string* datum_string = datum->mutable_data(); |
| 45 | if (is_color) { |
| 46 | for (int c = 0; c < num_channels; ++c) { |
| 47 | for (int h = 0; h < cv_img.rows; ++h) { |
| 48 | for (int w = 0; w < cv_img.cols; ++w) { |
| 49 | datum_string->push_back( |
| 50 | static_cast<char>(cv_img.at<cv::Vec3b>(h, w)[c])); |
| 51 | } |
| 52 | } |
| 53 | } |
| 54 | } else { // Faster than repeatedly testing is_color for each pixel w/i loop |
| 55 | for (int h = 0; h < cv_img.rows; ++h) { |
| 56 | for (int w = 0; w < cv_img.cols; ++w) { |
| 57 | datum_string->push_back( |
| 58 | static_cast<char>(cv_img.at<uchar>(h, w))); |
| 59 | } |
| 60 | } |
| 61 | } |
| 62 | return true; |
| 63 | } |
| 64 | |
| 65 | TEST_F(IOTest, TestReadImageToDatum) { |
| 66 | string filename = EXAMPLES_SOURCE_DIR "images/cat.jpg"; |