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



Page generated by Doxygen 1.8.14 for MRPT 1.9.9 Git: d1962bc6a Wed Jan 15 17:38:30 2020 +0100 at miƩ ene 15 17:45:11 CET 2020