Visual Servoing Platform  version 3.6.1 under development (2024-11-21)
tutorial-bridge-opencv-image.cpp
1 #include <iostream>
3 
4 #include <visp3/core/vpConfig.h>
5 #include <visp3/core/vpImageConvert.h>
6 #include <visp3/io/vpImageIo.h>
7 
8 #if defined(VISP_HAVE_OPENCV) && defined(HAVE_OPENCV_IMGPROC) && defined(HAVE_OPENCV_IMGCODECS)
9 #include <opencv2/core/core.hpp>
10 #include <opencv2/imgproc/imgproc.hpp>
11 #include <opencv2/imgcodecs/imgcodecs.hpp>
12 
13 int main()
14 {
15 #ifdef ENABLE_VISP_NAMESPACE
16  using namespace VISP_NAMESPACE_NAME;
17 #endif
18  // From ViSP to OpenCV conversion
19  {
21  vpImage<vpRGBa> Irgba;
22  vpImageIo::read(Irgba, "monkey.jpeg");
24 
27  vpImageIo::read(Igrey, "monkey.jpeg");
29 
31  cv::Mat cv_img_color;
32  vpImageConvert::convert(Irgba, cv_img_color);
34 
36  cv::Mat cv_img_grey;
37  vpImageConvert::convert(Igrey, cv_img_grey);
39 
40  std::cout << "Save converted images from vpImage to cv::Mat" << std::endl;
41  std::cout << "- monkey-cv-color.jpeg" << std::endl;
42  std::cout << "- monkey-cv-grey.jpeg" << std::endl;
44  cv::imwrite("monkey-cv-color.jpeg", cv_img_color);
47  cv::imwrite("monkey-cv-grey.jpeg", cv_img_grey);
49  }
50 
51  // From OpenCV to ViSP conversion
52  {
54 #if VISP_HAVE_OPENCV_VERSION >= 0x030000
55  cv::Mat cv_img_color = cv::imread("monkey.jpeg", cv::IMREAD_COLOR);
56 #else
57  cv::Mat cv_img_color = cv::imread("monkey.jpeg", CV_LOAD_IMAGE_COLOR);
58 #endif
60 
62  vpImage<vpRGBa> Irgba;
63  vpImageConvert::convert(cv_img_color, Irgba);
65 
67 #if VISP_HAVE_OPENCV_VERSION >= 0x030000
68  cv::Mat cv_img_grey = cv::imread("monkey.jpeg", cv::IMREAD_GRAYSCALE);
69 #else
70  cv::Mat cv_img_grey = cv::imread("monkey.jpeg", CV_LOAD_IMAGE_GRAYSCALE);
71 #endif
73 
76  vpImageConvert::convert(cv_img_grey, Igrey);
78 
79  std::cout << "Save converted images from cv::Mat to vpImage" << std::endl;
80  std::cout << "- monkey-vp-color.jpeg" << std::endl;
81  std::cout << "- monkey-vp-grey.jpeg" << std::endl;
83  vpImageIo::write(Irgba, "monkey-vp-color.jpeg");
86  vpImageIo::write(Igrey, "monkey-vp-grey.jpeg");
88  }
89 }
90 #else
91 int main()
92 {
93  std::cout << "This tutorial required OpenCV imgproc and imgcodecs modules." << std::endl;
94  return EXIT_SUCCESS;
95 }
96 #endif
static void convert(const vpImage< unsigned char > &src, vpImage< vpRGBa > &dest)
static void read(vpImage< unsigned char > &I, const std::string &filename, int backend=IO_DEFAULT_BACKEND)
Definition: vpImageIo.cpp:147
static void write(const vpImage< unsigned char > &I, const std::string &filename, int backend=IO_DEFAULT_BACKEND)
Definition: vpImageIo.cpp:291