MRPT  1.9.9
CImage.cpp
Go to the documentation of this file.
1 /* +------------------------------------------------------------------------+
2  | Mobile Robot Programming Toolkit (MRPT) |
3  | https://www.mrpt.org/ |
4  | |
5  | Copyright (c) 2005-2019, Individual contributors, see AUTHORS file |
6  | See: https://www.mrpt.org/Authors - All rights reserved. |
7  | Released under BSD License. See: https://www.mrpt.org/License |
8  +------------------------------------------------------------------------+ */
9 
10 #include "img-precomp.h" // Precompiled headers
11 
12 #include <mrpt/core/round.h> // for round()
13 #include <mrpt/img/CImage.h>
16 #include <mrpt/io/CMemoryStream.h>
17 #include <mrpt/io/zip.h>
18 #include <mrpt/math/CMatrixF.h>
19 #include <mrpt/math/fourier.h>
20 #include <mrpt/math/utils.h> // for roundup()
22 #include <mrpt/system/CTicTac.h>
24 #include <mrpt/system/filesystem.h>
25 #include <mrpt/system/memory.h>
26 #include <iostream>
27 
28 // Universal include for all versions of OpenCV
29 #include <mrpt/otherlibs/do_opencv_includes.h>
30 
31 #include "CImage_impl.h"
32 
33 #if MRPT_HAS_MATLAB
34 #include <mexplus/mxarray.h>
35 #endif
36 
37 // Prototypes of SSE2/SSE3/SSSE3 optimized functions:
38 #include "CImage_SSEx.h"
39 
40 using namespace mrpt;
41 using namespace mrpt::img;
42 using namespace mrpt::math;
43 using namespace mrpt::system;
44 using namespace std;
45 
46 // This must be added to any CSerializable class implementation file.
48 
49 static bool DISABLE_ZIP_COMPRESSION_value = false;
50 static bool DISABLE_JPEG_COMPRESSION_value = true;
52 static std::string IMAGES_PATH_BASE(".");
53 
54 void CImage::DISABLE_ZIP_COMPRESSION(bool val)
55 {
57 }
60 {
62 }
64 {
66 }
68 {
70 }
72 {
74 }
75 
77  const std::string& s)
78  : std::runtime_error(s)
79 {
80 }
81 
84 {
85  IMAGES_PATH_BASE = path;
86 }
87 
88 // Do performance time logging?
89 #define IMAGE_ALLOC_PERFLOG 0
90 
91 #if IMAGE_ALLOC_PERFLOG
92 mrpt::img::CTimeLogger alloc_tims;
93 #endif
94 
95 #if MRPT_HAS_OPENCV
97 {
98  // clang-format off
99  switch (i)
100  {
101  case IMG_INTERP_NN: return cv::INTER_NEAREST;
102  case IMG_INTERP_LINEAR: return cv::INTER_LINEAR;
103  case IMG_INTERP_CUBIC: return cv::INTER_CUBIC;
104  case IMG_INTERP_AREA: return cv::INTER_AREA;
105  };
106  // clang-format on
107  return -1;
108 }
109 
110 template <typename RET = uint32_t>
112 {
113  // clang-format off
114  switch (d)
115  {
116  case PixelDepth::D8U: return static_cast<RET>(CV_8U);
117  case PixelDepth::D8S: return static_cast<RET>(CV_8S);
118  case PixelDepth::D16U: return static_cast<RET>(CV_16U);
119  case PixelDepth::D16S: return static_cast<RET>(CV_16S);
120  case PixelDepth::D32S: return static_cast<RET>(CV_32S);
121  case PixelDepth::D32F: return static_cast<RET>(CV_32F);
122  case PixelDepth::D64F: return static_cast<RET>(CV_64F);
123  }
124  // clang-format on
125  return std::numeric_limits<RET>::max();
126 }
127 template <typename RET = uint32_t>
129 {
130  // clang-format off
131  switch (d)
132  {
133  case PixelDepth::D8U: return static_cast<RET>(IPL_DEPTH_8U);
134  case PixelDepth::D8S: return static_cast<RET>(IPL_DEPTH_8S);
135  case PixelDepth::D16U: return static_cast<RET>(IPL_DEPTH_16U);
136  case PixelDepth::D16S: return static_cast<RET>(IPL_DEPTH_16S);
137  case PixelDepth::D32S: return static_cast<RET>(IPL_DEPTH_32S);
138  case PixelDepth::D32F: return static_cast<RET>(IPL_DEPTH_32F);
139  case PixelDepth::D64F: return static_cast<RET>(IPL_DEPTH_64F);
140  }
141  // clang-format on
142  return std::numeric_limits<RET>::max();
143 }
144 
146 {
147  // clang-format off
148  switch (d)
149  {
150  case CV_8U: return PixelDepth::D8U;
151  case CV_8S: return PixelDepth::D8S;
152  case CV_16U: return PixelDepth::D16U;
153  case CV_16S: return PixelDepth::D16S;
154  case CV_32S: return PixelDepth::D32S;
155  case CV_32F: return PixelDepth::D32F;
156  case CV_64F: return PixelDepth::D64F;
157  }
158  // clang-format on
159  return PixelDepth::D8U;
160 }
161 
162 #endif // MRPT_HAS_OPENCV
163 
164 // Default ctor
166 
167 // Ctor with size
169  unsigned int width, unsigned int height, TImageChannels nChannels)
170  : CImage()
171 {
172  MRPT_START
173  resize(width, height, nChannels);
174  MRPT_END
175 }
176 
178 {
179  std::swap(m_impl, o.m_impl);
181  std::swap(m_externalFile, o.m_externalFile);
182 }
183 
185 {
186  *this = o;
187  forceLoad();
188 }
189 
190 CImage::CImage(const cv::Mat& img, copy_type_t copy_type) : CImage()
191 {
192 #if MRPT_HAS_OPENCV
193  MRPT_START
194  if (copy_type == DEEP_COPY)
195  m_impl->img = img.clone();
196  else
197  m_impl->img = img;
198  MRPT_END
199 #endif
200 }
201 
203  :
204 #if MRPT_HAS_OPENCV
205  CImage(img.m_impl->img, copy_type)
206 #else
207  CImage()
208 #endif
209 {
210 }
211 
213 {
214 #if MRPT_HAS_OPENCV
215  CImage ret(*this);
216  ret.m_impl->img = m_impl->img.clone();
217  return ret;
218 #else
219  THROW_EXCEPTION("Operation not supported: build MRPT against OpenCV!");
220 #endif
221 }
222 
223 void CImage::asCvMat(cv::Mat& out_img, copy_type_t copy_type) const
224 {
225 #if MRPT_HAS_OPENCV
226  if (copy_type == DEEP_COPY)
227  out_img = m_impl->img.clone();
228  else
229  out_img = m_impl->img;
230 #endif
231 }
232 
234 {
235 #if MRPT_HAS_OPENCV
237  return m_impl->img;
238 #else
239  THROW_EXCEPTION("Operation not supported: build MRPT against OpenCV!");
240 #endif
241 }
242 
243 const cv::Mat& CImage::asCvMatRef() const
244 {
245 #if MRPT_HAS_OPENCV
247  return m_impl->img;
248 #else
249  THROW_EXCEPTION("Operation not supported: build MRPT against OpenCV!");
250 #endif
251 }
252 
254  std::size_t width, std::size_t height, TImageChannels nChannels,
256 {
257  MRPT_START
258 
259 #if MRPT_HAS_OPENCV
260  // Dont call makeSureImageIsLoaded() here,
261  // since it will throw if resize() is called from a ctor, where it's
262  // legit for the img to be uninitialized.
263 
264  // If we're resizing to exactly the current size, do nothing:
265  {
266  _IplImage ipl = m_impl->img;
267 
268  if (static_cast<unsigned>(ipl.width) == width &&
269  static_cast<unsigned>(ipl.height) == height &&
270  ipl.nChannels == nChannels &&
271  static_cast<unsigned>(ipl.depth) == pixelDepth2IPLCvDepth(depth))
272  {
273  // Nothing to do:
274  return;
275  }
276  }
277 
278 #if IMAGE_ALLOC_PERFLOG
279  const std::string sLog = mrpt::format("cvCreateImage %ux%u", width, height);
280  alloc_tims.enter(sLog.c_str());
281 #endif
282 
283  static_assert(
284  pixelDepth2CvDepth<int>(PixelDepth::D8U) + CV_8UC(3) == CV_8UC3);
285 
286  m_impl->img = cv::Mat(
287  static_cast<int>(height), static_cast<int>(width),
288  pixelDepth2CvDepth<int>(depth) + ((nChannels - 1) << CV_CN_SHIFT));
289 
290 #if IMAGE_ALLOC_PERFLOG
291  alloc_tims.leave(sLog.c_str());
292 #endif
293 
294 #else
295  THROW_EXCEPTION("The MRPT has been compiled with MRPT_HAS_OPENCV=0 !");
296 #endif
297  MRPT_END
298 }
299 
301 {
302  MRPT_START
303 #if MRPT_HAS_OPENCV
304  return cvDepth2PixelDepth(m_impl->img.depth());
305 #else
306  THROW_EXCEPTION("The MRPT has been compiled with MRPT_HAS_OPENCV=0 !");
307 #endif
308  MRPT_END
309 }
310 
311 bool CImage::loadFromFile(const std::string& fileName, int isColor)
312 {
313  MRPT_START
314 
315 #if MRPT_HAS_OPENCV
316  m_imgIsExternalStorage = false;
317 #ifdef HAVE_OPENCV_IMGCODECS
318  MRPT_TODO("Port to cv::imdecode()?");
319  MRPT_TODO("add flag to reuse current img buffer");
320 
321  m_impl->img = cv::imread(fileName, static_cast<cv::ImreadModes>(isColor));
322 #else
323  IplImage* newImg = cvLoadImage(fileName.c_str(), isColor);
324  if (!newImg) return false;
325  m_impl->img = cv::cvarrToMat(newImg);
326 #endif
327  if (m_impl->img.empty()) return false;
328 
329  return true;
330 #else
331  THROW_EXCEPTION("The MRPT has been compiled with MRPT_HAS_OPENCV=0 !");
332 #endif
333  MRPT_END
334 }
335 
336 bool CImage::saveToFile(const std::string& fileName, int jpeg_quality) const
337 {
338  MRPT_START
339 #if MRPT_HAS_OPENCV
340  makeSureImageIsLoaded(); // For delayed loaded images stored externally
341  ASSERT_(!m_impl->img.empty());
342 
343 #ifdef HAVE_OPENCV_IMGCODECS
344  const std::vector<int> params = {cv::IMWRITE_JPEG_QUALITY, jpeg_quality};
345  return cv::imwrite(fileName, m_impl->img, params);
346 #else
347  int p[3] = {CV_IMWRITE_JPEG_QUALITY, jpeg_quality, 0};
348  _IplImage ipl = m_impl->img;
349  return (0 != cvSaveImage(fileName.c_str(), &ipl, p));
350 #endif
351 #else
352  THROW_EXCEPTION("The MRPT has been compiled with MRPT_HAS_OPENCV=0 !");
353 #endif
354  MRPT_END
355 }
356 
358 {
359  MRPT_START
360 #if MRPT_HAS_OPENCV
361  ASSERT_(iplImage != nullptr);
362  clear();
363  m_impl->img =
364  cv::cvarrToMat(iplImage, c == DEEP_COPY ? true : false /*copyData*/);
365 #else
366  THROW_EXCEPTION("The MRPT has been compiled with MRPT_HAS_OPENCV=0 !");
367 #endif
368  MRPT_END
369 }
370 
372  unsigned int width, unsigned int height, bool color,
373  unsigned char* rawpixels, bool swapRedBlue)
374 {
375  MRPT_START
376 
377 #if MRPT_HAS_OPENCV
379  m_imgIsExternalStorage = false;
380 
381  _IplImage ii(m_impl->img);
382  IplImage* img = &ii;
383 
384  if (color && swapRedBlue)
385  {
386  // Do copy & swap at once:
387  unsigned char* ptr_src = rawpixels;
388  auto* ptr_dest = reinterpret_cast<unsigned char*>(img->imageData);
389  const int bytes_per_row_out = img->widthStep;
390 
391  for (int h = height; h--;)
392  {
393  for (unsigned int i = 0; i < width;
394  i++, ptr_src += 3, ptr_dest += 3)
395  {
396  unsigned char t0 = ptr_src[0], t1 = ptr_src[1], t2 = ptr_src[2];
397  ptr_dest[2] = t0;
398  ptr_dest[1] = t1;
399  ptr_dest[0] = t2;
400  }
401  ptr_dest += bytes_per_row_out - width * 3;
402  }
403  }
404  else
405  {
406  if (img->widthStep == img->width * img->nChannels)
407  {
408  // Copy the image data:
409  memcpy(img->imageData, rawpixels, img->imageSize);
410  }
411  else
412  {
413  // Copy the image row by row:
414  unsigned char* ptr_src = rawpixels;
415  auto* ptr_dest = reinterpret_cast<unsigned char*>(img->imageData);
416  int bytes_per_row = width * (color ? 3 : 1);
417  int bytes_per_row_out = img->widthStep;
418  for (unsigned int y = 0; y < height; y++)
419  {
420  memcpy(ptr_dest, ptr_src, bytes_per_row);
421  ptr_src += bytes_per_row;
422  ptr_dest += bytes_per_row_out;
423  }
424  }
425  }
426 #else
427  THROW_EXCEPTION("The MRPT has been compiled with MRPT_HAS_OPENCV=0 !");
428 #endif
429  MRPT_END
430 }
431 
432 unsigned char* CImage::operator()(
433  unsigned int ucol, unsigned int urow, unsigned int uchannel) const
434 {
435 #if MRPT_HAS_OPENCV
436 
437 #if defined(_DEBUG) || (MRPT_ALWAYS_CHECKS_DEBUG)
438  MRPT_START
439 #endif
440 
441  makeSureImageIsLoaded(); // For delayed loaded images stored externally
442  const auto col = static_cast<int>(ucol);
443  const auto row = static_cast<int>(urow);
444  const auto channel = static_cast<int>(uchannel);
445 
446 #if defined(_DEBUG) || (MRPT_ALWAYS_CHECKS_DEBUG)
447  ASSERT_(m_impl && !m_impl->img.empty());
448  if (row >= m_impl->img.rows || col >= m_impl->img.cols ||
449  channel >= m_impl->img.channels())
450  {
452  "Pixel coordinates/channel out of bounds: row=%u/%u col=%u/%u "
453  "chan=%u/%u",
454  row, m_impl->img.rows, col, m_impl->img.cols, channel,
455  m_impl->img.channels()));
456  }
457 #endif
458  auto p =
459  (&m_impl->img.at<uint8_t>(row, m_impl->img.channels() * col)) + channel;
460  return const_cast<unsigned char*>(p);
461 #if defined(_DEBUG) || (MRPT_ALWAYS_CHECKS_DEBUG)
462  MRPT_END
463 #endif
464 
465 #else
466  THROW_EXCEPTION("MRPT was compiled without OpenCV");
467 #endif
468 }
469 
470 uint8_t* CImage::internal_get(int col, int row, uint8_t channel) const
471 {
472 #if MRPT_HAS_OPENCV
473  makeSureImageIsLoaded(); // For delayed loaded images stored externally
474  auto p =
475  (&m_impl->img.at<uint8_t>(row, m_impl->img.channels() * col)) + channel;
476  return const_cast<uint8_t*>(p);
477 #else
478  return nullptr;
479 #endif
480 }
481 
483  unsigned int col, unsigned int row, uint8_t channel) const
484 {
485  return internal_get(col, row, channel);
486 }
487 
489 {
490 #if !MRPT_HAS_OPENCV
491  return 100;
492 #else
493  return 9;
494 #endif
495 }
497 {
498 #if !MRPT_HAS_OPENCV
499  out << m_imgIsExternalStorage;
501 // Nothing else to serialize!
502 #else
503  {
504  // Added in version 6: possibility of being stored offline:
505  out << m_imgIsExternalStorage;
506 
508  {
509  out << m_externalFile;
510  }
511  else
512  { // Normal image loaded in memory:
513  ASSERT_(m_impl);
514 
515  const bool hasColor = m_impl->img.empty() ? false : isColor();
516 
517  out << hasColor;
518 
519  // Version >2: Color->JPEG, GrayScale->BYTE's array!
520  const int32_t width = m_impl->img.cols;
521  const int32_t height = m_impl->img.rows;
522  if (!hasColor)
523  {
524  // GRAY-SCALE: Raw bytes:
525  // Version 3: ZIP compression!
526  // Version 4: Skip zip if the image size <= 16Kb
527  int32_t origin = 0; // not used mrpt v1.9.9
528  uint32_t imageSize = height * m_impl->img.step[0];
529  // Version 10: depth
530  int32_t depth = m_impl->img.depth();
531 
532  out << width << height << origin << imageSize
534 
535  // Version 5: Use CImage::DISABLE_ZIP_COMPRESSION
536  bool imageStoredAsZip = !CImage::DISABLE_ZIP_COMPRESSION() &&
537  (imageSize > 16 * 1024);
538 
539  out << imageStoredAsZip;
540 
541  // Version 4: Skip zip if the image size <= 16Kb
542  if (imageStoredAsZip)
543  {
544  std::vector<unsigned char> tempBuf;
546  m_impl->img.data, imageSize, tempBuf);
547 
548  auto zipDataLen = static_cast<int32_t>(tempBuf.size());
549  out << zipDataLen;
550 
551  out.WriteBuffer(&tempBuf[0], tempBuf.size());
552  tempBuf.clear();
553  }
554  else
555  {
556  if (imageSize > 0 && m_impl->img.data != nullptr)
557  out.WriteBuffer(m_impl->img.data, imageSize);
558  }
559  }
560  else
561  {
562  // COLOR: High quality JPEG image
563 
564  // v7: If size is 0xN or Nx0, don't call
565  // "saveToStreamAsJPEG"!!
566 
567  // v8: If DISABLE_JPEG_COMPRESSION
569  {
570  // normal behavior: compress images:
571  out << width << height;
572 
573  if (width >= 1 && height >= 1)
574  {
575  // Save to temporary memory stream:
579 
580  const auto nBytes =
581  static_cast<uint32_t>(aux.getTotalBytesCount());
582 
583  out << nBytes;
584  out.WriteBuffer(aux.getRawBufferData(), nBytes);
585  }
586  }
587  else
588  { // (New in v8)
589  // Don't JPEG-compress behavior:
590  // Use negative image sizes to signal this behavior:
591  const int32_t neg_width = -width;
592  const int32_t neg_height = -height;
593 
594  out << neg_width << neg_height;
595 
596  // Dump raw image data:
597  const auto bytes_per_row = width * 3;
598 
599  out.WriteBuffer(m_impl->img.data, bytes_per_row * height);
600  }
601  }
602  } // end m_imgIsExternalStorage=false
603  }
604 #endif
605 }
606 
608 {
609 #if !MRPT_HAS_OPENCV
610  if (version == 100)
611  {
614  in >> m_externalFile;
615  else
616  {
618  "[CImage] Cannot deserialize image since MRPT has been "
619  "compiled without OpenCV");
620  }
621  }
622 #else
623  // First, free current image.
624  clear();
625 
626  switch (version)
627  {
628  case 100: // Saved from an MRPT build without OpenCV:
629  {
632  }
633  break;
634  case 0:
635  {
636  uint32_t width, height, nChannels, imgLength;
637  uint8_t originTopLeft;
638 
639  in >> width >> height >> nChannels >> originTopLeft >> imgLength;
640 
641  resize(width, height, static_cast<TImageChannels>(nChannels));
642  in.ReadBuffer(m_impl->img.data, imgLength);
643  }
644  break;
645  case 1:
646  {
647  // Version 1: High quality JPEG image
649  uint32_t nBytes;
650  in >> nBytes;
651  aux.changeSize(nBytes + 10);
652  in.ReadBuffer(aux.getRawBufferData(), nBytes);
653  aux.Seek(0);
655  }
656  break;
657  case 2:
658  case 3:
659  case 4:
660  case 5:
661  case 6:
662  case 7:
663  case 8:
664  case 9:
665  {
666  // Version 6: m_imgIsExternalStorage ??
667  if (version >= 6)
669  else
670  m_imgIsExternalStorage = false;
671 
673  {
674  // Just the file name:
675  in >> m_externalFile;
676  }
677  else
678  { // Normal, the whole image data:
679 
680  // Version 2: Color->JPEG, GrayScale->BYTE's array!
681  uint8_t hasColor;
682  in >> hasColor;
683  if (!hasColor)
684  {
685  // GRAY SCALE:
686  int32_t width, height, origin, imageSize;
687  in >> width >> height >> origin >> imageSize;
689  if (version >= 9)
690  {
691  int32_t tempdepth;
692  in >> tempdepth;
693  depth = PixelDepth(tempdepth);
694  }
695  resize(
696  static_cast<uint32_t>(width),
697  static_cast<uint32_t>(height), CH_GRAY, depth);
698  ASSERT_(
699  static_cast<uint32_t>(imageSize) ==
700  static_cast<uint32_t>(width) *
701  static_cast<uint32_t>(height) *
702  m_impl->img.step[0]);
703 
704  if (version == 2)
705  {
706  // RAW BYTES:
707  in.ReadBuffer(m_impl->img.data, imageSize);
708  }
709  else
710  {
711  // Version 3: ZIP compression!
712  bool imageIsZIP = true;
713 
714  // Version 4: Skip zip if the image size <= 16Kb
715  // Version 5: Use CImage::DISABLE_ZIP_COMPRESSION
716  if (version == 4 && imageSize <= 16 * 1024)
717  imageIsZIP = false;
718 
719  if (version >= 5)
720  {
721  // It is stored int the stream:
722  in >> imageIsZIP;
723  }
724 
725  if (imageIsZIP)
726  {
727  uint32_t zipDataLen;
728  in >> zipDataLen;
729 
730 #if 0
731  size_t outDataBufferSize = imageSize;
732  size_t outDataActualSize;
734  in, zipDataLen, m_impl->img.data,
735  outDataBufferSize, outDataActualSize);
736  ASSERT_(outDataActualSize == outDataBufferSize);
737 #else
739  "ZIP image deserialization not "
740  "implemented");
741 #endif
742  }
743  else
744  {
745  // Raw bytes:
746  if (imageSize)
747  in.ReadBuffer(m_impl->img.data, imageSize);
748  }
749  }
750  }
751  else
752  {
753  bool loadJPEG = true;
754 
755  if (version >= 7)
756  {
758  in >> width >> height;
759 
760  if (width >= 1 && height >= 1)
761  {
762  loadJPEG = true;
763  }
764  else
765  {
766  loadJPEG = false;
767 
768  if (width < 0 && height < 0)
769  {
770  // v8: raw image:
771  const int32_t real_w = -width;
772  const int32_t real_h = -height;
773 
774  resize(real_w, real_h, CH_RGB);
775 
776  auto& img = m_impl->img;
777  const size_t bytes_per_row = img.cols * 3;
778  for (int y = 0; y < img.rows; y++)
779  {
780  const size_t nRead = in.ReadBuffer(
781  img.ptr<void>(y), bytes_per_row);
782  if (nRead != bytes_per_row)
784  "Error: Truncated data stream "
785  "while parsing raw image?");
786  }
787  }
788  else
789  {
790  // it's a 0xN or Nx0 image: just resize and
791  // load nothing:
793  }
794  }
795  }
796 
797  // COLOR IMAGE: JPEG
798  if (loadJPEG)
799  {
801  uint32_t nBytes;
802  in >> nBytes;
803  aux.changeSize(nBytes + 10);
804  in.ReadBuffer(aux.getRawBufferData(), nBytes);
805  aux.Seek(0);
807  }
808  }
809  }
810  }
811  break;
812  default:
814  };
815 #endif
816 }
817 
818 /*---------------------------------------------------------------
819 Implements the writing to a mxArray for Matlab
820 ---------------------------------------------------------------*/
821 #if MRPT_HAS_MATLAB
822 // Add to implement mexplus::from template specialization
824 #endif
825 
827 {
828 #if MRPT_HAS_MATLAB
829  cv::Mat cvImg = cv::cvarrToMat(this->getAs<IplImage>());
830  return mexplus::from(cvImg);
831 #else
832  THROW_EXCEPTION("MRPT built without MATLAB/Mex support");
833 #endif
834 }
835 
837 {
838 #if MRPT_HAS_OPENCV
839  makeSureImageIsLoaded(); // For delayed loaded images stored externally
840  s.x = m_impl->img.cols;
841  s.y = m_impl->img.rows;
842 #else
843  THROW_EXCEPTION("MRPT built without MATLAB/Mex support");
844 #endif
845 }
846 
847 size_t CImage::getWidth() const
848 {
849 #if MRPT_HAS_OPENCV
851  return m_impl->img.cols;
852 #else
853  return 0;
854 #endif
855 }
856 
858 {
859 #if MRPT_HAS_OPENCV
860  makeSureImageIsLoaded(); // For delayed loaded images stored externally
861  IplImage ipl(m_impl->img);
862  return std::string(ipl.channelSeq);
863 #else
864  THROW_EXCEPTION("MRPT built without MATLAB/Mex support");
865 #endif
866 }
867 
868 size_t CImage::getRowStride() const
869 {
870 #if MRPT_HAS_OPENCV
871  makeSureImageIsLoaded(); // For delayed loaded images stored externally
872  return m_impl->img.step[0];
873 #else
874  THROW_EXCEPTION("MRPT built without MATLAB/Mex support");
875 #endif
876 }
877 
878 size_t CImage::getHeight() const
879 {
880 #if MRPT_HAS_OPENCV
882  return m_impl->img.rows;
883 #else
884  return 0;
885 #endif
886 }
887 
888 bool CImage::isColor() const
889 {
890 #if MRPT_HAS_OPENCV
891  makeSureImageIsLoaded(); // For delayed loaded images stored externally
892  return m_impl->img.channels() == 3;
893 #else
894  THROW_EXCEPTION("MRPT built without MATLAB/Mex support");
895 #endif
896 }
897 
899 {
900 #if MRPT_HAS_OPENCV
901  makeSureImageIsLoaded(); // For delayed loaded images stored externally
902  return static_cast<TImageChannels>(m_impl->img.channels());
903 #else
904  THROW_EXCEPTION("MRPT built without MATLAB/Mex support");
905 #endif
906 }
907 
909 {
910  return true; // As of mrpt v1.9.9
911 }
912 
914  unsigned int col, unsigned int row, unsigned int channel) const
915 {
916  makeSureImageIsLoaded(); // For delayed loaded images stored externally
917  // [0,255]->[0,1]
918  return (*(*this)(col, row, channel)) / 255.0f;
919 }
920 
921 float CImage::getAsFloat(unsigned int col, unsigned int row) const
922 {
923  // Is a RGB image??
924  if (isColor())
925  {
926  // Luminance: Y = 0.3R + 0.59G + 0.11B
927  unsigned char* pixels = (*this)(col, row, 0);
928  return (pixels[0] * 0.3f + pixels[1] * 0.59f + pixels[2] * 0.11f) /
929  255.0f;
930  }
931  else
932  {
933  // [0,255]->[0,1]
934  return (*(*this)(col, row, 0 /* Channel 0:Gray level */)) / 255.0f;
935  }
936 }
937 
938 /*---------------------------------------------------------------
939  getMaxAsFloat
940 ---------------------------------------------------------------*/
942 {
943  int x, y, cx = getWidth(), cy = getHeight();
944 
945  float maxPixel = 0;
946 
947  for (x = 0; x < cx; x++)
948  for (y = 0; y < cy; y++) maxPixel = max(maxPixel, getAsFloat(x, y));
949 
950  return maxPixel;
951 }
952 
954 {
955  CImage ret;
956  grayscale(ret);
957  return ret;
958 }
959 
960 // Auxiliary function for both ::grayscale() and ::grayscaleInPlace()
961 #if MRPT_HAS_OPENCV
962 static bool my_img_to_grayscale(const cv::Mat& src, cv::Mat& dest)
963 {
964  if (dest.size() != src.size() || dest.type() != src.type())
965  dest = cv::Mat(src.rows, src.cols, CV_8UC1);
966 
967 // If possible, use SSE optimized version:
968 #if MRPT_HAS_SSE3
969  if ((src.step[0] & 0x0f) == 0 && (dest.step[0] & 0x0f) == 0)
970  {
972  src.ptr<uint8_t>(), dest.ptr<uint8_t>(), src.cols, src.rows,
973  src.step[0], dest.step[0]);
974  return true;
975  }
976 #endif
977  // OpenCV Method:
978  cv::cvtColor(src, dest, CV_BGR2GRAY);
979  return false;
980 }
981 #endif
982 
983 bool CImage::grayscale(CImage& ret) const
984 {
985 #if MRPT_HAS_OPENCV
986  // The image is already grayscale??
987  makeSureImageIsLoaded(); // For delayed loaded images stored externally
988  if (m_impl->img.channels() == 1)
989  {
990  ret = *this; // shallow copy
991  return true;
992  }
993  else
994  {
995  // Convert to a single luminance channel image
996  cv::Mat src = m_impl->img;
997  // Detect in-place op and make deep copy:
998  if (src.data == ret.m_impl->img.data) src = src.clone();
999 
1000  return my_img_to_grayscale(src, ret.m_impl->img);
1001  }
1002 #else
1003  THROW_EXCEPTION("Operation not supported: build MRPT against OpenCV!");
1004 #endif
1005 }
1006 
1008 {
1009 #if MRPT_HAS_OPENCV
1010  makeSureImageIsLoaded(); // For delayed loaded images stored externally
1011  // Get this image size:
1012  auto& img = m_impl->img;
1013  const int w = img.cols, h = img.rows;
1014 
1015  // Create target image:
1016  out.resize(w >> 1, h >> 1, getChannelCount());
1017  auto& img_out = out.m_impl->img;
1018 
1019  // If possible, use SSE optimized version:
1020 #if MRPT_HAS_SSE3
1021  if (img.channels() == 3 && interp == IMG_INTERP_NN)
1022  {
1024  img.data, img_out.data, w, h, img.step[0], img_out.step[0]);
1025  return true;
1026  }
1027 #endif
1028 #if MRPT_HAS_SSE2
1029  if (img.channels() == 1)
1030  {
1031  if (interp == IMG_INTERP_NN)
1032  {
1034  img.data, img_out.data, w, h, img.step[0], img_out.step[0]);
1035  return true;
1036  }
1037  else if (interp == IMG_INTERP_LINEAR)
1038  {
1040  img.data, img_out.data, w, h, img.step[0], img_out.step[0]);
1041  return true;
1042  }
1043  }
1044 #endif
1045 
1046  // Fall back to slow method:
1047  cv::resize(
1048  img, img_out, img_out.size(), 0, 0, interpolationMethod2Cv(interp));
1049  return false;
1050 #else
1051  THROW_EXCEPTION("Operation not supported: build MRPT against OpenCV!");
1052 #endif
1053 }
1054 
1056 {
1057  out = *this;
1058  const TImageSize siz = this->getSize();
1059  out.scaleImage(out, siz.x * 2, siz.y * 2, interp);
1060 }
1061 
1063  unsigned int width, unsigned int height, unsigned int bytesPerRow,
1064  unsigned char* red, unsigned char* green, unsigned char* blue)
1065 {
1066 #if MRPT_HAS_OPENCV
1067  MRPT_START
1068 
1070 
1071  // Copy the image data:
1072  for (unsigned int y = 0; y < height; y++)
1073  {
1074  // The target pixels:
1075  auto* dest = m_impl->img.ptr<uint8_t>(y);
1076 
1077  // Source channels:
1078  unsigned char* srcR = red + bytesPerRow * y;
1079  unsigned char* srcG = green + bytesPerRow * y;
1080  unsigned char* srcB = blue + bytesPerRow * y;
1081 
1082  for (unsigned int x = 0; x < width; x++)
1083  {
1084  *(dest++) = *(srcB++);
1085  *(dest++) = *(srcG++);
1086  *(dest++) = *(srcR++);
1087  } // end of x
1088  } // end of y
1089 
1090  MRPT_END
1091 #endif
1092 }
1093 
1094 void CImage::setPixel(int x, int y, size_t color)
1095 {
1096 #if MRPT_HAS_OPENCV
1097 
1098 #if defined(_DEBUG) || (MRPT_ALWAYS_CHECKS_DEBUG)
1099  MRPT_START
1100 #endif
1101 
1102  makeSureImageIsLoaded(); // For delayed loaded images stored externally
1103  auto& img = m_impl->img;
1104 
1106 
1107  if (x >= 0 && y >= 0 && y < img.rows && x < img.cols)
1108  {
1109  // The pixel coordinates is valid:
1110  if (img.channels() == 1)
1111  {
1112  img.ptr<uint8_t>(y)[x] = static_cast<uint8_t>(color);
1113  }
1114  else
1115  {
1116 #if defined(_DEBUG) || (MRPT_ALWAYS_CHECKS_DEBUG)
1117  ASSERT_(img.channels() == 3);
1118 #endif
1119  auto* dest = &img.ptr<uint8_t>(y)[3 * x];
1120  const auto* src = reinterpret_cast<uint8_t*>(&color);
1121  // Copy the color:
1122  *dest++ = *src++; // R
1123  *dest++ = *src++; // G
1124  *dest++ = *src++; // B
1125  }
1126  }
1127 
1128 #if defined(_DEBUG) || (MRPT_ALWAYS_CHECKS_DEBUG)
1129  MRPT_END
1130 #endif
1131 
1132 #endif
1133 }
1134 
1136  int x0, int y0, int x1, int y1, const mrpt::img::TColor color,
1137  unsigned int width, [[maybe_unused]] TPenStyle penStyle)
1138 {
1139 #if MRPT_HAS_OPENCV
1140  makeSureImageIsLoaded(); // For delayed loaded images stored externally
1141 
1142  cv::line(
1143  m_impl->img, cv::Point(x0, y0), cv::Point(x1, y1),
1144  CV_RGB(color.R, color.G, color.B), static_cast<int>(width));
1145 #endif
1146 }
1147 
1149  int x, int y, int radius, const mrpt::img::TColor& color,
1150  unsigned int width)
1151 {
1152 #if MRPT_HAS_OPENCV
1153  makeSureImageIsLoaded(); // For delayed loaded images stored externally
1154  cv::circle(
1155  m_impl->img, cv::Point(x, y), radius, CV_RGB(color.R, color.G, color.B),
1156  static_cast<int>(width));
1157 #endif
1158 }
1159 
1161 {
1162 #if MRPT_HAS_OPENCV
1164  img.makeSureImageIsLoaded();
1165 
1166  cv::Rect roi(cv::Point(x, y), cv::Size(img.getWidth(), img.getHeight()));
1167  cv::Mat dest = m_impl->img(roi);
1168  img.m_impl->img.copyTo(dest);
1169 #endif
1170 }
1171 
1173  const CImage& patch, const unsigned int col_, const unsigned int row_)
1174 {
1175 #if MRPT_HAS_OPENCV
1176  makeSureImageIsLoaded(); // For delayed loaded images stored externally
1177  const auto& src = m_impl->img;
1178  auto& dest = patch.m_impl->img;
1179 
1180  src(cv::Rect(col_, row_, dest.cols, dest.rows)).copyTo(dest);
1181 #endif
1182 }
1183 
1185  CImage& patch, const unsigned int col_, const unsigned int row_,
1186  const unsigned int col_num, const unsigned int row_num) const
1187 {
1188 #if MRPT_HAS_OPENCV
1189  makeSureImageIsLoaded(); // For delayed loaded images stored externally
1190  const auto& src = m_impl->img;
1191  auto& dest = patch.m_impl->img;
1192 
1193  src(cv::Rect(col_, row_, col_num, row_num)).copyTo(dest);
1194 #endif
1195 }
1196 
1198  const CImage& img2, int width_init, int height_init) const
1199 {
1200 #if MRPT_HAS_OPENCV
1201  makeSureImageIsLoaded(); // For delayed loaded images stored externally
1202 
1203  if ((img2.getWidth() + width_init > getWidth()) |
1204  (img2.getHeight() + height_init > getHeight()))
1205  THROW_EXCEPTION("Correlation Error!, image to correlate out of bounds");
1206 
1207  unsigned int i, j;
1208  float x1, x2;
1209  float syy = 0.0f, sxy = 0.0f, sxx = 0.0f, m1 = 0.0f, m2 = 0.0f,
1210  n = (float)(img2.getHeight() * img2.getWidth());
1211  // IplImage *ipl1 = (*this).img;
1212  // IplImage *ipl2 = img2.img;
1213 
1214  // find the means
1215  for (i = 0; i < img2.getHeight(); i++)
1216  {
1217  for (j = 0; j < img2.getWidth(); j++)
1218  {
1219  m1 += *(*this)(
1220  j + width_init,
1221  i + height_init); //(double)(ipl1->imageData[i*ipl1->widthStep
1222  //+ j ]);
1223  m2 += *img2(
1224  j, i); //(double)(ipl2->imageData[i*ipl2->widthStep + j ]);
1225  } //[ row * ipl->widthStep + col * ipl->nChannels + channel ];
1226  }
1227  m1 /= n;
1228  m2 /= n;
1229 
1230  for (i = 0; i < img2.getHeight(); i++)
1231  {
1232  for (j = 0; j < img2.getWidth(); j++)
1233  {
1234  x1 = *(*this)(j + width_init, i + height_init) -
1235  m1; //(double)(ipl1->imageData[i*ipl1->widthStep
1236  //+ j]) - m1;
1237  x2 = *img2(j, i) - m2; //(double)(ipl2->imageData[i*ipl2->widthStep
1238  //+ j]) - m2;
1239  sxx += x1 * x1;
1240  syy += x2 * x2;
1241  sxy += x1 * x2;
1242  }
1243  }
1244 
1245  return sxy / sqrt(sxx * syy);
1246 #else
1247  return 0;
1248 #endif
1249 }
1250 
1252 {
1253 #if MRPT_HAS_OPENCV
1254  makeSureImageIsLoaded(); // For delayed loaded images stored externally
1255  cv::normalize(m_impl->img, m_impl->img, 255, 0, cv::NORM_MINMAX);
1256 #endif
1257 }
1258 
1260  CMatrixFloat& outMatrix, bool doResize, int x_min, int y_min, int x_max,
1261  int y_max, bool normalize_01) const
1262 {
1263 #if MRPT_HAS_OPENCV
1264  MRPT_START
1265  makeSureImageIsLoaded(); // For delayed loaded images stored externally
1266 
1267  const auto& img = m_impl->img;
1268 
1269  // Set sizes:
1270  if (x_max == -1) x_max = img.cols - 1;
1271  if (y_max == -1) y_max = img.rows - 1;
1272 
1273  ASSERT_(x_min >= 0 && x_min < img.cols && x_min < x_max);
1274  ASSERT_(y_min >= 0 && y_min < img.rows && y_min < y_max);
1275 
1276  int lx = (x_max - x_min + 1);
1277  int ly = (y_max - y_min + 1);
1278 
1279  if (doResize || outMatrix.rows() < ly || outMatrix.cols() < lx)
1280  outMatrix.setSize(y_max - y_min + 1, x_max - x_min + 1);
1281 
1282  if (isColor())
1283  {
1284  // Luminance: Y = 0.3R + 0.59G + 0.11B
1285  for (int y = 0; y < ly; y++)
1286  {
1287  const uint8_t* pixels = ptr<uint8_t>(x_min, y_min + y);
1288  for (int x = 0; x < lx; x++)
1289  {
1290  float aux = *pixels++ * 0.3f;
1291  aux += *pixels++ * 0.59f;
1292  aux += *pixels++ * 0.11f;
1293  if (normalize_01) aux *= (1.0f / 255);
1294  outMatrix.coeffRef(y, x) = aux;
1295  }
1296  }
1297  }
1298  else
1299  {
1300  for (int y = 0; y < ly; y++)
1301  {
1302  const uint8_t* pixels = ptr<uint8_t>(x_min, y_min + y);
1303  for (int x = 0; x < lx; x++)
1304  {
1305  float aux = (*pixels++);
1306  if (normalize_01) aux *= (1.0f / 255);
1307  outMatrix.coeffRef(y, x) = aux;
1308  }
1309  }
1310  }
1311 
1312  MRPT_END
1313 #endif
1314 }
1315 
1318  mrpt::math::CMatrixFloat& B, bool doResize, int x_min, int y_min, int x_max,
1319  int y_max) const
1320 {
1321 #if MRPT_HAS_OPENCV
1322  MRPT_START
1323 
1324  makeSureImageIsLoaded(); // For delayed loaded images stored externally
1325  const auto& img = m_impl->img;
1326 
1327  // Set sizes:
1328  if (x_max == -1) x_max = img.cols - 1;
1329  if (y_max == -1) y_max = img.rows - 1;
1330 
1331  ASSERT_(x_min >= 0 && x_min < img.cols && x_min < x_max);
1332  ASSERT_(y_min >= 0 && y_min < img.rows && y_min < y_max);
1333 
1334  int lx = (x_max - x_min + 1);
1335  int ly = (y_max - y_min + 1);
1336 
1337  if (doResize || R.rows() < ly || R.cols() < lx) R.setSize(ly, lx);
1338  if (doResize || G.rows() < ly || G.cols() < lx) G.setSize(ly, lx);
1339  if (doResize || B.rows() < ly || B.cols() < lx) B.setSize(ly, lx);
1340 
1341  if (isColor())
1342  {
1343  for (int y = 0; y < ly; y++)
1344  {
1345  const uint8_t* pixels = ptr<uint8_t>(x_min, y_min + y);
1346  for (int x = 0; x < lx; x++)
1347  {
1348  float aux = *pixels++ * (1.0f / 255);
1349  R.coeffRef(y, x) = aux;
1350  aux = *pixels++ * (1.0f / 255);
1351  G.coeffRef(y, x) = aux;
1352  aux = *pixels++ * (1.0f / 255);
1353  B.coeffRef(y, x) = aux;
1354  }
1355  }
1356  }
1357  else
1358  {
1359  for (int y = 0; y < ly; y++)
1360  {
1361  const uint8_t* pixels = ptr<uint8_t>(x_min, y_min + y);
1362  for (int x = 0; x < lx; x++)
1363  {
1364  R.coeffRef(y, x) = (*pixels) * (1.0f / 255);
1365  G.coeffRef(y, x) = (*pixels) * (1.0f / 255);
1366  B.coeffRef(y, x) = (*pixels++) * (1.0f / 255);
1367  }
1368  }
1369  }
1370 
1371  MRPT_END
1372 #endif
1373 }
1374 
1376  const CImage& in_img, CMatrixFloat& out_corr, int u_search_ini,
1377  int v_search_ini, int u_search_size, int v_search_size, float biasThisImg,
1378  float biasInImg) const
1379 {
1380  MRPT_START
1381 
1382  makeSureImageIsLoaded(); // For delayed loaded images stored externally
1383 
1384  // Set limits:
1385  if (u_search_ini == -1) u_search_ini = 0;
1386  if (v_search_ini == -1) v_search_ini = 0;
1387  if (u_search_size == -1) u_search_size = static_cast<int>(getWidth());
1388  if (v_search_size == -1) v_search_size = static_cast<int>(getHeight());
1389 
1390  int u_search_end = u_search_ini + u_search_size - 1;
1391  int v_search_end = v_search_ini + v_search_size - 1;
1392 
1393  ASSERT_(u_search_end < static_cast<int>(getWidth()));
1394  ASSERT_(v_search_end < static_cast<int>(getHeight()));
1395 
1396  // Find smallest valid size:
1397  size_t x, y;
1398  size_t actual_lx =
1399  std::max(static_cast<size_t>(u_search_size), in_img.getWidth());
1400  size_t actual_ly =
1401  std::max(static_cast<size_t>(v_search_size), in_img.getHeight());
1402  size_t lx = mrpt::round2up<size_t>(actual_lx);
1403  size_t ly = mrpt::round2up<size_t>(actual_ly);
1404 
1405  CMatrixF i1(ly, lx), i2(ly, lx);
1406 
1407  // We fill the images with the bias, such as when we substract the bias
1408  // later on,
1409  // those pixels not really occupied by the image really becomes zero:
1410  i1.fill(biasInImg);
1411  i2.fill(biasThisImg);
1412 
1413  // Get as matrixes, padded with zeros up to power-of-two sizes:
1414  getAsMatrix(
1415  i2, false, u_search_ini, v_search_ini, u_search_ini + u_search_size - 1,
1416  v_search_ini + v_search_size - 1);
1417  in_img.getAsMatrix(i1, false);
1418 
1419  // Remove the bias now:
1420  i2 -= biasThisImg;
1421  i1 -= biasInImg;
1422 
1423  // FFT:
1424  CMatrixF I1_R, I1_I, I2_R, I2_I, ZEROS(ly, lx);
1425  math::dft2_complex(i1, ZEROS, I1_R, I1_I);
1426  math::dft2_complex(i2, ZEROS, I2_R, I2_I);
1427 
1428  // Compute the COMPLEX division of I2 by I1:
1429  for (y = 0; y < ly; y++)
1430  for (x = 0; x < lx; x++)
1431  {
1432  float r1 = I1_R(y, x);
1433  float r2 = I2_R(y, x);
1434 
1435  float ii1 = I1_I(y, x);
1436  float ii2 = I2_I(y, x);
1437 
1438  float den = square(r1) + square(ii1);
1439  I2_R(y, x) = (r1 * r2 + ii1 * ii2) / den;
1440  I2_I(y, x) = (ii2 * r1 - r2 * ii1) / den;
1441  }
1442 
1443  // IFFT:
1444  CMatrixF res_R, res_I;
1445  math::idft2_complex(I2_R, I2_I, res_R, res_I);
1446 
1447  out_corr.setSize(actual_ly, actual_lx);
1448  for (y = 0; y < actual_ly; y++)
1449  for (x = 0; x < actual_lx; x++)
1450  out_corr(y, x) = sqrt(square(res_R(y, x)) + square(res_I(y, x)));
1451 
1452  MRPT_END
1453 }
1454 
1456 {
1457 #if MRPT_HAS_OPENCV
1458  MRPT_START
1459 
1460  makeSureImageIsLoaded(); // For delayed loaded images stored externally
1461  const auto& img = m_impl->img;
1462 
1463  // The size of the matrix:
1464  const auto matrix_lx = outMatrix.cols();
1465  const auto matrix_ly = outMatrix.rows();
1466 
1467  if (isColor())
1468  {
1469  // Luminance: Y = 0.3R + 0.59G + 0.11B
1470  for (CMatrixFloat::Index y = 0; y < matrix_ly; y++)
1471  {
1472  unsigned char* min_pixels = (*this)(0, y % img.rows, 0);
1473  unsigned char* max_pixels = min_pixels + img.cols * 3;
1474  unsigned char* pixels = min_pixels;
1475  float aux;
1476  for (CMatrixFloat::Index x = 0; x < matrix_lx; x++)
1477  {
1478  aux = *pixels++ * 0.30f;
1479  aux += *pixels++ * 0.59f;
1480  aux += *pixels++ * 0.11f;
1481  outMatrix(y, x) = aux;
1482  if (pixels >= max_pixels) pixels = min_pixels;
1483  }
1484  }
1485  }
1486  else
1487  {
1488  for (CMatrixFloat::Index y = 0; y < matrix_ly; y++)
1489  {
1490  unsigned char* min_pixels = (*this)(0, y % img.rows, 0);
1491  unsigned char* max_pixels = min_pixels + img.cols;
1492  unsigned char* pixels = min_pixels;
1493  for (CMatrixFloat::Index x = 0; x < matrix_lx; x++)
1494  {
1495  outMatrix(y, x) = *pixels++;
1496  if (pixels >= max_pixels) pixels = min_pixels;
1497  }
1498  }
1499  }
1500 
1501  MRPT_END
1502 #endif
1503 }
1504 
1506 {
1507  // Reset to defaults:
1508  *this = CImage();
1509 }
1510 
1511 void CImage::setExternalStorage(const std::string& fileName) noexcept
1512 {
1513  clear();
1514  m_externalFile = fileName;
1515  m_imgIsExternalStorage = true;
1516 }
1517 
1518 void CImage::unload() const noexcept
1519 {
1520 #if MRPT_HAS_OPENCV
1521  if (m_imgIsExternalStorage) const_cast<cv::Mat&>(m_impl->img) = cv::Mat();
1522 #endif
1523 }
1524 
1526 {
1527 #if MRPT_HAS_OPENCV
1528  if (!m_impl->img.empty()) return; // OK, continue
1529 #endif
1530 
1532  {
1533  // Load the file:
1534  string wholeFile;
1536 
1537  const std::string tmpFile = m_externalFile;
1538 
1539  bool ret = const_cast<CImage*>(this)->loadFromFile(wholeFile);
1540 
1541  // These are removed by "loadFromFile", and that's good, just fix it
1542  // here and carry on.
1543  m_imgIsExternalStorage = true;
1544  m_externalFile = tmpFile;
1545 
1546  if (!ret)
1549  "Error loading externally-stored image from: %s",
1550  wholeFile.c_str());
1551  }
1552  else
1553  {
1555  "Trying to access uninitialized image in a non "
1556  "externally-stored "
1557  "image.");
1558  }
1559 }
1560 
1562 {
1563  ASSERT_(m_externalFile.size() > 2);
1564 
1565  if (m_externalFile[0] == '/' ||
1566  (m_externalFile[1] == ':' &&
1567  (m_externalFile[2] == '\\' || m_externalFile[2] == '/')))
1568  {
1569  out_path = m_externalFile;
1570  }
1571  else
1572  {
1573  out_path = IMAGES_PATH_BASE;
1574 
1575  size_t N = IMAGES_PATH_BASE.size() - 1;
1576  if (IMAGES_PATH_BASE[N] != '/' && IMAGES_PATH_BASE[N] != '\\')
1577  out_path += "/";
1578 
1579  out_path += m_externalFile;
1580  }
1581 }
1582 
1584 {
1585 #if MRPT_HAS_OPENCV
1587  cv::flip(m_impl->img, m_impl->img, 0 /* x-axis */);
1588 #endif
1589 }
1590 
1592 {
1593 #if MRPT_HAS_OPENCV
1595  cv::flip(m_impl->img, m_impl->img, 1 /* y-axis */);
1596 #endif
1597 }
1598 
1600 {
1601 #if MRPT_HAS_OPENCV
1602  makeSureImageIsLoaded(); // For delayed loaded images stored externally
1603  cv::cvtColor(m_impl->img, m_impl->img, cv::COLOR_RGB2BGR);
1604 #endif
1605 }
1606 
1607 void CImage::rectifyImageInPlace(void* mapX, void* mapY)
1608 {
1609 #if MRPT_HAS_OPENCV
1610  makeSureImageIsLoaded(); // For delayed loaded images stored externally
1611 
1612  auto& srcImg = m_impl->img;
1613  cv::Mat outImg(srcImg.rows, srcImg.cols, srcImg.type());
1614 
1615  auto mapXm = static_cast<cv::Mat*>(mapX);
1616  auto mapYm = static_cast<cv::Mat*>(mapX);
1617 
1618  cv::remap(srcImg, outImg, *mapXm, *mapYm, cv::INTER_CUBIC);
1619 
1620  clear();
1621  srcImg = outImg;
1622 #endif
1623 }
1624 
1626  CImage& out_img, const mrpt::img::TCamera& cameraParams) const
1627 {
1628 #if MRPT_HAS_OPENCV
1629  makeSureImageIsLoaded(); // For delayed loaded images stored externally
1630 
1631  ASSERTMSG_(
1632  out_img.m_impl->img.data != m_impl->img.data,
1633  "In-place undistort() not supported");
1634 
1635  auto& srcImg = const_cast<cv::Mat&>(m_impl->img);
1636  // This will avoid re-alloc if size already matches.
1637  out_img.resize(srcImg.cols, srcImg.rows, getChannelCount());
1638 
1639  const auto& intrMat = cameraParams.intrinsicParams;
1640  const auto& dist = cameraParams.dist;
1641 
1642  cv::Mat distM(1, 5, CV_64F, const_cast<double*>(&dist[0]));
1643  cv::Mat inMat(3, 3, CV_64F);
1644 
1645  for (int i = 0; i < 3; i++)
1646  for (int j = 0; j < 3; j++) inMat.at<double>(i, j) = intrMat(i, j);
1647 
1648  cv::undistort(srcImg, out_img.m_impl->img, inMat, distM);
1649 
1650 #endif
1651 }
1652 
1653 void CImage::filterMedian(CImage& out_img, int W) const
1654 {
1655 #if MRPT_HAS_OPENCV
1656  makeSureImageIsLoaded(); // For delayed loaded images stored externally
1657 
1658  auto srcImg = const_cast<cv::Mat&>(m_impl->img);
1659  if (this == &out_img)
1660  srcImg = srcImg.clone();
1661  else
1662  out_img.resize(srcImg.cols, srcImg.rows, getChannelCount());
1663 
1664  cv::medianBlur(srcImg, out_img.m_impl->img, W);
1665 #endif
1666 }
1667 
1668 void CImage::filterGaussian(CImage& out_img, int W, int H, double sigma) const
1669 {
1670 #if MRPT_HAS_OPENCV
1671  makeSureImageIsLoaded(); // For delayed loaded images stored externally
1672  auto srcImg = const_cast<cv::Mat&>(m_impl->img);
1673  if (this == &out_img)
1674  srcImg = srcImg.clone();
1675  else
1676  out_img.resize(srcImg.cols, srcImg.rows, getChannelCount());
1677 
1678  cv::GaussianBlur(srcImg, out_img.m_impl->img, cv::Size(W, H), sigma);
1679 #endif
1680 }
1681 
1683  CImage& out_img, unsigned int width, unsigned int height,
1685 {
1686 #if MRPT_HAS_OPENCV
1687  makeSureImageIsLoaded(); // For delayed loaded images stored externally
1688 
1689  auto srcImg = m_impl->img;
1690  // Detect in-place operation and make a deep copy if needed:
1691  if (out_img.m_impl->img.data == srcImg.data) srcImg = srcImg.clone();
1692 
1693  // Already done?
1694  if (out_img.getWidth() == width && out_img.getHeight() == height)
1695  {
1696  out_img.m_impl->img = srcImg;
1697  return;
1698  }
1699  out_img.resize(width, height, getChannelCount());
1700 
1701  // Resize:
1702  cv::resize(
1703  srcImg, out_img.m_impl->img, out_img.m_impl->img.size(), 0, 0,
1705 #endif
1706 }
1707 
1709  CImage& out_img, double ang, unsigned int cx, unsigned int cy,
1710  double scale) const
1711 {
1712 #if MRPT_HAS_OPENCV
1713  makeSureImageIsLoaded(); // For delayed loaded images stored externally
1714 
1715  auto srcImg = m_impl->img;
1716  // Detect in-place operation and make a deep copy if needed:
1717  if (out_img.m_impl->img.data == srcImg.data) srcImg = srcImg.clone();
1718 
1719  out_img.resize(getWidth(), getHeight(), getChannelCount());
1720 
1721  // Based on the blog entry:
1722  // http://blog.weisu.org/2007/12/opencv-image-rotate-and-zoom-rotation.html
1723 
1724  // Apply rotation & scale:
1725  double m[2 * 3] = {scale * cos(ang), -scale * sin(ang), 1.0 * cx,
1726  scale * sin(ang), scale * cos(ang), 1.0 * cy};
1727  cv::Mat M(2, 3, CV_64F, m);
1728 
1729  double dx = (srcImg.cols - 1) * 0.5;
1730  double dy = (srcImg.rows - 1) * 0.5;
1731  m[2] -= m[0] * dx + m[1] * dy;
1732  m[5] -= m[3] * dx + m[4] * dy;
1733 
1734  cv::warpAffine(
1735  srcImg, out_img.m_impl->img, M, out_img.m_impl->img.size(),
1736  cv::INTER_LINEAR + cv::WARP_INVERSE_MAP, cv::BORDER_REPLICATE);
1737 #endif
1738 }
1739 
1741  std::vector<TPixelCoordf>& cornerCoords, unsigned int check_size_x,
1742  unsigned int check_size_y, unsigned int lines_width, unsigned int r)
1743 {
1744 #if MRPT_HAS_OPENCV
1745 
1746  if (cornerCoords.size() != check_size_x * check_size_y) return false;
1747 
1748  auto& img = m_impl->img;
1749 
1750  unsigned int x, y, i;
1751  CvPoint prev_pt = cvPoint(0, 0);
1752  const int line_max = 8;
1753  CvScalar line_colors[8];
1754 
1755  line_colors[0] = CV_RGB(255, 0, 0);
1756  line_colors[1] = CV_RGB(255, 128, 0);
1757  line_colors[2] = CV_RGB(255, 128, 0);
1758  line_colors[3] = CV_RGB(200, 200, 0);
1759  line_colors[4] = CV_RGB(0, 255, 0);
1760  line_colors[5] = CV_RGB(0, 200, 200);
1761  line_colors[6] = CV_RGB(0, 0, 255);
1762  line_colors[7] = CV_RGB(255, 0, 255);
1763 
1764  CCanvas::selectTextFont("10x20");
1765 
1766  IplImage iplp(img);
1767  IplImage* ipl = &iplp;
1768 
1769  for (y = 0, i = 0; y < check_size_y; y++)
1770  {
1771  CvScalar color = line_colors[y % line_max];
1772  for (x = 0; x < check_size_x; x++, i++)
1773  {
1774  CvPoint pt;
1775  pt.x = cvRound(cornerCoords[i].x);
1776  pt.y = cvRound(cornerCoords[i].y);
1777 
1778  if (i != 0) cvLine(ipl, prev_pt, pt, color, lines_width);
1779 
1780  cvLine(
1781  ipl, cvPoint(pt.x - r, pt.y - r), cvPoint(pt.x + r, pt.y + r),
1782  color, lines_width);
1783  cvLine(
1784  ipl, cvPoint(pt.x - r, pt.y + r), cvPoint(pt.x + r, pt.y - r),
1785  color, lines_width);
1786 
1787  if (r > 0) cvCircle(ipl, pt, r + 1, color);
1788  prev_pt = pt;
1789 
1790  // Text label with the corner index in the first and last
1791  // corners:
1792  if (i == 0 || i == cornerCoords.size() - 1)
1794  pt.x + 5, pt.y - 5, mrpt::format("%u", i),
1796  }
1797  }
1798 
1799  return true;
1800 #else
1801  return false;
1802 #endif
1803 }
1804 
1806 {
1807  CImage ret;
1808  colorImage(ret);
1809  return ret;
1810 }
1811 
1812 void CImage::colorImage(CImage& ret) const
1813 {
1814 #if MRPT_HAS_OPENCV
1815  if (this->isColor())
1816  {
1817  if (&ret != this) ret = *this;
1818  return;
1819  }
1820 
1821  auto srcImg = m_impl->img;
1822  // Detect in-place op. and make deep copy:
1823  if (srcImg.data == ret.m_impl->img.data) srcImg = srcImg.clone();
1824 
1825  ret.resize(getWidth(), getHeight(), CH_RGB);
1826 
1827  cv::cvtColor(srcImg, ret.m_impl->img, cv::COLOR_GRAY2BGR);
1828 #endif
1829 }
1830 
1831 void CImage::joinImagesHorz(const CImage& img1, const CImage& img2)
1832 {
1833 #if MRPT_HAS_OPENCV
1834  ASSERT_(img1.getHeight() == img2.getHeight());
1835 
1836  auto im1 = img1.m_impl->img, im2 = img2.m_impl->img, img = m_impl->img;
1837  ASSERT_(im1.type() == im2.type());
1838 
1839  this->resize(im1.cols + im2.cols, im1.rows, getChannelCount());
1840 
1841  im1.copyTo(img(cv::Rect(0, 0, im1.cols, im1.rows)));
1842  im2.copyTo(img(cv::Rect(im1.cols, 0, im2.cols, im2.rows)));
1843 #endif
1844 } // end
1845 
1846 void CImage::equalizeHist(CImage& out_img) const
1847 {
1848 #if MRPT_HAS_OPENCV
1849  // Convert to a single luminance channel image
1850  auto srcImg = m_impl->img;
1851  if (this != &out_img)
1852  out_img.resize(srcImg.cols, srcImg.rows, getChannelCount());
1853  auto outImg = out_img.m_impl->img;
1854 
1855  if (srcImg.channels() == 1)
1856  cv::equalizeHist(srcImg, outImg);
1857  else
1858  THROW_EXCEPTION("Operation only supported for grayscale images");
1859 #endif
1860 }
1861 
1862 // See: https://github.com/MRPT/mrpt/issues/885
1863 // This seems a bug in GCC?
1864 #if defined(__GNUC__)
1865 #define MRPT_DISABLE_FULL_OPTIMIZATION __attribute__((optimize("O1")))
1866 #else
1867 #define MRPT_DISABLE_FULL_OPTIMIZATION
1868 #endif
1869 
1870 template <unsigned int HALF_WIN_SIZE>
1872  const uint8_t* in, const int widthStep, unsigned int x, unsigned int y,
1873  int32_t& _gxx, int32_t& _gyy, int32_t& _gxy)
1874 {
1875  const auto min_x = x - HALF_WIN_SIZE;
1876  const auto min_y = y - HALF_WIN_SIZE;
1877 
1878  int32_t gxx = 0;
1879  int32_t gxy = 0;
1880  int32_t gyy = 0;
1881 
1882  const unsigned int WIN_SIZE = 1 + 2 * HALF_WIN_SIZE;
1883 
1884  unsigned int yy = min_y;
1885  for (unsigned int iy = WIN_SIZE; iy; --iy, ++yy)
1886  {
1887  const uint8_t* ptr = in + widthStep * yy + min_x;
1888  unsigned int xx = min_x;
1889  for (unsigned int ix = WIN_SIZE; ix; --ix, ++xx, ++ptr)
1890  {
1891  const int32_t dx =
1892  static_cast<int32_t>(ptr[+1]) - static_cast<int32_t>(ptr[-1]);
1893  const int32_t dy = static_cast<int32_t>(ptr[+widthStep]) -
1894  static_cast<int32_t>(ptr[-widthStep]);
1895  gxx += dx * dx;
1896  gxy += dx * dy;
1897  gyy += dy * dy;
1898  }
1899  }
1900  _gxx = gxx;
1901  _gyy = gyy;
1902  _gxy = gxy;
1903 }
1904 
1906  const unsigned int x, const unsigned int y,
1907  const unsigned int half_window_size) const
1908 {
1909 #if MRPT_HAS_OPENCV
1910 
1911  const auto& im1 = m_impl->img;
1912  const auto img_w = static_cast<unsigned int>(im1.cols),
1913  img_h = static_cast<unsigned int>(im1.rows);
1914  const int widthStep = im1.step[0];
1915 
1916  // If any of those predefined values worked, do the generic way:
1917  const unsigned int min_x = x - half_window_size;
1918  const unsigned int max_x = x + half_window_size;
1919  const unsigned int min_y = y - half_window_size;
1920  const unsigned int max_y = y + half_window_size;
1921 
1922  // Since min_* are "unsigned", checking "<" will detect negative
1923  // numbers:
1924  ASSERTMSG_(
1925  min_x < img_w && max_x < img_w && min_y < img_h && max_y < img_h,
1926  "Window is out of image bounds");
1927 
1928  // Gradient sums: Use integers since they're much faster than
1929  // doubles/floats!!
1930  int32_t gxx = 0;
1931  int32_t gxy = 0;
1932  int32_t gyy = 0;
1933 
1934  const auto* img_data = im1.ptr<uint8_t>(0);
1935  switch (half_window_size)
1936  {
1937  case 2:
1938  image_KLT_response_template<2>(
1939  img_data, widthStep, x, y, gxx, gyy, gxy);
1940  break;
1941  case 3:
1942  image_KLT_response_template<3>(
1943  img_data, widthStep, x, y, gxx, gyy, gxy);
1944  break;
1945  case 4:
1946  image_KLT_response_template<4>(
1947  img_data, widthStep, x, y, gxx, gyy, gxy);
1948  break;
1949  case 5:
1950  image_KLT_response_template<5>(
1951  img_data, widthStep, x, y, gxx, gyy, gxy);
1952  break;
1953  case 6:
1954  image_KLT_response_template<6>(
1955  img_data, widthStep, x, y, gxx, gyy, gxy);
1956  break;
1957  case 7:
1958  image_KLT_response_template<7>(
1959  img_data, widthStep, x, y, gxx, gyy, gxy);
1960  break;
1961  case 8:
1962  image_KLT_response_template<8>(
1963  img_data, widthStep, x, y, gxx, gyy, gxy);
1964  break;
1965  case 9:
1966  image_KLT_response_template<9>(
1967  img_data, widthStep, x, y, gxx, gyy, gxy);
1968  break;
1969  case 10:
1970  image_KLT_response_template<10>(
1971  img_data, widthStep, x, y, gxx, gyy, gxy);
1972  break;
1973  case 11:
1974  image_KLT_response_template<11>(
1975  img_data, widthStep, x, y, gxx, gyy, gxy);
1976  break;
1977  case 12:
1978  image_KLT_response_template<12>(
1979  img_data, widthStep, x, y, gxx, gyy, gxy);
1980  break;
1981  case 13:
1982  image_KLT_response_template<13>(
1983  img_data, widthStep, x, y, gxx, gyy, gxy);
1984  break;
1985  case 14:
1986  image_KLT_response_template<14>(
1987  img_data, widthStep, x, y, gxx, gyy, gxy);
1988  break;
1989  case 15:
1990  image_KLT_response_template<15>(
1991  img_data, widthStep, x, y, gxx, gyy, gxy);
1992  break;
1993  case 16:
1994  image_KLT_response_template<16>(
1995  img_data, widthStep, x, y, gxx, gyy, gxy);
1996  break;
1997  case 32:
1998  image_KLT_response_template<32>(
1999  img_data, widthStep, x, y, gxx, gyy, gxy);
2000  break;
2001 
2002  default:
2003  for (unsigned int yy = min_y; yy <= max_y; yy++)
2004  {
2005  const uint8_t* p = img_data + widthStep * yy + min_x;
2006  for (unsigned int xx = min_x; xx <= max_x; xx++)
2007  {
2008  const int32_t dx = p[+1] - p[-1];
2009  const int32_t dy = p[+widthStep] - p[-widthStep];
2010  gxx += dx * dx;
2011  gxy += dx * dy;
2012  gyy += dy * dy;
2013  }
2014  }
2015  break;
2016  }
2017  // Convert to float's and normalize in the way:
2018  const float K = 0.5f / ((max_y - min_y + 1) * (max_x - min_x + 1));
2019  const float Gxx = gxx * K;
2020  const float Gxy = gxy * K;
2021  const float Gyy = gyy * K;
2022 
2023  // Return the minimum eigenvalue of:
2024  // ( gxx gxy )
2025  // ( gxy gyy )
2026  // See, for example:
2027  // mrpt::math::detail::eigenVectorsMatrix_special_2x2():
2028  const float t = Gxx + Gyy; // Trace
2029  const float de = Gxx * Gyy - Gxy * Gxy; // Det
2030  // The smallest eigenvalue is:
2031  return 0.5f * (t - std::sqrt(t * t - 4.0f * de));
2032 #else
2033  return 0;
2034 #endif
2035 }
2036 
2037 // Load from TGA files. Used in loadFromFile()
2038 // Contains code from
2039 // https://github.com/tjohnman/Simple-Targa-Library/blob/master/src/simpleTGA.cpp
2040 // (FreeBSD license)
2042  const std::string& fileName, mrpt::img::CImage& out_RGB,
2043  mrpt::img::CImage& out_alpha)
2044 {
2045 #if MRPT_HAS_OPENCV
2046  std::fstream stream;
2047  stream.open(fileName.c_str(), std::fstream::in | std::fstream::binary);
2048  if (!stream.is_open())
2049  {
2050  std::cerr << "[CImage::loadTGA] Couldn't open file '" << fileName
2051  << "'.\n";
2052  return false;
2053  }
2054 
2055  stream.seekg(0, std::ios_base::end);
2056  // long length = stream.tellg();
2057  stream.seekg(0, std::ios_base::beg);
2058 
2059  // Simple uncompressed true-color image
2060  char dumpBuffer[12];
2061  char trueColorHeader[] = "\0\0\2\0\0\0\0\0\0\0\0\0";
2062  stream.read(dumpBuffer, 12);
2063  if (memcmp(dumpBuffer, trueColorHeader, 12) != 0)
2064  {
2065  std::cerr << "[CImage::loadTGA] Unsupported format or invalid file.\n";
2066  return false;
2067  }
2068 
2069  unsigned short width, height;
2070  unsigned char bpp;
2071 
2072  stream.read((char*)&width, 2);
2073  stream.read((char*)&height, 2);
2074  bpp = stream.get();
2075  if (bpp != 32)
2076  {
2077  std::cerr << "[CImage::loadTGA] Only 32 bpp format supported!\n";
2078  return false;
2079  }
2080 
2081  unsigned char desc;
2082  desc = stream.get();
2083  if (desc != 8 && desc != 32)
2084  {
2085  std::cerr << "[CImage::loadTGA] Unsupported format or invalid file.\n";
2086  return false;
2087  }
2088  const bool origin_is_low_corner = (desc == 8);
2089 
2090  // Data section
2091  std::vector<uint8_t> bytes(width * height * 4);
2092  stream.read((char*)&bytes[0], width * height * 4);
2093  stream.close();
2094 
2095  // Move data to images:
2096  out_RGB.resize(width, height, CH_RGB);
2097  out_alpha.resize(width, height, CH_GRAY);
2098 
2099  size_t idx = 0;
2100  for (int r = 0; r < height; r++)
2101  {
2102  const auto actual_row = origin_is_low_corner ? (height - 1 - r) : r;
2103  auto& img = out_RGB.m_impl->img;
2104  auto data = img.ptr<uint8_t>(actual_row);
2105 
2106  auto& img_alpha = out_alpha.m_impl->img;
2107  auto data_alpha = img_alpha.ptr<uint8_t>(actual_row);
2108 
2109  for (unsigned int c = 0; c < width; c++)
2110  {
2111  *data++ = bytes[idx++]; // R
2112  *data++ = bytes[idx++]; // G
2113  *data++ = bytes[idx++]; // B
2114  *data_alpha++ = bytes[idx++]; // A
2115  }
2116  }
2117 
2118  return true;
2119 #else
2120  return false;
2121 #endif // MRPT_HAS_OPENCV
2122 }
2123 
2124 std::ostream& mrpt::img::operator<<(std::ostream& o, const TPixelCoordf& p)
2125 {
2126  o << "(" << p.x << "," << p.y << ")";
2127  return o;
2128 }
2129 std::ostream& mrpt::img::operator<<(std::ostream& o, const TPixelCoord& p)
2130 {
2131  o << "(" << p.x << "," << p.y << ")";
2132  return o;
2133 }
void update_patch(const CImage &patch, const unsigned int col, const unsigned int row)
Update a part of this image with the "patch" given as argument.
Definition: CImage.cpp:1172
void drawCircle(int x, int y, int radius, const mrpt::img::TColor &color=mrpt::img::TColor(255, 255, 255), unsigned int width=1) override
Draws a circle of a given radius.
Definition: CImage.cpp:1148
GLint GLenum GLsizei GLsizei GLsizei GLint GLsizei imageSize
Definition: glext.h:3749
void line(int x0, int y0, int x1, int y1, const mrpt::img::TColor color, unsigned int width=1, TPenStyle penStyle=psSolid) override
Draws a line.
Definition: CImage.cpp:1135
Used in mrpt::img::CImage.
Definition: img/CImage.h:81
void decompress(void *inData, size_t inDataSize, std::vector< unsigned char > &outData, size_t outDataEstimatedSize)
Decompress an array of bytes into another one.
Definition: zip.cpp:135
#define MRPT_START
Definition: exceptions.h:241
GLdouble GLdouble t
Definition: glext.h:3695
TPenStyle
Definition of pen styles.
Definition: CCanvas.h:55
bool drawChessboardCorners(std::vector< TPixelCoordf > &cornerCoords, unsigned int check_size_x, unsigned int check_size_y, unsigned int lines_width=1, unsigned int circles_radius=4)
Draw onto this image the detected corners of a chessboard.
Definition: CImage.cpp:1740
void getAsMatrixTiled(mrpt::math::CMatrixFloat &outMatrix) const
Returns the image as a matrix, where the image is "tiled" (repeated) the required number of times to ...
Definition: CImage.cpp:1455
void MRPT_DISABLE_FULL_OPTIMIZATION image_KLT_response_template(const uint8_t *in, const int widthStep, unsigned int x, unsigned int y, int32_t &_gxx, int32_t &_gyy, int32_t &_gxy)
Definition: CImage.cpp:1871
static bool DISABLE_ZIP_COMPRESSION()
Definition: CImage.cpp:58
unsigned char red[10]
Definition: PbMapMaker.cpp:810
#define THROW_EXCEPTION(msg)
Definition: exceptions.h:67
CImage scaleHalf(TInterpolationMethod interp) const
Returns a new image scaled down to half its original size.
Definition: img/CImage.h:313
void getAsMatrix(mrpt::math::CMatrixFloat &outMatrix, bool doResize=true, int x_min=0, int y_min=0, int x_max=-1, int y_max=-1, bool normalize_01=true) const
Returns the image as a matrix with pixel grayscale values in the range [0,1].
Definition: CImage.cpp:1259
uint8_t serializeGetVersion() const override
Must return the current versioning number of the object.
Definition: CImage.cpp:488
void image_SSE2_scale_half_smooth_1c8u(const uint8_t *in, uint8_t *out, int w, int h, size_t step_in, size_t step_out)
Average each 2x2 pixels into 1x1 pixel (arithmetic average)
#define IMPLEMENTS_SERIALIZABLE(class_name, base, NameSpace)
To be added to all CSerializable-classes implementation files.
GLenum GLenum GLenum GLenum GLenum scale
Definition: glext.h:6604
void copyFromForceLoad(const CImage &o)
Copies from another image (shallow copy), and, if it is externally stored, the image file will be act...
Definition: CImage.cpp:184
const double G
void getAsRGBMatrices(mrpt::math::CMatrixFloat &outMatrixR, mrpt::math::CMatrixFloat &outMatrixG, mrpt::math::CMatrixFloat &outMatrixB, bool doResize=true, int x_min=0, int y_min=0, int x_max=-1, int y_max=-1) const
Returns the image as RGB matrices with pixel values in the range [0,1].
Definition: CImage.cpp:1316
static bool DISABLE_JPEG_COMPRESSION()
Definition: CImage.cpp:63
GLdouble GLdouble GLdouble GLdouble q
Definition: glext.h:3727
GLenum GLsizei n
Definition: glext.h:5136
void image_SSE2_scale_half_1c8u(const uint8_t *in, uint8_t *out, int w, int h, size_t step_in, size_t step_out)
Subsample each 2x2 pixel block into 1x1 pixel, taking the first pixel & ignoring the other 3...
copy_type_t
Define kind of copies.
Definition: img/CImage.h:71
CExceptionExternalImageNotFound(const std::string &s)
Definition: CImage.cpp:76
float getMaxAsFloat() const
Return the maximum pixel value of the image, as a float value in the range [0,1]. ...
Definition: CImage.cpp:941
void drawImage(int x, int y, const mrpt::img::CImage &img) override
Draws an image as a bitmap at a given position.
Definition: CImage.cpp:1160
cv::Mat & asCvMatRef()
Get a reference to the internal cv::Mat, which can be resized, etc.
Definition: CImage.cpp:233
void flipHorizontal()
Flips the image horizontally.
Definition: CImage.cpp:1591
TImageChannels getChannelCount() const
Returns the number of channels, typically 1 (GRAY) or 3 (RGB)
Definition: CImage.cpp:898
static constexpr TColor blue()
Definition: TColor.h:62
size_t getHeight() const override
Returns the height of the image in pixels.
Definition: CImage.cpp:878
void scaleImage(CImage &out_img, unsigned int width, unsigned int height, TInterpolationMethod interp=IMG_INTERP_CUBIC) const
Scales this image to a new size, interpolating as needed, saving the new image in a different output ...
Definition: CImage.cpp:1682
std::string getChannelsOrder() const
As of mrpt 2.0.0, this returns either "GRAY" or "BGR".
Definition: CImage.cpp:857
A pair (x,y) of pixel coordinates (subpixel resolution).
Definition: TPixelCoord.h:18
void setExternalStorage(const std::string &fileName) noexcept
By using this method the image is marked as referenced to an external file, which will be loaded only...
Definition: CImage.cpp:1511
GLint GLint GLsizei GLsizei GLsizei depth
Definition: glext.h:3606
float correlate(const CImage &img2int, int width_init=0, int height_init=0) const
Computes the correlation coefficient (returned as val), between two images This function use grayscal...
Definition: CImage.cpp:1197
void makeSureImageIsLoaded() const
Checks if the image is of type "external storage", and if so and not loaded yet, load it...
Definition: CImage.cpp:1525
STL namespace.
void filterGaussian(CImage &out_img, int W=3, int H=3, double sigma=1.0) const
Filter the image with a Gaussian filter with a window size WxH, replacing "this" image by the filtere...
Definition: CImage.cpp:1668
void WriteBuffer(const void *Buffer, size_t Count)
Writes a block of bytes to the stream from Buffer.
Definition: CArchive.cpp:49
void joinImagesHorz(const CImage &im1, const CImage &im2)
Joins two images side-by-side horizontally.
Definition: CImage.cpp:1831
GLdouble s
Definition: glext.h:3682
GLuint src
Definition: glext.h:7397
void unload() const noexcept
For external storage image objects only, this method unloads the image from memory (or does nothing i...
Definition: CImage.cpp:1518
float getAsFloat(unsigned int col, unsigned int row, unsigned int channel) const
Returns the contents of a given pixel at the desired channel, in float format: [0,255]->[0,1] The coordinate origin is pixel(0,0)=top-left corner of the image.
Definition: CImage.cpp:913
#define MRPT_DISABLE_FULL_OPTIMIZATION
Definition: CImage.cpp:1867
GLenum GLsizei width
Definition: glext.h:3535
mrpt::pimpl< Impl > m_impl
Definition: img/CImage.h:1007
void image_SSSE3_scale_half_3c8u(const uint8_t *in, uint8_t *out, int w, int h, size_t step_in, size_t step_out)
Subsample each 2x2 pixel block into 1x1 pixel, taking the first pixel & ignoring the other 3...
GLubyte GLubyte GLubyte GLubyte w
Definition: glext.h:4199
void swap(CImage &o)
Efficiently swap of two images.
Definition: CImage.cpp:177
static std::string IMAGES_PATH_BASE(".")
void asCvMat(cv::Mat &out_img, copy_type_t copy_type) const
Makes a shallow or deep copy of this image into the provided cv::Mat.
Definition: CImage.cpp:223
unsigned char uint8_t
Definition: rptypes.h:44
#define MRPT_THROW_UNKNOWN_SERIALIZATION_VERSION(__V)
For use in CSerializable implementations.
Definition: exceptions.h:97
uint64_t getTotalBytesCount() const override
Returns the total size of the internal buffer.
T square(const T x)
Inline function for the square of a number.
void swapRB()
Swaps red and blue channels.
Definition: CImage.cpp:1599
CImage colorImage() const
Returns a color (RGB) version of the grayscale image, or a shallow copy of itself if it is already a ...
Definition: CImage.cpp:1805
GLuint color
Definition: glext.h:8459
mrpt::math::CMatrixDouble33 intrinsicParams
Matrix of intrinsic parameters (containing the focal length and principal point coordinates) ...
Definition: TCamera.h:40
#define ASSERT_(f)
Defines an assertion mechanism.
Definition: exceptions.h:120
bool loadFromFile(const std::string &fileName, int isColor=-1)
Load image from a file, whose format is determined from the extension (internally uses OpenCV)...
Definition: CImage.cpp:311
This base provides a set of functions for maths stuff.
static int SERIALIZATION_JPEG_QUALITY_value
Definition: CImage.cpp:51
RET pixelDepth2IPLCvDepth(PixelDepth d)
Definition: CImage.cpp:128
size_t getWidth() const override
Returns the width of the image in pixels.
Definition: CImage.cpp:847
float KLT_response(const unsigned int x, const unsigned int y, const unsigned int half_window_size) const
Compute the KLT response at a given pixel (x,y) - Only for grayscale images (for efficiency it avoids...
Definition: CImage.cpp:1905
void resize(std::size_t width, std::size_t height, TImageChannels nChannels, PixelDepth depth=PixelDepth::D8U)
Changes the size of the image, erasing previous contents (does NOT scale its current content...
Definition: CImage.cpp:253
mrpt::system::CTimeLogger CTimeLogger
unsigned char * operator()(unsigned int col, unsigned int row, unsigned int channel=0) const
Returns a pointer to a given pixel information.
Definition: CImage.cpp:432
void normalize(CONTAINER &c, Scalar valMin, Scalar valMax)
Scales all elements such as the minimum & maximum values are shifted to the given values...
virtual void selectTextFont(const std::string &fontName)
Select the current font used when drawing text.
Definition: CCanvas.cpp:228
__int64 int64_t
Definition: rptypes.h:52
void * getRawBufferData()
Method for getting a pointer to the raw stored data.
const GLubyte * c
Definition: glext.h:6406
This CStream derived class allow using a memory buffer as a CStream.
GLint GLvoid * img
Definition: glext.h:3769
void internal_fromIPL(const IplImage *iplImage, copy_type_t c)
Definition: CImage.cpp:357
void saveToStreamAsJPEG(mrpt::io::CStream &out, const int jpeg_quality=95) const
Save image to binary stream as a JPEG (.jpg) compressed format.
GLuint GLuint end
Definition: glext.h:3532
void normalize()
Optimize the brightness range of an image without using histogram Only for one channel images...
Definition: CImage.cpp:1251
uint64_t Seek(int64_t Offset, CStream::TSeekOrigin Origin=sFromBeginning) override
Introduces a pure virtual method for moving to a specified position in the streamed resource...
static PixelDepth cvDepth2PixelDepth(int64_t d)
Definition: CImage.cpp:145
A pair (x,y) of pixel coordinates (integer resolution).
Definition: TPixelCoord.h:39
void flipVertical()
Flips the image vertically.
Definition: CImage.cpp:1583
int val
Definition: mrpt_jpeglib.h:957
uint8_t * get_unsafe(unsigned int col, unsigned int row, uint8_t channel=0) const
Access to pixels without checking boundaries - Use normally the () operator better, which checks the coordinates.
Definition: CImage.cpp:482
#define IMPLEMENTS_MEXPLUS_FROM(complete_type)
Structure to hold the parameters of a pinhole camera model.
Definition: TCamera.h:25
#define ASSERTMSG_(f, __ERROR_MSG)
Defines an assertion mechanism.
Definition: exceptions.h:108
static bool DISABLE_ZIP_COMPRESSION_value
Definition: CImage.cpp:49
void loadFromStreamAsJPEG(mrpt::io::CStream &in)
Reads the image from a binary stream containing a binary jpeg file.
void rectifyImageInPlace(void *mapX, void *mapY)
Rectify an image (undistorts and rectification) from a stereo pair according to a pair of precomputed...
Definition: CImage.cpp:1607
void serializeFrom(mrpt::serialization::CArchive &in, uint8_t serial_version) override
Pure virtual method for reading (deserializing) from an abstract archive.
Definition: CImage.cpp:607
TImageSize getSize() const
Return the size of the image.
Definition: img/CImage.h:643
GLsizei const GLchar ** string
Definition: glext.h:4116
GLint GLint GLsizei GLsizei GLsizei GLint GLenum GLenum const GLvoid * pixels
Definition: glext.h:3606
size_type rows() const
Number of rows in the matrix.
size_type cols() const
Number of columns in the matrix.
void clear()
Resets the image to the state after a default ctor.
Definition: CImage.cpp:1505
uint8_t * internal_get(int col, int row, uint8_t channel=0) const
Definition: CImage.cpp:470
struct mxArray_tag mxArray
Forward declaration for mxArray (avoid #including as much as possible to speed up compiling) ...
Definition: CSerializable.h:18
CImage grayscale() const
Returns a grayscale version of the image, or a shallow copy of itself if it is already a grayscale im...
Definition: CImage.cpp:953
void cross_correlation_FFT(const CImage &in_img, math::CMatrixFloat &out_corr, int u_search_ini=-1, int v_search_ini=-1, int u_search_size=-1, int v_search_size=-1, float biasThisImg=0, float biasInImg=0) const
Computes the correlation matrix between this image and another one.
Definition: CImage.cpp:1375
void idft2_complex(const CMatrixFloat &in_real, const CMatrixFloat &in_imag, CMatrixFloat &out_real, CMatrixFloat &out_imag)
Compute the 2D inverse Discrete Fourier Transform (DFT).
Definition: fourier.cpp:1332
std::array< double, 5 > dist
[k1 k2 t1 t2 k3] -> k_i: parameters of radial distortion, t_i: parameters of tangential distortion (d...
Definition: TCamera.h:43
void setPixel(int x, int y, size_t color) override
Changes the value of the pixel (x,y).
Definition: CImage.cpp:1094
__int32 int32_t
Definition: rptypes.h:49
PixelDepth getPixelDepth() const
Definition: CImage.cpp:300
This class is a "CSerializable" wrapper for "CMatrixFloat".
Definition: CMatrixF.h:22
This is the global namespace for all Mobile Robot Programming Toolkit (MRPT) libraries.
void filterMedian(CImage &out_img, int W=3) const
Filter the image with a Median filter with a window size WxW, returning the filtered image in out_img...
Definition: CImage.cpp:1653
CImage()
Default constructor: initialize to empty image.
Definition: CImage.cpp:165
Virtual base class for "archives": classes abstracting I/O streams.
Definition: CArchive.h:53
#define MRPT_TODO(x)
Definition: common.h:129
GLdouble GLdouble GLdouble r
Definition: glext.h:3711
CImage makeDeepCopy() const
Returns a deep copy of this image.
Definition: CImage.cpp:212
bool isColor() const
Returns true if the image is RGB, false if it is grayscale.
Definition: CImage.cpp:888
TInterpolationMethod
Interpolation methods for images.
Definition: img/CImage.h:49
bool isOriginTopLeft() const
Returns true (as of MRPT v2.0.0, it&#39;s fixed)
Definition: CImage.cpp:908
GLclampf green
Definition: glext.h:3529
const float R
struct _IplImage IplImage
Definition: img/CImage.h:21
virtual mxArray * writeToMatlab() const
Introduces a pure virtual method responsible for writing to a mxArray Matlab object, typically a MATLAB struct whose contents are documented in each derived class.
Definition: CSerializable.h:90
bool m_imgIsExternalStorage
Set to true only when using setExternalStorage.
Definition: img/CImage.h:1013
std::string format(const char *fmt,...) MRPT_printf_format_check(1
A std::string version of C sprintf.
Definition: format.cpp:16
Deep copy: the copied object has a duplicate of all data, becoming independent.
Definition: img/CImage.h:77
GLenum GLenum GLvoid * row
Definition: glext.h:3580
void setSize(size_t row, size_t col, bool zeroNewElements=false)
Changes the size of matrix, maintaining the previous contents.
#define MRPT_END
Definition: exceptions.h:245
size_t getRowStride() const
Returns the row stride of the image: this is the number of bytes between two consecutive rows...
Definition: CImage.cpp:868
GLuint in
Definition: glext.h:7391
#define MRPT_HAS_OPENCV
void changeSize(uint64_t newSize)
Change size.
CImage scaleDouble(TInterpolationMethod interp) const
Returns a new image scaled up to double its original size.
Definition: img/CImage.h:328
void serializeTo(mrpt::serialization::CArchive &out) const override
Pure virtual method for writing (serializing) to an abstract archive.
Definition: CImage.cpp:496
void rotateImage(CImage &out_img, double ang, unsigned int cx, unsigned int cy, double scale=1.0) const
Rotates the image by the given angle around the given center point, with an optional scale factor...
Definition: CImage.cpp:1708
void extract_patch(CImage &patch, const unsigned int col=0, const unsigned int row=0, const unsigned int width=1, const unsigned int height=1) const
Extract a patch from this image, saveing it into "patch" (its previous contents will be overwritten)...
Definition: CImage.cpp:1184
GLenum GLint GLint y
Definition: glext.h:3542
constexpr RET pixelDepth2CvDepth(PixelDepth d)
Definition: CImage.cpp:111
pimpl< T > make_impl(Args &&... args)
Definition: pimpl.h:18
virtual void textOut(int x0, int y0, const std::string &str, const mrpt::img::TColor color)
Renders 2D text using bitmap fonts.
Definition: CCanvas.cpp:375
static int interpolationMethod2Cv(TInterpolationMethod i)
Definition: CImage.cpp:96
void image_SSSE3_bgr_to_gray_8u(const uint8_t *in, uint8_t *out, int w, int h, size_t step_in, size_t step_out)
Convert a RGB image (3cu8) into a GRAYSCALE (1c8u) image, using Y=77*R+150*G+29*B.
bool saveToFile(const std::string &fileName, int jpeg_quality=95) const
Save the image to a file, whose format is determined from the extension (internally uses OpenCV)...
Definition: CImage.cpp:336
TImageChannels
For use in mrpt::img::CImage.
Definition: img/CImage.h:58
static int SERIALIZATION_JPEG_QUALITY()
Definition: CImage.cpp:71
static bool DISABLE_JPEG_COMPRESSION_value
Definition: CImage.cpp:50
GLuint interp
Definition: glext.h:7247
A RGB color - 8bit.
Definition: TColor.h:20
GLclampf GLclampf blue
Definition: glext.h:3529
GLenum GLint x
Definition: glext.h:3542
void undistort(CImage &out_img, const mrpt::img::TCamera &cameraParams) const
Undistort the image according to some camera parameters, and returns an output undistorted image...
Definition: CImage.cpp:1625
std::ostream & operator<<(std::ostream &o, const TColor &c)
Definition: TColor.cpp:76
void compress(void *inData, size_t inDataSize, std::vector< unsigned char > &outData)
Compress an array of bytes into another one.
Definition: zip.cpp:35
GLenum GLsizei GLsizei height
Definition: glext.h:3558
void dft2_complex(const CMatrixFloat &in_real, const CMatrixFloat &in_imag, CMatrixFloat &out_real, CMatrixFloat &out_imag)
Compute the 2D Discrete Fourier Transform (DFT) of a complex matrix, returning the real and imaginary...
Definition: fourier.cpp:1227
unsigned __int32 uint32_t
Definition: rptypes.h:50
std::string getExternalStorageFileAbsolutePath() const
Only if isExternallyStored() returns true.
Definition: img/CImage.h:777
This template class provides the basic functionality for a general 2D any-size, resizable container o...
GLsizei GLsizei GLenum GLenum const GLvoid * data
Definition: glext.h:3550
GLfloat GLfloat p
Definition: glext.h:6398
std::string m_externalFile
The file name of a external storage image.
Definition: img/CImage.h:1016
GLenum const GLfloat * params
Definition: glext.h:3538
void clear()
Clear the contents of this container.
Definition: ts_hash_map.h:182
static void setImagesPathBase(const std::string &path)
Definition: CImage.cpp:83
void equalizeHist(CImage &out_img) const
Equalize the image histogram, saving the new image in the given output object.
Definition: CImage.cpp:1846
#define THROW_TYPED_EXCEPTION_FMT(exceptionClass, _FORMAT_STRING,...)
Definition: exceptions.h:72
void forceLoad() const
For external storage image objects only, this method makes sure the image is loaded in memory...
Definition: img/CImage.h:789
static bool loadTGA(const std::string &fileName, mrpt::img::CImage &out_RGB, mrpt::img::CImage &out_alpha)
Loads a TGA true-color RGBA image as two CImage objects, one for the RGB channels plus a separate gra...
Definition: CImage.cpp:2041
static bool my_img_to_grayscale(const cv::Mat &src, cv::Mat &dest)
Definition: CImage.cpp:962
A class for storing images as grayscale or RGB bitmaps.
Definition: img/CImage.h:147
void memcpy(void *dest, size_t destSize, const void *src, size_t copyCount) noexcept
An OS and compiler independent version of "memcpy".
Definition: os.cpp:358
void loadFromMemoryBuffer(unsigned int width, unsigned int height, bool color, unsigned char *rawpixels, bool swapRedBlue=false)
Reads the image from raw pixels buffer in memory.
Definition: CImage.cpp:371
Scalar & coeffRef(int r, int c)
static const std::string & getImagesPathBase()
By default, ".".
Definition: CImage.cpp:82



Page generated by Doxygen 1.8.14 for MRPT 1.9.9 Git: 8fe78517f Sun Jul 14 19:43:28 2019 +0200 at lun oct 28 02:10:00 CET 2019