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-2020, 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 = cvIplImage(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 = cvIplImage(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  return;
505  }
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:
558 
559  const auto nBytes =
560  static_cast<uint32_t>(aux.getTotalBytesCount());
561 
562  out << nBytes;
563  out.WriteBuffer(aux.getRawBufferData(), nBytes);
564  }
565  }
566  else
567  { // (New in v8)
568  // Don't JPEG-compress behavior:
569  // Use negative image sizes to signal this behavior:
570  const int32_t neg_width = -width;
571  const int32_t neg_height = -height;
572 
573  out << neg_width << neg_height;
574 
575  // Dump raw image data:
576  const auto bytes_per_row = width * 3;
577 
578  out.WriteBuffer(m_impl->img.data, bytes_per_row * height);
579  }
580  }
581 
582 #endif
583 }
584 
586 {
587 #if !MRPT_HAS_OPENCV
588  if (version == 100)
589  {
592  in >> m_externalFile;
593  else
594  {
596  "[CImage] Cannot deserialize image since MRPT has been "
597  "compiled without OpenCV");
598  }
599  }
600 #else
601  // First, free current image.
602  clear();
603 
604  switch (version)
605  {
606  case 100: // Saved from an MRPT build without OpenCV:
607  {
610  }
611  break;
612  case 0:
613  {
614  uint32_t width, height, nChannels, imgLength;
615  uint8_t originTopLeft;
616 
617  in >> width >> height >> nChannels >> originTopLeft >> imgLength;
618 
619  resize(width, height, static_cast<TImageChannels>(nChannels));
620  in.ReadBuffer(m_impl->img.data, imgLength);
621  }
622  break;
623  case 1:
624  {
625  // Version 1: High quality JPEG image
626  uint32_t nBytes;
627  in >> nBytes;
628  std::vector<uint8_t> buf(nBytes);
629  in.ReadBuffer(buf.data(), nBytes);
630 
632  aux.assignMemoryNotOwn(buf.data(), buf.size());
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  {
768  uint32_t nBytes;
769  in >> nBytes;
770 
771  std::vector<uint8_t> buf(nBytes);
772  in.ReadBuffer(buf.data(), nBytes);
773 
775  aux.assignMemoryNotOwn(buf.data(), buf.size());
776  aux.Seek(0);
777 
779  }
780  }
781  }
782  }
783  break;
784  default:
786  };
787 #endif
788 }
789 
790 /*---------------------------------------------------------------
791 Implements the writing to a mxArray for Matlab
792 ---------------------------------------------------------------*/
793 #if MRPT_HAS_MATLAB
794 // Add to implement mexplus::from template specialization
796 #endif
797 
799 {
800 #if MRPT_HAS_MATLAB
801  return mexplus::from(this->asCvMatRef());
802 #else
803  THROW_EXCEPTION("MRPT built without MATLAB/Mex support");
804 #endif
805 }
806 
808 {
809 #if MRPT_HAS_OPENCV
810  makeSureImageIsLoaded(); // For delayed loaded images stored externally
811  s.x = m_impl->img.cols;
812  s.y = m_impl->img.rows;
813 #else
814  THROW_EXCEPTION("MRPT built without OpenCV support");
815 #endif
816 }
817 
818 size_t CImage::getWidth() const
819 {
820 #if MRPT_HAS_OPENCV
822  return m_impl->img.cols;
823 #else
824  return 0;
825 #endif
826 }
827 
828 std::string CImage::getChannelsOrder() const
829 {
830 #if MRPT_HAS_OPENCV
831  makeSureImageIsLoaded(); // For delayed loaded images stored externally
832  IplImage ipl = cvIplImage(m_impl->img);
833  return std::string(ipl.channelSeq);
834 #else
835  THROW_EXCEPTION("MRPT built without OpenCV support");
836 #endif
837 }
838 
839 size_t CImage::getRowStride() const
840 {
841 #if MRPT_HAS_OPENCV
842  makeSureImageIsLoaded(); // For delayed loaded images stored externally
843  return m_impl->img.step[0];
844 #else
845  THROW_EXCEPTION("MRPT built without OpenCV support");
846 #endif
847 }
848 
849 size_t CImage::getHeight() const
850 {
851 #if MRPT_HAS_OPENCV
853  return m_impl->img.rows;
854 #else
855  return 0;
856 #endif
857 }
858 
859 bool CImage::isColor() const
860 {
861 #if MRPT_HAS_OPENCV
862  makeSureImageIsLoaded(); // For delayed loaded images stored externally
863  return m_impl->img.channels() == 3;
864 #else
865  THROW_EXCEPTION("MRPT built without OpenCV support");
866 #endif
867 }
868 
869 bool CImage::isEmpty() const
870 {
871 #if MRPT_HAS_OPENCV
872  return m_imgIsExternalStorage || m_impl->img.empty();
873 #else
874  THROW_EXCEPTION("MRPT built without OpenCV support");
875 #endif
876 }
877 
879 {
880 #if MRPT_HAS_OPENCV
881  makeSureImageIsLoaded(); // For delayed loaded images stored externally
882  return static_cast<TImageChannels>(m_impl->img.channels());
883 #else
884  THROW_EXCEPTION("MRPT built without OpenCV support");
885 #endif
886 }
887 
889 {
890  return true; // As of mrpt v1.9.9
891 }
892 
894  unsigned int col, unsigned int row, unsigned int channel) const
895 {
896  makeSureImageIsLoaded(); // For delayed loaded images stored externally
897  // [0,255]->[0,1]
898  return (*(*this)(col, row, channel)) / 255.0f;
899 }
900 
901 float CImage::getAsFloat(unsigned int col, unsigned int row) const
902 {
903  // Is a RGB image??
904  if (isColor())
905  {
906  // Luminance: Y = 0.3R + 0.59G + 0.11B
907  unsigned char* pixels = (*this)(col, row, 0);
908  return (pixels[0] * 0.3f + pixels[1] * 0.59f + pixels[2] * 0.11f) /
909  255.0f;
910  }
911  else
912  {
913  // [0,255]->[0,1]
914  return (*(*this)(col, row, 0 /* Channel 0:Gray level */)) / 255.0f;
915  }
916 }
917 
918 /*---------------------------------------------------------------
919  getMaxAsFloat
920 ---------------------------------------------------------------*/
922 {
923  int x, y, cx = getWidth(), cy = getHeight();
924 
925  float maxPixel = 0;
926 
927  for (x = 0; x < cx; x++)
928  for (y = 0; y < cy; y++) maxPixel = max(maxPixel, getAsFloat(x, y));
929 
930  return maxPixel;
931 }
932 
934 {
935  CImage ret;
936  grayscale(ret);
937  return ret;
938 }
939 
940 // Auxiliary function for both ::grayscale() and ::grayscaleInPlace()
941 #if MRPT_HAS_OPENCV
942 static bool my_img_to_grayscale(const cv::Mat& src, cv::Mat& dest)
943 {
944  if (dest.size() != src.size() || dest.type() != src.type())
945  dest = cv::Mat(src.rows, src.cols, CV_8UC1);
946 
947  // If possible, use SSE optimized version:
948 #if MRPT_ARCH_INTEL_COMPATIBLE
949  if ((src.step[0] & 0x0f) == 0 && (dest.step[0] & 0x0f) == 0 &&
951  {
953  src.ptr<uint8_t>(), dest.ptr<uint8_t>(), src.cols, src.rows,
954  src.step[0], dest.step[0]);
955  return true;
956  }
957 #endif
958 
959  // OpenCV Method:
960  cv::cvtColor(src, dest, CV_BGR2GRAY);
961  return false;
962 }
963 #endif
964 
965 bool CImage::grayscale(CImage& ret) const
966 {
967 #if MRPT_HAS_OPENCV
968  // The image is already grayscale??
969  makeSureImageIsLoaded(); // For delayed loaded images stored externally
970  if (m_impl->img.channels() == 1)
971  {
972  ret = *this; // shallow copy
973  return true;
974  }
975  else
976  {
977  // Convert to a single luminance channel image
978  cv::Mat src = m_impl->img;
979  // Detect in-place op and make deep copy:
980  if (src.data == ret.m_impl->img.data) src = src.clone();
981 
982  return my_img_to_grayscale(src, ret.m_impl->img);
983  }
984 #else
985  THROW_EXCEPTION("Operation not supported: build MRPT against OpenCV!");
986 #endif
987 }
988 
990 {
991 #if MRPT_HAS_OPENCV
992  makeSureImageIsLoaded(); // For delayed loaded images stored externally
993  // Get this image size:
994  auto& img = m_impl->img;
995  const int w = img.cols, h = img.rows;
996 
997  // Create target image:
998  out.resize(w >> 1, h >> 1, getChannelCount());
999  auto& img_out = out.m_impl->img;
1000 
1001 // If possible, use SSE optimized version:
1002 #if MRPT_ARCH_INTEL_COMPATIBLE
1003  if (img.channels() == 3 && interp == IMG_INTERP_NN &&
1005  {
1007  img.data, img_out.data, w, h, img.step[0], img_out.step[0]);
1008  return true;
1009  }
1010 
1011  if (img.channels() == 1 && mrpt::cpu::supports(mrpt::cpu::feature::SSE2))
1012  {
1013  if (interp == IMG_INTERP_NN)
1014  {
1016  img.data, img_out.data, w, h, img.step[0], img_out.step[0]);
1017  return true;
1018  }
1019  else if (interp == IMG_INTERP_LINEAR)
1020  {
1022  img.data, img_out.data, w, h, img.step[0], img_out.step[0]);
1023  return true;
1024  }
1025  }
1026 #endif
1027 
1028  // Fall back to slow method:
1029  cv::resize(
1030  img, img_out, img_out.size(), 0, 0, interpolationMethod2Cv(interp));
1031  return false;
1032 #else
1033  THROW_EXCEPTION("Operation not supported: build MRPT against OpenCV!");
1034 #endif
1035 }
1036 
1038 {
1039  out = *this;
1040  const TImageSize siz = this->getSize();
1041  out.scaleImage(out, siz.x * 2, siz.y * 2, interp);
1042 }
1043 
1045  unsigned int width, unsigned int height, unsigned int bytesPerRow,
1046  unsigned char* red, unsigned char* green, unsigned char* blue)
1047 {
1048 #if MRPT_HAS_OPENCV
1049  MRPT_START
1050 
1051  resize(width, height, CH_RGB, PixelDepth::D8U);
1052 
1053  // Copy the image data:
1054  for (unsigned int y = 0; y < height; y++)
1055  {
1056  // The target pixels:
1057  auto* dest = m_impl->img.ptr<uint8_t>(y);
1058 
1059  // Source channels:
1060  unsigned char* srcR = red + bytesPerRow * y;
1061  unsigned char* srcG = green + bytesPerRow * y;
1062  unsigned char* srcB = blue + bytesPerRow * y;
1063 
1064  for (unsigned int x = 0; x < width; x++)
1065  {
1066  *(dest++) = *(srcB++);
1067  *(dest++) = *(srcG++);
1068  *(dest++) = *(srcR++);
1069  } // end of x
1070  } // end of y
1071 
1072  MRPT_END
1073 #endif
1074 }
1075 
1076 void CImage::setPixel(int x, int y, size_t color)
1077 {
1078 #if MRPT_HAS_OPENCV
1079 
1080 #if defined(_DEBUG) || (MRPT_ALWAYS_CHECKS_DEBUG)
1081  MRPT_START
1082 #endif
1083 
1084  makeSureImageIsLoaded(); // For delayed loaded images stored externally
1085  auto& img = m_impl->img;
1086 
1088 
1089  if (x >= 0 && y >= 0 && y < img.rows && x < img.cols)
1090  {
1091  // The pixel coordinates is valid:
1092  if (img.channels() == 1)
1093  {
1094  img.ptr<uint8_t>(y)[x] = static_cast<uint8_t>(color);
1095  }
1096  else
1097  {
1098 #if defined(_DEBUG) || (MRPT_ALWAYS_CHECKS_DEBUG)
1099  ASSERT_(img.channels() == 3);
1100 #endif
1101  auto* dest = &img.ptr<uint8_t>(y)[3 * x];
1102  const auto* src = reinterpret_cast<uint8_t*>(&color);
1103  // Copy the color:
1104  *dest++ = *src++; // R
1105  *dest++ = *src++; // G
1106  *dest++ = *src++; // B
1107  }
1108  }
1109 
1110 #if defined(_DEBUG) || (MRPT_ALWAYS_CHECKS_DEBUG)
1111  MRPT_END
1112 #endif
1113 
1114 #endif
1115 }
1116 
1118  int x0, int y0, int x1, int y1, const mrpt::img::TColor color,
1119  unsigned int width, [[maybe_unused]] TPenStyle penStyle)
1120 {
1121 #if MRPT_HAS_OPENCV
1122  makeSureImageIsLoaded(); // For delayed loaded images stored externally
1123 
1124  cv::line(
1125  m_impl->img, cv::Point(x0, y0), cv::Point(x1, y1),
1126  CV_RGB(color.R, color.G, color.B), static_cast<int>(width));
1127 #endif
1128 }
1129 
1131  int x, int y, int radius, const mrpt::img::TColor& color,
1132  unsigned int width)
1133 {
1134 #if MRPT_HAS_OPENCV
1135  makeSureImageIsLoaded(); // For delayed loaded images stored externally
1136  cv::circle(
1137  m_impl->img, cv::Point(x, y), radius, CV_RGB(color.R, color.G, color.B),
1138  static_cast<int>(width));
1139 #endif
1140 }
1141 
1142 void CImage::drawImage(int x, int y, const mrpt::img::CImage& img)
1143 {
1144 #if MRPT_HAS_OPENCV
1146  img.makeSureImageIsLoaded();
1147 
1148  cv::Rect roi(cv::Point(x, y), cv::Size(img.getWidth(), img.getHeight()));
1149  cv::Mat dest = m_impl->img(roi);
1150  img.m_impl->img.copyTo(dest);
1151 #endif
1152 }
1153 
1155  const CImage& patch, const unsigned int col_, const unsigned int row_)
1156 {
1157 #if MRPT_HAS_OPENCV
1158  makeSureImageIsLoaded(); // For delayed loaded images stored externally
1159  const auto& src = m_impl->img;
1160  auto& dest = patch.m_impl->img;
1161 
1162  src(cv::Rect(col_, row_, dest.cols, dest.rows)).copyTo(dest);
1163 #endif
1164 }
1165 
1167  CImage& patch, const unsigned int col_, const unsigned int row_,
1168  const unsigned int col_num, const unsigned int row_num) const
1169 {
1170 #if MRPT_HAS_OPENCV
1171  makeSureImageIsLoaded(); // For delayed loaded images stored externally
1172  const auto& src = m_impl->img;
1173  auto& dest = patch.m_impl->img;
1174 
1175  src(cv::Rect(col_, row_, col_num, row_num)).copyTo(dest);
1176 #endif
1177 }
1178 
1180  const CImage& img2, int width_init, int height_init) const
1181 {
1182 #if MRPT_HAS_OPENCV
1183  makeSureImageIsLoaded(); // For delayed loaded images stored externally
1184 
1185  if ((img2.getWidth() + width_init > getWidth()) |
1186  (img2.getHeight() + height_init > getHeight()))
1187  THROW_EXCEPTION("Correlation Error!, image to correlate out of bounds");
1188 
1189  float x1, x2;
1190  float syy = 0.0f, sxy = 0.0f, sxx = 0.0f, m1 = 0.0f, m2 = 0.0f,
1191  n = (float)(img2.getHeight() * img2.getWidth());
1192 
1193  // find the means
1194  for (size_t i = 0; i < img2.getHeight(); i++)
1195  {
1196  for (size_t j = 0; j < img2.getWidth(); j++)
1197  {
1198  m1 += *(*this)(
1199  j + width_init,
1200  i + height_init); //(double)(ipl1->imageData[i*ipl1->widthStep
1201  //+ j ]);
1202  m2 += *img2(
1203  j, i); //(double)(ipl2->imageData[i*ipl2->widthStep + j ]);
1204  } //[ row * ipl->widthStep + col * ipl->nChannels + channel ];
1205  }
1206  m1 /= n;
1207  m2 /= n;
1208 
1209  for (size_t i = 0; i < img2.getHeight(); i++)
1210  {
1211  for (size_t j = 0; j < img2.getWidth(); j++)
1212  {
1213  x1 = *(*this)(j + width_init, i + height_init) -
1214  m1; //(double)(ipl1->imageData[i*ipl1->widthStep
1215  //+ j]) - m1;
1216  x2 = *img2(j, i) - m2; //(double)(ipl2->imageData[i*ipl2->widthStep
1217  //+ j]) - m2;
1218  sxx += x1 * x1;
1219  syy += x2 * x2;
1220  sxy += x1 * x2;
1221  }
1222  }
1223 
1224  return sxy / sqrt(sxx * syy);
1225 #else
1226  return 0;
1227 #endif
1228 }
1229 
1231 {
1232 #if MRPT_HAS_OPENCV
1233  makeSureImageIsLoaded(); // For delayed loaded images stored externally
1234  cv::normalize(m_impl->img, m_impl->img, 255, 0, cv::NORM_MINMAX);
1235 #endif
1236 }
1237 
1239  CMatrixFloat& outMatrix, bool doResize, int x_min, int y_min, int x_max,
1240  int y_max, bool normalize_01) const
1241 {
1242 #if MRPT_HAS_OPENCV
1243  MRPT_START
1244  makeSureImageIsLoaded(); // For delayed loaded images stored externally
1245 
1246  const auto& img = m_impl->img;
1247 
1248  // Set sizes:
1249  if (x_max == -1) x_max = img.cols - 1;
1250  if (y_max == -1) y_max = img.rows - 1;
1251 
1252  ASSERT_(x_min >= 0 && x_min < img.cols && x_min < x_max);
1253  ASSERT_(y_min >= 0 && y_min < img.rows && y_min < y_max);
1254 
1255  int lx = (x_max - x_min + 1);
1256  int ly = (y_max - y_min + 1);
1257 
1258  if (doResize || outMatrix.rows() < ly || outMatrix.cols() < lx)
1259  outMatrix.setSize(y_max - y_min + 1, x_max - x_min + 1);
1260 
1261  const bool is_color = isColor();
1262 
1263  // Luminance: Y = 0.3R + 0.59G + 0.11B
1264  for (int y = 0; y < ly; y++)
1265  {
1266  const uint8_t* pixels = ptr<uint8_t>(x_min, y_min + y);
1267  for (int x = 0; x < lx; x++)
1268  {
1269  float aux;
1270  if (is_color)
1271  {
1272  aux = *pixels++ * 0.3f;
1273  aux += *pixels++ * 0.59f;
1274  aux += *pixels++ * 0.11f;
1275  }
1276  else
1277  {
1278  aux = (*pixels++);
1279  }
1280  outMatrix.coeffRef(y, x) = aux;
1281  }
1282  }
1283  if (normalize_01) outMatrix *= (1.0f / 255);
1284 
1285  MRPT_END
1286 #endif
1287 }
1288 
1290  CMatrix_u8& outMatrix, bool doResize, int x_min, int y_min, int x_max,
1291  int y_max) const
1292 {
1293 #if MRPT_HAS_OPENCV
1294  MRPT_START
1295  makeSureImageIsLoaded(); // For delayed loaded images stored externally
1296 
1297  const auto& img = m_impl->img;
1298 
1299  // Set sizes:
1300  if (x_max == -1) x_max = img.cols - 1;
1301  if (y_max == -1) y_max = img.rows - 1;
1302 
1303  ASSERT_(x_min >= 0 && x_min < img.cols && x_min < x_max);
1304  ASSERT_(y_min >= 0 && y_min < img.rows && y_min < y_max);
1305 
1306  int lx = (x_max - x_min + 1);
1307  int ly = (y_max - y_min + 1);
1308 
1309  if (doResize || outMatrix.rows() < ly || outMatrix.cols() < lx)
1310  outMatrix.setSize(y_max - y_min + 1, x_max - x_min + 1);
1311 
1312  const bool is_color = isColor();
1313 
1314  // Luminance: Y = 0.3R + 0.59G + 0.11B
1315  for (int y = 0; y < ly; y++)
1316  {
1317  const uint8_t* pixels = ptr<uint8_t>(x_min, y_min + y);
1318  for (int x = 0; x < lx; x++)
1319  {
1320  if (is_color)
1321  {
1322  unsigned int aux = *pixels++ * 3000; // 0.3f;
1323  aux += *pixels++ * 5900; // 0.59f;
1324  aux += *pixels++ * 1100; // 0.11f;
1325  outMatrix.coeffRef(y, x) = static_cast<uint8_t>(aux / 1000);
1326  }
1327  else
1328  {
1329  outMatrix.coeffRef(y, x) = (*pixels++);
1330  }
1331  }
1332  }
1333 
1334  MRPT_END
1335 #endif
1336 }
1339  mrpt::math::CMatrixFloat& B, bool doResize, int x_min, int y_min, int x_max,
1340  int y_max) const
1341 {
1342 #if MRPT_HAS_OPENCV
1343  MRPT_START
1344 
1345  makeSureImageIsLoaded(); // For delayed loaded images stored externally
1346  const auto& img = m_impl->img;
1347 
1348  // Set sizes:
1349  if (x_max == -1) x_max = img.cols - 1;
1350  if (y_max == -1) y_max = img.rows - 1;
1351 
1352  ASSERT_(x_min >= 0 && x_min < img.cols && x_min < x_max);
1353  ASSERT_(y_min >= 0 && y_min < img.rows && y_min < y_max);
1354 
1355  int lx = (x_max - x_min + 1);
1356  int ly = (y_max - y_min + 1);
1357 
1358  if (doResize || R.rows() < ly || R.cols() < lx) R.setSize(ly, lx);
1359  if (doResize || G.rows() < ly || G.cols() < lx) G.setSize(ly, lx);
1360  if (doResize || B.rows() < ly || B.cols() < lx) B.setSize(ly, lx);
1361 
1362  const bool is_color = isColor();
1363  for (int y = 0; y < ly; y++)
1364  {
1365  const uint8_t* pixels = ptr<uint8_t>(x_min, y_min + y);
1366  for (int x = 0; x < lx; x++)
1367  {
1368  if (is_color)
1369  {
1370  R.coeffRef(y, x) = u8tof(*pixels++);
1371  G.coeffRef(y, x) = u8tof(*pixels++);
1372  B.coeffRef(y, x) = u8tof(*pixels++);
1373  }
1374  else
1375  {
1376  R.coeffRef(y, x) = G.coeffRef(y, x) = B.coeffRef(y, x) =
1377  u8tof(*pixels++);
1378  }
1379  }
1380  }
1381 
1382  MRPT_END
1383 #endif
1384 }
1385 
1388  mrpt::math::CMatrix_u8& B, bool doResize, int x_min, int y_min, int x_max,
1389  int y_max) const
1390 {
1391 #if MRPT_HAS_OPENCV
1392  MRPT_START
1393 
1394  makeSureImageIsLoaded(); // For delayed loaded images stored externally
1395  const auto& img = m_impl->img;
1396 
1397  // Set sizes:
1398  if (x_max == -1) x_max = img.cols - 1;
1399  if (y_max == -1) y_max = img.rows - 1;
1400 
1401  ASSERT_(x_min >= 0 && x_min < img.cols && x_min < x_max);
1402  ASSERT_(y_min >= 0 && y_min < img.rows && y_min < y_max);
1403 
1404  int lx = (x_max - x_min + 1);
1405  int ly = (y_max - y_min + 1);
1406 
1407  if (doResize || R.rows() < ly || R.cols() < lx) R.setSize(ly, lx);
1408  if (doResize || G.rows() < ly || G.cols() < lx) G.setSize(ly, lx);
1409  if (doResize || B.rows() < ly || B.cols() < lx) B.setSize(ly, lx);
1410 
1411  const bool is_color = isColor();
1412  for (int y = 0; y < ly; y++)
1413  {
1414  const uint8_t* pixels = ptr<uint8_t>(x_min, y_min + y);
1415  for (int x = 0; x < lx; x++)
1416  {
1417  if (is_color)
1418  {
1419  R.coeffRef(y, x) = *pixels++;
1420  G.coeffRef(y, x) = *pixels++;
1421  B.coeffRef(y, x) = *pixels++;
1422  }
1423  else
1424  {
1425  R.coeffRef(y, x) = G.coeffRef(y, x) = B.coeffRef(y, x) =
1426  *pixels++;
1427  }
1428  }
1429  }
1430 
1431  MRPT_END
1432 #endif
1433 }
1434 
1436  const CImage& in_img, CMatrixFloat& out_corr, int u_search_ini,
1437  int v_search_ini, int u_search_size, int v_search_size, float biasThisImg,
1438  float biasInImg) const
1439 {
1440  MRPT_START
1441 
1442  makeSureImageIsLoaded(); // For delayed loaded images stored externally
1443 
1444  // Set limits:
1445  if (u_search_ini == -1) u_search_ini = 0;
1446  if (v_search_ini == -1) v_search_ini = 0;
1447  if (u_search_size == -1) u_search_size = static_cast<int>(getWidth());
1448  if (v_search_size == -1) v_search_size = static_cast<int>(getHeight());
1449 
1450  int u_search_end = u_search_ini + u_search_size - 1;
1451  int v_search_end = v_search_ini + v_search_size - 1;
1452 
1453  ASSERT_(u_search_end < static_cast<int>(getWidth()));
1454  ASSERT_(v_search_end < static_cast<int>(getHeight()));
1455 
1456  // Find smallest valid size:
1457  size_t x, y;
1458  size_t actual_lx =
1459  std::max(static_cast<size_t>(u_search_size), in_img.getWidth());
1460  size_t actual_ly =
1461  std::max(static_cast<size_t>(v_search_size), in_img.getHeight());
1462  size_t lx = mrpt::round2up<size_t>(actual_lx);
1463  size_t ly = mrpt::round2up<size_t>(actual_ly);
1464 
1465  CMatrixF i1(ly, lx), i2(ly, lx);
1466 
1467  // We fill the images with the bias, such as when we substract the bias
1468  // later on,
1469  // those pixels not really occupied by the image really becomes zero:
1470  i1.fill(biasInImg);
1471  i2.fill(biasThisImg);
1472 
1473  // Get as matrixes, padded with zeros up to power-of-two sizes:
1474  getAsMatrix(
1475  i2, false, u_search_ini, v_search_ini, u_search_ini + u_search_size - 1,
1476  v_search_ini + v_search_size - 1);
1477  in_img.getAsMatrix(i1, false);
1478 
1479  // Remove the bias now:
1480  i2 -= biasThisImg;
1481  i1 -= biasInImg;
1482 
1483  // FFT:
1484  CMatrixF I1_R, I1_I, I2_R, I2_I, ZEROS(ly, lx);
1485  math::dft2_complex(i1, ZEROS, I1_R, I1_I);
1486  math::dft2_complex(i2, ZEROS, I2_R, I2_I);
1487 
1488  // Compute the COMPLEX division of I2 by I1:
1489  for (y = 0; y < ly; y++)
1490  for (x = 0; x < lx; x++)
1491  {
1492  float r1 = I1_R(y, x);
1493  float r2 = I2_R(y, x);
1494 
1495  float ii1 = I1_I(y, x);
1496  float ii2 = I2_I(y, x);
1497 
1498  float den = square(r1) + square(ii1);
1499  I2_R(y, x) = (r1 * r2 + ii1 * ii2) / den;
1500  I2_I(y, x) = (ii2 * r1 - r2 * ii1) / den;
1501  }
1502 
1503  // IFFT:
1504  CMatrixF res_R, res_I;
1505  math::idft2_complex(I2_R, I2_I, res_R, res_I);
1506 
1507  out_corr.setSize(actual_ly, actual_lx);
1508  for (y = 0; y < actual_ly; y++)
1509  for (x = 0; x < actual_lx; x++)
1510  out_corr(y, x) = sqrt(square(res_R(y, x)) + square(res_I(y, x)));
1511 
1512  MRPT_END
1513 }
1514 
1516 {
1517 #if MRPT_HAS_OPENCV
1518  MRPT_START
1519 
1520  makeSureImageIsLoaded(); // For delayed loaded images stored externally
1521  const auto& img = m_impl->img;
1522 
1523  // The size of the matrix:
1524  const auto matrix_lx = outMatrix.cols();
1525  const auto matrix_ly = outMatrix.rows();
1526 
1527  if (isColor())
1528  {
1529  // Luminance: Y = 0.3R + 0.59G + 0.11B
1530  for (CMatrixFloat::Index y = 0; y < matrix_ly; y++)
1531  {
1532  unsigned char* min_pixels = (*this)(0, y % img.rows, 0);
1533  unsigned char* max_pixels = min_pixels + img.cols * 3;
1534  unsigned char* pixels = min_pixels;
1535  float aux;
1536  for (CMatrixFloat::Index x = 0; x < matrix_lx; x++)
1537  {
1538  aux = *pixels++ * 0.30f;
1539  aux += *pixels++ * 0.59f;
1540  aux += *pixels++ * 0.11f;
1541  outMatrix(y, x) = aux;
1542  if (pixels >= max_pixels) pixels = min_pixels;
1543  }
1544  }
1545  }
1546  else
1547  {
1548  for (CMatrixFloat::Index y = 0; y < matrix_ly; y++)
1549  {
1550  unsigned char* min_pixels = (*this)(0, y % img.rows, 0);
1551  unsigned char* max_pixels = min_pixels + img.cols;
1552  unsigned char* pixels = min_pixels;
1553  for (CMatrixFloat::Index x = 0; x < matrix_lx; x++)
1554  {
1555  outMatrix(y, x) = *pixels++;
1556  if (pixels >= max_pixels) pixels = min_pixels;
1557  }
1558  }
1559  }
1560 
1561  MRPT_END
1562 #endif
1563 }
1564 
1566 {
1567  // Reset to defaults:
1568  *this = CImage();
1569 }
1570 
1571 void CImage::setExternalStorage(const std::string& fileName) noexcept
1572 {
1573  clear();
1574  m_externalFile = fileName;
1575  m_imgIsExternalStorage = true;
1576 }
1577 
1578 void CImage::unload() const noexcept
1579 {
1580 #if MRPT_HAS_OPENCV
1581  if (m_imgIsExternalStorage) const_cast<cv::Mat&>(m_impl->img) = cv::Mat();
1582 #endif
1583 }
1584 
1586 {
1587 #if MRPT_HAS_OPENCV
1588  if (!m_impl->img.empty()) return; // OK, continue
1589 #endif
1590 
1592  {
1593  // Load the file:
1594  string wholeFile;
1596 
1597  const std::string tmpFile = m_externalFile;
1598 
1599  bool ret = const_cast<CImage*>(this)->loadFromFile(wholeFile);
1600 
1601  // These are removed by "loadFromFile", and that's good, just fix it
1602  // here and carry on.
1603  m_imgIsExternalStorage = true;
1604  m_externalFile = tmpFile;
1605 
1606  if (!ret)
1609  "Error loading externally-stored image from: %s",
1610  wholeFile.c_str());
1611  }
1612  else
1613  {
1615  "Trying to access uninitialized image in a non "
1616  "externally-stored "
1617  "image.");
1618  }
1619 }
1620 
1621 void CImage::getExternalStorageFileAbsolutePath(std::string& out_path) const
1622 {
1623  ASSERT_(m_externalFile.size() > 2);
1624 
1625  if (m_externalFile[0] == '/' ||
1626  (m_externalFile[1] == ':' &&
1627  (m_externalFile[2] == '\\' || m_externalFile[2] == '/')))
1628  {
1629  out_path = m_externalFile;
1630  }
1631  else
1632  {
1633  out_path = IMAGES_PATH_BASE;
1634 
1635  size_t N = IMAGES_PATH_BASE.size() - 1;
1636  if (IMAGES_PATH_BASE[N] != '/' && IMAGES_PATH_BASE[N] != '\\')
1637  out_path += "/";
1638 
1639  out_path += m_externalFile;
1640  }
1641 }
1642 
1644 {
1645 #if MRPT_HAS_OPENCV
1647  cv::flip(m_impl->img, m_impl->img, 0 /* x-axis */);
1648 #endif
1649 }
1650 
1652 {
1653 #if MRPT_HAS_OPENCV
1655  cv::flip(m_impl->img, m_impl->img, 1 /* y-axis */);
1656 #endif
1657 }
1658 
1660 {
1661 #if MRPT_HAS_OPENCV
1662  makeSureImageIsLoaded(); // For delayed loaded images stored externally
1663  cv::cvtColor(m_impl->img, m_impl->img, cv::COLOR_RGB2BGR);
1664 #endif
1665 }
1666 
1667 void CImage::rectifyImageInPlace(void* mapX, void* mapY)
1668 {
1669 #if MRPT_HAS_OPENCV
1670  makeSureImageIsLoaded(); // For delayed loaded images stored externally
1671 
1672  auto& srcImg = m_impl->img;
1673  cv::Mat outImg(srcImg.rows, srcImg.cols, srcImg.type());
1674 
1675  auto mapXm = static_cast<cv::Mat*>(mapX);
1676  auto mapYm = static_cast<cv::Mat*>(mapX);
1677 
1678  cv::remap(srcImg, outImg, *mapXm, *mapYm, cv::INTER_CUBIC);
1679 
1680  clear();
1681  srcImg = outImg;
1682 #endif
1683 }
1684 
1686  CImage& out_img, const mrpt::img::TCamera& cameraParams) const
1687 {
1688 #if MRPT_HAS_OPENCV
1689  makeSureImageIsLoaded(); // For delayed loaded images stored externally
1690 
1691  ASSERTMSG_(
1692  out_img.m_impl->img.data != m_impl->img.data,
1693  "In-place undistort() not supported");
1694 
1695  auto& srcImg = const_cast<cv::Mat&>(m_impl->img);
1696  // This will avoid re-alloc if size already matches.
1697  out_img.resize(srcImg.cols, srcImg.rows, getChannelCount());
1698 
1699  const auto& intrMat = cameraParams.intrinsicParams;
1700  const auto& dist = cameraParams.dist;
1701 
1702  cv::Mat distM(1, dist.size(), CV_64F, const_cast<double*>(&dist[0]));
1703  cv::Mat inMat(3, 3, CV_64F);
1704 
1705  for (int i = 0; i < 3; i++)
1706  for (int j = 0; j < 3; j++) inMat.at<double>(i, j) = intrMat(i, j);
1707 
1708  cv::undistort(srcImg, out_img.m_impl->img, inMat, distM);
1709 #endif
1710 }
1711 
1712 void CImage::filterMedian(CImage& out_img, int W) const
1713 {
1714 #if MRPT_HAS_OPENCV
1715  makeSureImageIsLoaded(); // For delayed loaded images stored externally
1716 
1717  auto srcImg = const_cast<cv::Mat&>(m_impl->img);
1718  if (this == &out_img)
1719  srcImg = srcImg.clone();
1720  else
1721  out_img.resize(srcImg.cols, srcImg.rows, getChannelCount());
1722 
1723  cv::medianBlur(srcImg, out_img.m_impl->img, W);
1724 #endif
1725 }
1726 
1727 void CImage::filterGaussian(CImage& out_img, int W, int H, double sigma) const
1728 {
1729 #if MRPT_HAS_OPENCV
1730  makeSureImageIsLoaded(); // For delayed loaded images stored externally
1731  auto srcImg = const_cast<cv::Mat&>(m_impl->img);
1732  if (this == &out_img)
1733  srcImg = srcImg.clone();
1734  else
1735  out_img.resize(srcImg.cols, srcImg.rows, getChannelCount());
1736 
1737  cv::GaussianBlur(srcImg, out_img.m_impl->img, cv::Size(W, H), sigma);
1738 #endif
1739 }
1740 
1742  CImage& out_img, unsigned int width, unsigned int height,
1743  TInterpolationMethod interp) const
1744 {
1745 #if MRPT_HAS_OPENCV
1746  makeSureImageIsLoaded(); // For delayed loaded images stored externally
1747 
1748  auto srcImg = m_impl->img;
1749  // Detect in-place operation and make a deep copy if needed:
1750  if (out_img.m_impl->img.data == srcImg.data) srcImg = srcImg.clone();
1751 
1752  // Already done?
1753  if (out_img.getWidth() == width && out_img.getHeight() == height)
1754  {
1755  out_img.m_impl->img = srcImg;
1756  return;
1757  }
1758  out_img.resize(width, height, getChannelCount());
1759 
1760  // Resize:
1761  cv::resize(
1762  srcImg, out_img.m_impl->img, out_img.m_impl->img.size(), 0, 0,
1763  interpolationMethod2Cv(interp));
1764 #endif
1765 }
1766 
1768  CImage& out_img, double ang, unsigned int cx, unsigned int cy,
1769  double scale) const
1770 {
1771 #if MRPT_HAS_OPENCV
1772  makeSureImageIsLoaded(); // For delayed loaded images stored externally
1773 
1774  auto srcImg = m_impl->img;
1775  // Detect in-place operation and make a deep copy if needed:
1776  if (out_img.m_impl->img.data == srcImg.data) srcImg = srcImg.clone();
1777 
1778  out_img.resize(getWidth(), getHeight(), getChannelCount());
1779 
1780  // Based on the blog entry:
1781  // http://blog.weisu.org/2007/12/opencv-image-rotate-and-zoom-rotation.html
1782 
1783  // Apply rotation & scale:
1784  double m[2 * 3] = {scale * cos(ang), -scale * sin(ang), 1.0 * cx,
1785  scale * sin(ang), scale * cos(ang), 1.0 * cy};
1786  cv::Mat M(2, 3, CV_64F, m);
1787 
1788  double dx = (srcImg.cols - 1) * 0.5;
1789  double dy = (srcImg.rows - 1) * 0.5;
1790  m[2] -= m[0] * dx + m[1] * dy;
1791  m[5] -= m[3] * dx + m[4] * dy;
1792 
1793  cv::warpAffine(
1794  srcImg, out_img.m_impl->img, M, out_img.m_impl->img.size(),
1795  cv::INTER_LINEAR + cv::WARP_INVERSE_MAP, cv::BORDER_REPLICATE);
1796 #endif
1797 }
1798 
1800  std::vector<TPixelCoordf>& cornerCoords, unsigned int check_size_x,
1801  unsigned int check_size_y, unsigned int lines_width, unsigned int r)
1802 {
1803 #if MRPT_HAS_OPENCV
1804 
1805  if (cornerCoords.size() != check_size_x * check_size_y) return false;
1806 
1807  auto& img = m_impl->img;
1808 
1809  unsigned int x, y, i;
1810  cv::Point prev_pt = cvPoint(0, 0);
1811  const int line_max = 8;
1812  cv::Scalar line_colors[8];
1813 
1814  line_colors[0] = CV_RGB(255, 0, 0);
1815  line_colors[1] = CV_RGB(255, 128, 0);
1816  line_colors[2] = CV_RGB(255, 128, 0);
1817  line_colors[3] = CV_RGB(200, 200, 0);
1818  line_colors[4] = CV_RGB(0, 255, 0);
1819  line_colors[5] = CV_RGB(0, 200, 200);
1820  line_colors[6] = CV_RGB(0, 0, 255);
1821  line_colors[7] = CV_RGB(255, 0, 255);
1822 
1823  CCanvas::selectTextFont("10x20");
1824 
1825  for (y = 0, i = 0; y < check_size_y; y++)
1826  {
1827  const auto color = line_colors[y % line_max];
1828  for (x = 0; x < check_size_x; x++, i++)
1829  {
1830  cv::Point pt;
1831  pt.x = cvRound(cornerCoords[i].x);
1832  pt.y = cvRound(cornerCoords[i].y);
1833 
1834  if (i != 0) cv::line(img, prev_pt, pt, color, lines_width);
1835 
1836  cv::line(
1837  img, cvPoint(pt.x - r, pt.y - r), cvPoint(pt.x + r, pt.y + r),
1838  color, lines_width);
1839  cv::line(
1840  img, cvPoint(pt.x - r, pt.y + r), cvPoint(pt.x + r, pt.y - r),
1841  color, lines_width);
1842 
1843  if (r > 0) cv::circle(img, pt, r + 1, color);
1844  prev_pt = pt;
1845 
1846  // Text label with the corner index in the first and last
1847  // corners:
1848  if (i == 0 || i == cornerCoords.size() - 1)
1850  pt.x + 5, pt.y - 5, mrpt::format("%u", i),
1852  }
1853  }
1854 
1855  return true;
1856 #else
1857  return false;
1858 #endif
1859 }
1860 
1862 {
1863  CImage ret;
1864  colorImage(ret);
1865  return ret;
1866 }
1867 
1868 void CImage::colorImage(CImage& ret) const
1869 {
1870 #if MRPT_HAS_OPENCV
1871  if (this->isColor())
1872  {
1873  if (&ret != this) ret = *this;
1874  return;
1875  }
1876 
1877  auto srcImg = m_impl->img;
1878  // Detect in-place op. and make deep copy:
1879  if (srcImg.data == ret.m_impl->img.data) srcImg = srcImg.clone();
1880 
1881  ret.resize(getWidth(), getHeight(), CH_RGB);
1882 
1883  cv::cvtColor(srcImg, ret.m_impl->img, cv::COLOR_GRAY2BGR);
1884 #endif
1885 }
1886 
1887 void CImage::joinImagesHorz(const CImage& img1, const CImage& img2)
1888 {
1889 #if MRPT_HAS_OPENCV
1890  ASSERT_(img1.getHeight() == img2.getHeight());
1891 
1892  auto im1 = img1.m_impl->img, im2 = img2.m_impl->img, img = m_impl->img;
1893  ASSERT_(im1.type() == im2.type());
1894 
1895  this->resize(im1.cols + im2.cols, im1.rows, getChannelCount());
1896 
1897  im1.copyTo(img(cv::Rect(0, 0, im1.cols, im1.rows)));
1898  im2.copyTo(img(cv::Rect(im1.cols, 0, im2.cols, im2.rows)));
1899 #endif
1900 } // end
1901 
1902 void CImage::equalizeHist(CImage& out_img) const
1903 {
1904 #if MRPT_HAS_OPENCV
1905  // Convert to a single luminance channel image
1906  auto srcImg = m_impl->img;
1907  if (this != &out_img)
1908  out_img.resize(srcImg.cols, srcImg.rows, getChannelCount());
1909  auto outImg = out_img.m_impl->img;
1910 
1911  if (srcImg.channels() == 1)
1912  cv::equalizeHist(srcImg, outImg);
1913  else
1914  THROW_EXCEPTION("Operation only supported for grayscale images");
1915 #endif
1916 }
1917 
1918 // See: https://github.com/MRPT/mrpt/issues/885
1919 // This seems a bug in GCC?
1920 #if defined(__GNUC__)
1921 #define MRPT_DISABLE_FULL_OPTIMIZATION __attribute__((optimize("O1")))
1922 #else
1923 #define MRPT_DISABLE_FULL_OPTIMIZATION
1924 #endif
1925 
1926 template <unsigned int HALF_WIN_SIZE>
1928  const uint8_t* in, const int widthStep, unsigned int x, unsigned int y,
1929  int32_t& _gxx, int32_t& _gyy, int32_t& _gxy)
1930 {
1931  const auto min_x = x - HALF_WIN_SIZE;
1932  const auto min_y = y - HALF_WIN_SIZE;
1933 
1934  int32_t gxx = 0;
1935  int32_t gxy = 0;
1936  int32_t gyy = 0;
1937 
1938  const unsigned int WIN_SIZE = 1 + 2 * HALF_WIN_SIZE;
1939 
1940  unsigned int yy = min_y;
1941  for (unsigned int iy = WIN_SIZE; iy; --iy, ++yy)
1942  {
1943  const uint8_t* ptr = in + widthStep * yy + min_x;
1944  unsigned int xx = min_x;
1945  for (unsigned int ix = WIN_SIZE; ix; --ix, ++xx, ++ptr)
1946  {
1947  const int32_t dx =
1948  static_cast<int32_t>(ptr[+1]) - static_cast<int32_t>(ptr[-1]);
1949  const int32_t dy = static_cast<int32_t>(ptr[+widthStep]) -
1950  static_cast<int32_t>(ptr[-widthStep]);
1951  gxx += dx * dx;
1952  gxy += dx * dy;
1953  gyy += dy * dy;
1954  }
1955  }
1956  _gxx = gxx;
1957  _gyy = gyy;
1958  _gxy = gxy;
1959 }
1960 
1962  const unsigned int x, const unsigned int y,
1963  const unsigned int half_window_size) const
1964 {
1965 #if MRPT_HAS_OPENCV
1966 
1967  const auto& im1 = m_impl->img;
1968  const auto img_w = static_cast<unsigned int>(im1.cols),
1969  img_h = static_cast<unsigned int>(im1.rows);
1970  const int widthStep = im1.step[0];
1971 
1972  // If any of those predefined values worked, do the generic way:
1973  const unsigned int min_x = x - half_window_size;
1974  const unsigned int max_x = x + half_window_size;
1975  const unsigned int min_y = y - half_window_size;
1976  const unsigned int max_y = y + half_window_size;
1977 
1978  // Since min_* are "unsigned", checking "<" will detect negative
1979  // numbers:
1980  ASSERTMSG_(
1981  min_x < img_w && max_x < img_w && min_y < img_h && max_y < img_h,
1982  "Window is out of image bounds");
1983 
1984  // Gradient sums: Use integers since they're much faster than
1985  // doubles/floats!!
1986  int32_t gxx = 0;
1987  int32_t gxy = 0;
1988  int32_t gyy = 0;
1989 
1990  const auto* img_data = im1.ptr<uint8_t>(0);
1991  switch (half_window_size)
1992  {
1993  case 2:
1994  image_KLT_response_template<2>(
1995  img_data, widthStep, x, y, gxx, gyy, gxy);
1996  break;
1997  case 3:
1998  image_KLT_response_template<3>(
1999  img_data, widthStep, x, y, gxx, gyy, gxy);
2000  break;
2001  case 4:
2002  image_KLT_response_template<4>(
2003  img_data, widthStep, x, y, gxx, gyy, gxy);
2004  break;
2005  case 5:
2006  image_KLT_response_template<5>(
2007  img_data, widthStep, x, y, gxx, gyy, gxy);
2008  break;
2009  case 6:
2010  image_KLT_response_template<6>(
2011  img_data, widthStep, x, y, gxx, gyy, gxy);
2012  break;
2013  case 7:
2014  image_KLT_response_template<7>(
2015  img_data, widthStep, x, y, gxx, gyy, gxy);
2016  break;
2017  case 8:
2018  image_KLT_response_template<8>(
2019  img_data, widthStep, x, y, gxx, gyy, gxy);
2020  break;
2021  case 9:
2022  image_KLT_response_template<9>(
2023  img_data, widthStep, x, y, gxx, gyy, gxy);
2024  break;
2025  case 10:
2026  image_KLT_response_template<10>(
2027  img_data, widthStep, x, y, gxx, gyy, gxy);
2028  break;
2029  case 11:
2030  image_KLT_response_template<11>(
2031  img_data, widthStep, x, y, gxx, gyy, gxy);
2032  break;
2033  case 12:
2034  image_KLT_response_template<12>(
2035  img_data, widthStep, x, y, gxx, gyy, gxy);
2036  break;
2037  case 13:
2038  image_KLT_response_template<13>(
2039  img_data, widthStep, x, y, gxx, gyy, gxy);
2040  break;
2041  case 14:
2042  image_KLT_response_template<14>(
2043  img_data, widthStep, x, y, gxx, gyy, gxy);
2044  break;
2045  case 15:
2046  image_KLT_response_template<15>(
2047  img_data, widthStep, x, y, gxx, gyy, gxy);
2048  break;
2049  case 16:
2050  image_KLT_response_template<16>(
2051  img_data, widthStep, x, y, gxx, gyy, gxy);
2052  break;
2053  case 32:
2054  image_KLT_response_template<32>(
2055  img_data, widthStep, x, y, gxx, gyy, gxy);
2056  break;
2057 
2058  default:
2059  for (unsigned int yy = min_y; yy <= max_y; yy++)
2060  {
2061  const uint8_t* p = img_data + widthStep * yy + min_x;
2062  for (unsigned int xx = min_x; xx <= max_x; xx++)
2063  {
2064  const int32_t dx = p[+1] - p[-1];
2065  const int32_t dy = p[+widthStep] - p[-widthStep];
2066  gxx += dx * dx;
2067  gxy += dx * dy;
2068  gyy += dy * dy;
2069  }
2070  }
2071  break;
2072  }
2073  // Convert to float's and normalize in the way:
2074  const float K = 0.5f / ((max_y - min_y + 1) * (max_x - min_x + 1));
2075  const float Gxx = gxx * K;
2076  const float Gxy = gxy * K;
2077  const float Gyy = gyy * K;
2078 
2079  // Return the minimum eigenvalue of:
2080  // ( gxx gxy )
2081  // ( gxy gyy )
2082  // See, for example:
2083  // mrpt::math::detail::eigenVectorsMatrix_special_2x2():
2084  const float t = Gxx + Gyy; // Trace
2085  const float de = Gxx * Gyy - Gxy * Gxy; // Det
2086  // The smallest eigenvalue is:
2087  return 0.5f * (t - std::sqrt(t * t - 4.0f * de));
2088 #else
2089  return 0;
2090 #endif
2091 }
2092 
2093 // Load from TGA files. Used in loadFromFile()
2094 // Contains code from
2095 // https://github.com/tjohnman/Simple-Targa-Library/blob/master/src/simpleTGA.cpp
2096 // (FreeBSD license)
2098  const std::string& fileName, mrpt::img::CImage& out_RGB,
2099  mrpt::img::CImage& out_alpha)
2100 {
2101 #if MRPT_HAS_OPENCV
2102  std::fstream stream;
2103  stream.open(fileName.c_str(), std::fstream::in | std::fstream::binary);
2104  if (!stream.is_open())
2105  {
2106  std::cerr << "[CImage::loadTGA] Couldn't open file '" << fileName
2107  << "'.\n";
2108  return false;
2109  }
2110 
2111  stream.seekg(0, std::ios_base::end);
2112  // long length = stream.tellg();
2113  stream.seekg(0, std::ios_base::beg);
2114 
2115  // Simple uncompressed true-color image
2116  char dumpBuffer[12];
2117  char trueColorHeader[] = "\0\0\2\0\0\0\0\0\0\0\0\0";
2118  stream.read(dumpBuffer, 12);
2119  if (memcmp(dumpBuffer, trueColorHeader, 12) != 0)
2120  {
2121  std::cerr << "[CImage::loadTGA] Unsupported format or invalid file.\n";
2122  return false;
2123  }
2124 
2125  unsigned short width, height;
2126  unsigned char bpp;
2127 
2128  stream.read((char*)&width, 2);
2129  stream.read((char*)&height, 2);
2130  bpp = stream.get();
2131  if (bpp != 32)
2132  {
2133  std::cerr << "[CImage::loadTGA] Only 32 bpp format supported!\n";
2134  return false;
2135  }
2136 
2137  unsigned char desc;
2138  desc = stream.get();
2139  if (desc != 8 && desc != 32)
2140  {
2141  std::cerr << "[CImage::loadTGA] Unsupported format or invalid file.\n";
2142  return false;
2143  }
2144  const bool origin_is_low_corner = (desc == 8);
2145 
2146  // Data section
2147  std::vector<uint8_t> bytes(width * height * 4);
2148  stream.read((char*)&bytes[0], width * height * 4);
2149  stream.close();
2150 
2151  // Move data to images:
2152  out_RGB.resize(width, height, CH_RGB);
2153  out_alpha.resize(width, height, CH_GRAY);
2154 
2155  size_t idx = 0;
2156  for (int r = 0; r < height; r++)
2157  {
2158  const auto actual_row = origin_is_low_corner ? (height - 1 - r) : r;
2159  auto& img = out_RGB.m_impl->img;
2160  auto data = img.ptr<uint8_t>(actual_row);
2161 
2162  auto& img_alpha = out_alpha.m_impl->img;
2163  auto data_alpha = img_alpha.ptr<uint8_t>(actual_row);
2164 
2165  for (unsigned int c = 0; c < width; c++)
2166  {
2167  *data++ = bytes[idx++]; // R
2168  *data++ = bytes[idx++]; // G
2169  *data++ = bytes[idx++]; // B
2170  *data_alpha++ = bytes[idx++]; // A
2171  }
2172  }
2173 
2174  return true;
2175 #else
2176  return false;
2177 #endif // MRPT_HAS_OPENCV
2178 }
2179 
2181 {
2182 #if MRPT_HAS_OPENCV
2184 
2185  ASSERT_(dest != nullptr);
2186  *dest = cvIplImage(m_impl->img);
2187 #endif
2188 }
2189 
2190 std::ostream& mrpt::img::operator<<(std::ostream& o, const TPixelCoordf& p)
2191 {
2192  o << "(" << p.x << "," << p.y << ")";
2193  return o;
2194 }
2195 std::ostream& mrpt::img::operator<<(std::ostream& o, const TPixelCoord& p)
2196 {
2197  o << "(" << p.x << "," << p.y << ")";
2198  return o;
2199 }
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:1154
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:1130
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:1117
Used in mrpt::img::CImage.
Definition: img/CImage.h:82
bool isEmpty() const
Returns true if the object is in the state after default constructor.
Definition: CImage.cpp:869
double Scalar
Definition: KmUtils.h:43
#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:1799
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:1515
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:1927
#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:314
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:1238
uint8_t serializeGetVersion() const override
Must return the current versioning number of the object.
Definition: CImage.cpp:482
#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:1337
static bool DISABLE_JPEG_COMPRESSION()
Definition: CImage.cpp:57
copy_type_t
Define kind of copies.
Definition: img/CImage.h:72
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:921
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:1142
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:1651
TImageChannels getChannelCount() const
Returns the number of channels, typically 1 (GRAY) or 3 (RGB)
Definition: CImage.cpp:878
static constexpr TColor blue()
Definition: TColor.h:68
size_t getHeight() const override
Returns the height of the image in pixels.
Definition: CImage.cpp:849
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:1741
std::string getChannelsOrder() const
As of mrpt 2.0.0, this returns either "GRAY" or "BGR".
Definition: CImage.cpp:828
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:1571
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:1179
void makeSureImageIsLoaded() const
Checks if the image is of type "external storage", and if so and not loaded yet, load it...
Definition: CImage.cpp:1585
STL namespace.
uint8_t B
Definition: TColor.h:51
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:1727
void joinImagesHorz(const CImage &im1, const CImage &im2)
Joins two images side-by-side horizontally.
Definition: CImage.cpp:1887
uint8_t G
Definition: TColor.h:51
void unload() const noexcept
For external storage image objects only, this method unloads the image from memory (or does nothing i...
Definition: CImage.cpp:1578
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:893
#define MRPT_DISABLE_FULL_OPTIMIZATION
Definition: CImage.cpp:1923
mrpt::pimpl< Impl > m_impl
Definition: img/CImage.h:1027
bool supports(feature f) noexcept
Returns true if the current CPU (and OS) supports the given CPU feature.
Definition: cpu.h:75
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:1659
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:1861
void image_SSSE3_scale_half_3c8u(const uint8_t *in, uint8_t *out, int w, int h, size_t in_step, size_t out_step)
mrpt::math::CMatrixDouble33 intrinsicParams
Matrix of intrinsic parameters (containing the focal length and principal point coordinates): ...
Definition: TCamera.h:50
#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:818
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:1961
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:220
#define ASSERT_EQUAL_(__A, __B)
Assert comparing two values, reporting their actual values upon failure.
Definition: exceptions.h:137
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 assignMemoryNotOwn(const void *data, const uint64_t nBytesInData)
Initilize the data in the stream from a block of memory which is NEITHER OWNED NOR COPIED by the obje...
void normalize()
Optimize the brightness range of an image without using histogram Only for one channel images...
Definition: CImage.cpp:1230
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:40
void flipVertical()
Flips the image vertically.
Definition: CImage.cpp:1643
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:26
void getAsIplImage(IplImage *dest) const
(DEPRECATED, DO NOT USE - Kept here only to interface opencv 2.4)
Definition: CImage.cpp:2180
#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:1667
void serializeFrom(mrpt::serialization::CArchive &in, uint8_t serial_version) override
Pure virtual method for reading (deserializing) from an abstract archive.
Definition: CImage.cpp:585
TImageSize getSize() const
Return the size of the image.
Definition: img/CImage.h:646
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:51
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:53
void clear()
Resets the image to the state after a default ctor.
Definition: CImage.cpp:1565
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:933
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:1435
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
return_t square(const num_t x)
Inline function for the square of a number.
void setPixel(int x, int y, size_t color) override
Changes the value of the pixel (x,y).
Definition: CImage.cpp:1076
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:1712
void image_SSSE3_bgr_to_gray_8u(const uint8_t *in, uint8_t *out, int w, int h, size_t in_step, size_t out_step)
CImage()
Default constructor: initialize to empty image.
Definition: CImage.cpp:159
void image_SSE2_scale_half_1c8u(const uint8_t *in, uint8_t *out, int w, int h, size_t in_step, size_t out_step)
Virtual base class for "archives": classes abstracting I/O streams.
Definition: CArchive.h:54
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:859
TInterpolationMethod
Interpolation methods for images.
Definition: img/CImage.h:50
bool isOriginTopLeft() const
Returns true (as of MRPT v2.0.0, it&#39;s fixed)
Definition: CImage.cpp:888
const float R
mrpt::vision::TStereoCalibResults out
struct _IplImage IplImage
Definition: img/CImage.h:22
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:1033
Deep copy: the copied object has a duplicate of all data, becoming independent.
Definition: img/CImage.h:78
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
float u8tof(const uint8_t v)
converts a uint8_t [0,255] into a float [0,1]
size_t getRowStride() const
Returns the row stride of the image: this is the number of bytes between two consecutive rows...
Definition: CImage.cpp:839
#define MRPT_HAS_OPENCV
CImage scaleDouble(TInterpolationMethod interp) const
Returns a new image scaled up to double its original size.
Definition: img/CImage.h:329
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:1767
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:1166
constexpr RET pixelDepth2CvDepth(PixelDepth d)
Definition: CImage.cpp:105
pimpl< T > make_impl(Args &&... args)
Definition: pimpl.h:18
void image_SSE2_scale_half_smooth_1c8u(const uint8_t *in, uint8_t *out, int w, int h, size_t in_step, size_t out_step)
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:374
MRPT_TODO("toPointCloud / calibration")
static int interpolationMethod2Cv(TInterpolationMethod i)
Definition: CImage.cpp:90
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:59
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:25
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:1685
std::ostream & operator<<(std::ostream &o, const TColor &c)
Definition: TColor.cpp:80
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:794
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:1036
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:1902
#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:806
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:2097
static bool my_img_to_grayscale(const cv::Mat &src, cv::Mat &dest)
Definition: CImage.cpp:942
A class for storing images as grayscale or RGB bitmaps.
Definition: img/CImage.h:148
void memcpy(void *dest, size_t destSize, const void *src, size_t copyCount) noexcept
An OS and compiler independent version of "memcpy".
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 struct FontData data
Definition: gltext.cpp:144
static const std::string & getImagesPathBase()
By default, ".".
Definition: CImage.cpp:76



Page generated by Doxygen 1.8.14 for MRPT 1.9.9 Git: c7a3bec24 Sun Mar 29 18:33:13 2020 +0200 at dom mar 29 18:50:38 CEST 2020