Publishing 2019 R1 content
[platform/upstream/dldt.git] / inference-engine / samples / common / samples / ocv_common.hpp
1 // Copyright (C) 2018-2019 Intel Corporation
2 // SPDX-License-Identifier: Apache-2.0
3 //
4
5 /**
6  * @brief a header file with common samples functionality using OpenCV
7  * @file ocv_common.hpp
8  */
9
10 #pragma once
11
12 #include <samples/common.hpp>
13 #include <opencv2/opencv.hpp>
14
15 /**
16 * @brief Sets image data stored in cv::Mat object to a given Blob object.
17 * @param orig_image - given cv::Mat object with an image data.
18 * @param blob - Blob object which to be filled by an image data.
19 * @param batchIndex - batch index of an image inside of the blob.
20 */
21 template <typename T>
22 void matU8ToBlob(const cv::Mat& orig_image, InferenceEngine::Blob::Ptr& blob, int batchIndex = 0) {
23     InferenceEngine::SizeVector blobSize = blob->getTensorDesc().getDims();
24     const size_t width = blobSize[3];
25     const size_t height = blobSize[2];
26     const size_t channels = blobSize[1];
27     T* blob_data = blob->buffer().as<T*>();
28
29     cv::Mat resized_image(orig_image);
30     if (static_cast<int>(width) != orig_image.size().width ||
31             static_cast<int>(height) != orig_image.size().height) {
32         cv::resize(orig_image, resized_image, cv::Size(width, height));
33     }
34
35     int batchOffset = batchIndex * width * height * channels;
36
37     for (size_t c = 0; c < channels; c++) {
38         for (size_t  h = 0; h < height; h++) {
39             for (size_t w = 0; w < width; w++) {
40                 blob_data[batchOffset + c * width * height + h * width + w] =
41                         resized_image.at<cv::Vec3b>(h, w)[c];
42             }
43         }
44     }
45 }
46
47 /**
48  * @brief Wraps data stored inside of a passed cv::Mat object by new Blob pointer.
49  * @note: No memory allocation is happened. The blob just points to already existing
50  *        cv::Mat data.
51  * @param mat - given cv::Mat object with an image data.
52  * @return resulting Blob pointer.
53  */
54 static UNUSED InferenceEngine::Blob::Ptr wrapMat2Blob(const cv::Mat &mat) {
55     size_t channels = mat.channels();
56     size_t height = mat.size().height;
57     size_t width = mat.size().width;
58
59     size_t strideH = mat.step.buf[0];
60     size_t strideW = mat.step.buf[1];
61
62     bool is_dense =
63             strideW == channels &&
64             strideH == channels * width;
65
66     if (!is_dense) THROW_IE_EXCEPTION
67                 << "Doesn't support conversion from not dense cv::Mat";
68
69     InferenceEngine::TensorDesc tDesc(InferenceEngine::Precision::U8,
70                                       {1, channels, height, width},
71                                       InferenceEngine::Layout::NHWC);
72
73     return InferenceEngine::make_shared_blob<uint8_t>(tDesc, mat.data);
74 }