From ae73da4438bacacc5a9e62b03a7e9bfaca2fdde5 Mon Sep 17 00:00:00 2001 From: Davis King Date: Sat, 21 Apr 2012 22:42:51 -0400 Subject: [PATCH] Added the toMat() routine for converting from a dlib style image to an OpenCV cv::Mat image. --- dlib/opencv.h | 1 + dlib/opencv/to_open_cv.h | 37 +++++++++++++++++++++++++++++++ dlib/opencv/to_open_cv_abstract.h | 31 ++++++++++++++++++++++++++ 3 files changed, 69 insertions(+) create mode 100644 dlib/opencv/to_open_cv.h create mode 100644 dlib/opencv/to_open_cv_abstract.h diff --git a/dlib/opencv.h b/dlib/opencv.h index 251f9ad5f..140410792 100644 --- a/dlib/opencv.h +++ b/dlib/opencv.h @@ -4,6 +4,7 @@ #define DLIB_OPEnCV_HEADER #include "opencv/cv_image.h" +#include "opencv/to_open_cv.h" #endif // DLIB_OPEnCV_HEADER diff --git a/dlib/opencv/to_open_cv.h b/dlib/opencv/to_open_cv.h new file mode 100644 index 000000000..78a924ee1 --- /dev/null +++ b/dlib/opencv/to_open_cv.h @@ -0,0 +1,37 @@ +// Copyright (C) 2012 Davis E. King (davis@dlib.net) +// License: Boost Software License See LICENSE.txt for the full license. +#ifndef DLIB_TO_OPEN_Cv_H__ +#define DLIB_TO_OPEN_Cv_H__ + +#include "to_open_cv_abstract.h" +#include "../pixel.h" + +namespace dlib +{ + template < + typename image_type + > + cv::Mat toMat ( + image_type& img + ) + { + if (img.size() == 0) + return cv::Mat(); + + typedef typename image_type::type type; + if (pixel_traits::num == 1) + { + return cv::Mat(img.nr(), img.nc(), cv::DataType::type, &img[0][0], img.width_step()); + } + else + { + int depth = sizeof(typename pixel_traits::basic_pixel_type)*8; + int channels = pixel_traits::num; + int type CV_MAKETYPE(depth, channels); + return cv::Mat(img.nr(), img.nc(), type, &img[0][0], img.width_step()); + } + } +} + +#endif // DLIB_TO_OPEN_Cv_H__ + diff --git a/dlib/opencv/to_open_cv_abstract.h b/dlib/opencv/to_open_cv_abstract.h new file mode 100644 index 000000000..69e7540dd --- /dev/null +++ b/dlib/opencv/to_open_cv_abstract.h @@ -0,0 +1,31 @@ +// Copyright (C) 2012 Davis E. King (davis@dlib.net) +// License: Boost Software License See LICENSE.txt for the full license. +#undef DLIB_TO_OPEN_Cv_ABSTRACT__ +#ifdef DLIB_TO_OPEN_Cv_ABSTRACT__ + +#include "../pixel.h" + +namespace dlib +{ + template < + typename image_type + > + cv::Mat toMat ( + image_type& img + ); + /*! + requires + - image_type == an implementation of dlib/array2d/array2d_kernel_abstract.h + - pixel_traits is defined + ensures + - returns an OpenCV Mat object which represents the same image as img. This + is done by setting up the Mat object to point to the same memory as img. + Therefore, the returned Mat object is valid only as long as pointers + to the pixels in img remain valid. + !*/ +} + +#endif // DLIB_TO_OPEN_Cv_ABSTRACT__ + + +