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



Page generated by Doxygen 1.8.14 for MRPT 1.9.9 Git: c26d46ba6 Thu Jul 18 13:03:42 2019 +0200 at jue jul 18 13:10:17 CEST 2019