00001 /* +---------------------------------------------------------------------------+ 00002 | The Mobile Robot Programming Toolkit (MRPT) C++ library | 00003 | | 00004 | http://mrpt.sourceforge.net/ | 00005 | | 00006 | Copyright (C) 2005-2010 University of Malaga | 00007 | | 00008 | This software was written by the Machine Perception and Intelligent | 00009 | Robotics Lab, University of Malaga (Spain). | 00010 | Contact: Jose-Luis Blanco <jlblanco@ctima.uma.es> | 00011 | | 00012 | This file is part of the MRPT project. | 00013 | | 00014 | MRPT is free software: you can redistribute it and/or modify | 00015 | it under the terms of the GNU General Public License as published by | 00016 | the Free Software Foundation, either version 3 of the License, or | 00017 | (at your option) any later version. | 00018 | | 00019 | MRPT is distributed in the hope that it will be useful, | 00020 | but WITHOUT ANY WARRANTY; without even the implied warranty of | 00021 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | 00022 | GNU General Public License for more details. | 00023 | | 00024 | You should have received a copy of the GNU General Public License | 00025 | along with MRPT. If not, see <http://www.gnu.org/licenses/>. | 00026 | | 00027 +---------------------------------------------------------------------------+ */ 00028 #ifndef CImage_H 00029 #define CImage_H 00030 00031 #include <mrpt/utils/utils_defs.h> 00032 #include <mrpt/utils/CSerializable.h> 00033 #include <mrpt/math/CMatrix.h> 00034 #include <mrpt/utils/CCanvas.h> 00035 #include <mrpt/utils/TCamera.h> 00036 #include <mrpt/system/os.h> 00037 #include <mrpt/utils/exceptions.h> 00038 00039 namespace mrpt 00040 { 00041 namespace utils 00042 { 00043 /** Interpolation methods for images. 00044 * Used for OpenCV related operations with images, but also with MRPT native classes. 00045 * \sa mrpt::utils::CMappedImage, CImage::scaleImage 00046 */ 00047 enum TInterpolationMethod 00048 { 00049 IMG_INTERP_NN = 0, 00050 IMG_INTERP_LINEAR=1, 00051 IMG_INTERP_CUBIC=2, 00052 IMG_INTERP_AREA=3 00053 }; 00054 00055 /** For use in mrpt::utils::CImage */ 00056 typedef int TImageChannels; 00057 #define CH_GRAY 1 00058 #define CH_RGB 3 00059 00060 /** For usage in one of the CImage constructors */ 00061 enum TConstructorFlags_CImage 00062 { 00063 UNINITIALIZED_IMAGE = 0, 00064 FAST_REF_OR_CONVERT_TO_GRAY = 1 00065 }; 00066 00067 // This must be added to any CSerializable derived class: 00068 DEFINE_SERIALIZABLE_PRE_CUSTOM_BASE( CImage, mrpt::utils::CSerializable ) 00069 00070 /** A class for storing images as grayscale or RGB bitmaps. 00071 * File I/O is supported in two different ways: 00072 * - Binary dump using the CSerializable interface(<< and >> operators), just as most objects 00073 * in the MRPT library. This format is not compatible with any standarized image format. 00074 * - Saving/loading from files of different formats (bmp,jpg,png,...) using the methods CImage::loadFromFile and CImage::saveToFile. 00075 * 00076 * How to create color/grayscale images: 00077 * \code 00078 * CImage img1(width, height, CH_GRAY ); // Grayscale image (8U1C) 00079 * CImage img2(width, height, CH_RGB ); // RGB image (8U3C) 00080 * \endcode 00081 * 00082 * Additional notes: 00083 * - The OpenCV "IplImage" format is used internally for compatibility with all OpenCV functions. See CImage::getAsIplImage and CImage::getAs<>(). Example: 00084 * \code 00085 * CImage img; 00086 * ... 00087 * // Call to OpenCV function expecting an "IplImage *" or a "void* arr": 00088 * cvFunction( img.getAs<IplImage>(), ... ); 00089 * \endcode 00090 * - Only the unsigned 8-bit storage format for pixels (on each channel) is supported. 00091 * - An external storage mode can be enabled by calling CImage::setExternalStorage, useful for storing large collections of image objects in memory while loading the image data itself only for the relevant images at any time. 00092 * - To move images from one object to the another, use CImage::copyFastFrom rather than the copy operator =. 00093 * - If you are interested in a smart pointer to an image, use: 00094 * \code 00095 * CImagePtr myImgPtr = CImagePtr( new CImage(...) ); 00096 * \endcode 00097 * - To set a CImage from an OpenCV "IPLImage*", use the methods: 00098 * - CImage::loadFromIplImage 00099 * - CImage::setFromIplImage 00100 * - CImage::CImage(void *IPL) 00101 * 00102 * For many computer vision functions that use CImage as its image data type, see mrpt::vision. 00103 * 00104 * \note This class acts as a wrapper class to a small subset of OpenCV functions. IplImage is the internal storage structure. 00105 * 00106 * \sa mrpt::vision, mrpt::vision::CFeatureExtractor, CSerializable, CCanvas 00107 */ 00108 class BASE_IMPEXP CImage : public mrpt::utils::CSerializable, public CCanvas 00109 { 00110 friend class CImageFloat; 00111 DEFINE_SERIALIZABLE( CImage ) 00112 public: 00113 00114 // ================================================================ 00115 /** @name Constructors & destructor 00116 @{ */ 00117 00118 /** Default constructor: initialize an 1x1 RGB image. */ 00119 CImage(); 00120 00121 /** Constructor for a given image size and type. 00122 * Examples: 00123 * \code 00124 * CImage img1(width, height, CH_GRAY ); // Grayscale image (8U1C) 00125 * CImage img2(width, height, CH_RGB ); // RGB image (8U3C) 00126 * \endcode 00127 */ 00128 CImage( unsigned int width, 00129 unsigned int height, 00130 TImageChannels nChannels = CH_RGB, 00131 bool originTopLeft = true 00132 ); 00133 00134 /** Copy constructor, makes a full copy of the original image contents */ 00135 CImage( const CImage &o ); 00136 00137 /** Copy constructor */ 00138 CImage( const CImageFloat &o ); 00139 00140 /** Fast constructor that leaves the image uninitialized (the internal IplImage pointer set to NULL). 00141 * Use only when you know the image will be soon be assigned another image. 00142 * Example of usage: 00143 * \code 00144 * CImage myImg(UNINITIALIZED_IMAGE); 00145 * \endcode 00146 */ 00147 inline CImage(TConstructorFlags_CImage constructor_flag) : img(NULL),m_imgIsReadOnly(false), m_imgIsExternalStorage(false) 00148 { } 00149 00150 /** Fast constructor of a grayscale version of another image, making a <b>reference</b> to the original image if it already was in grayscale, or otherwise creating a new grayscale image and converting the original image into it. 00151 * It's <b>very important to keep in mind</b> that the original image can't be destroyed before the new object being created with this constructor. 00152 * Example of usage: 00153 * \code 00154 * void my_func(const CImage &in_img) { 00155 * const CImage gray_img(in_img, FAST_REF_OR_CONVERT_TO_GRAY); 00156 * // We can now operate on "gray_img" being sure it's in grayscale. 00157 * } 00158 * \endcode 00159 */ 00160 inline CImage(const CImage& other_img, TConstructorFlags_CImage constructor_flag) : img(NULL),m_imgIsReadOnly(false), m_imgIsExternalStorage(false) 00161 { 00162 if( other_img.isColor() ) other_img.grayscale(*this); 00163 else this->setFromImageReadOnly(other_img); 00164 } 00165 00166 /** Constructor from an IPLImage*, making a copy of the image. 00167 * \sa loadFromIplImage, setFromIplImage 00168 */ 00169 CImage( void *iplImage ); 00170 00171 /** Destructor: */ 00172 virtual ~CImage( ); 00173 00174 /** @} */ 00175 // ================================================================ 00176 00177 00178 /** By default, when storing images through the CSerializable interface, grayscale images will be ZIP compressed if they are larger than 16Kb: this flag can be turn on to disable ZIP compression and gain speed versus occupied space. 00179 * The default value of this variable is "false". 00180 */ 00181 static bool DISABLE_ZIP_COMPRESSION; 00182 00183 00184 // ================================================================ 00185 /** @name Manipulate the image contents or size, various computer-vision methods (image filters, undistortion, etc.) 00186 @{ */ 00187 00188 /** Changes the size of the image, erasing previous contents (does NOT scale its current content, for that, see scaleImage). 00189 * - nChannels: Can be 3 for RGB images or 1 for grayscale images. 00190 * - originTopLeft: Is true if the top-left corner is (0,0). In other case, the reference is the bottom-left corner. 00191 * \sa scaleImage 00192 */ 00193 inline void resize( 00194 unsigned int width, 00195 unsigned int height, 00196 TImageChannels nChannels, 00197 bool originTopLeft ) 00198 { 00199 ASSERT_(img!=NULL); 00200 changeSize(width,height,nChannels,originTopLeft); 00201 } 00202 00203 /** Scales this image to a new size, interpolating as needed. 00204 * \sa resize, rotateImage 00205 */ 00206 void scaleImage( unsigned int width, unsigned int height, TInterpolationMethod interp = IMG_INTERP_CUBIC ); 00207 00208 /** Scales this image to a new size, interpolating as needed, saving the new image in a different output object. 00209 * \sa resize, rotateImage 00210 */ 00211 void scaleImage( CImage &out_img, unsigned int width, unsigned int height, TInterpolationMethod interp = IMG_INTERP_CUBIC ) const; 00212 00213 /** Rotates the image by the given angle around the given center point, with an optional scale factor. 00214 * \sa resize, scaleImage 00215 */ 00216 void rotateImage( double angle_radians, unsigned int center_x, unsigned int center_y, double scale = 1.0 ); 00217 00218 /** Changes the value of the pixel (x,y). 00219 * Pixel coordinates starts at the left-top corner of the image, and start in (0,0). 00220 * The meaning of the parameter "color" depends on the implementation: it will usually 00221 * be a 24bit RGB value (0x00RRGGBB), but it can also be just a 8bit gray level. 00222 * This method must support (x,y) values OUT of the actual image size without neither 00223 * raising exceptions, nor leading to memory access errors. 00224 */ 00225 void setPixel(int x, int y, size_t color); 00226 00227 /** Changes the property of the image stating if the top-left corner (vs. bottom-left) is the coordinate reference. 00228 */ 00229 void setOriginTopLeft(bool val); 00230 00231 /** Draws a circle of a given radius. 00232 * \param x The center - x coordinate in pixels. 00233 * \param y The center - y coordinate in pixels. 00234 * \param radius The radius - in pixels. 00235 * \param color The color of the circle. 00236 * \param width The desired width of the line 00237 */ 00238 void drawCircle( 00239 int x, 00240 int y, 00241 int radius, 00242 const mrpt::utils::TColor &color = mrpt::utils::TColor(255,255,255), 00243 unsigned int width = 1); 00244 00245 void equalizeHistInPlace(); //!< Equalize the image histogram, replacing the original image. 00246 void equalizeHist( CImage &outImg ) const; //!< Equalize the image histogram, saving the new image in the given output object. 00247 00248 /** Returns a new image scaled down to half its original size. 00249 * \exception std::exception On odd size 00250 * \sa scaleDouble, scaleImage 00251 */ 00252 CImage scaleHalf()const; 00253 00254 /** Returns a new image scaled up to double its original size. 00255 * \exception std::exception On odd size 00256 * \sa scaleHalf, scaleImage 00257 */ 00258 CImage scaleDouble()const; 00259 00260 00261 00262 00263 /** Update a part of this image with the "patch" given as argument. 00264 * The "patch" will be "pasted" at the (col,row) coordinates of this image. 00265 * \exception std::exception if patch pasted on the pixel (_row, _column) jut out 00266 * of the image. 00267 * \sa extract_patch 00268 */ 00269 void update_patch(const CImage &patch, 00270 const unsigned int col, 00271 const unsigned int row); 00272 00273 /** Extract a patch from this image, saveing it into "patch" (its previous contents will be overwritten). 00274 * The patch to extract starts at (col,row) and has the given dimensions. 00275 * \sa update_patch 00276 */ 00277 void extract_patch( 00278 CImage &patch, 00279 const unsigned int col=0, 00280 const unsigned int row=0, 00281 const unsigned int width=1, 00282 const unsigned int height=1 ) const; 00283 00284 /** Computes the correlation coefficient (returned as val), between two images 00285 * This function use grayscale images only 00286 * img1, img2 must be same size 00287 * (by AJOGD @ DEC-2006) 00288 */ 00289 float correlate( const CImage &img2int, int width_init=0, int height_init=0 )const; 00290 00291 /** Computes the correlation between this image and another one, encapsulating the openCV function cvMatchTemplate 00292 * 00293 * \param patch_img The "patch" image, which must be equal, or smaller than "this" image. This function supports gray-scale (1 channel only) images. 00294 * \param u_search_ini The "x" coordinate of the search window. 00295 * \param v_search_ini The "y" coordinate of the search window. 00296 * \param u_search_size The width of the search window. 00297 * \param v_search_size The height of the search window. 00298 * \param u_max The u coordinate where find the maximun cross correlation value. 00299 * \param v_max The v coordinate where find the maximun cross correlation value 00300 * \param max_val The maximun value of cross correlation which we can find 00301 * \param out_corr_image If a !=NULL pointer is provided, it will be saved here the correlation image. The size of the output image is (this_width-patch_width+1, this_height-patch_height+1 ) 00302 * Note: By default, the search area is the whole (this) image. 00303 * (by AJOGD @ MAR-2007) 00304 */ 00305 void cross_correlation( 00306 const CImage &patch_img, 00307 size_t &u_max, 00308 size_t &v_max, 00309 double &max_val, 00310 int u_search_ini=-1, 00311 int v_search_ini=-1, 00312 int u_search_size=-1, 00313 int v_search_size=-1, 00314 CImage *out_corr_image = NULL 00315 )const; 00316 00317 /** Computes the correlation matrix between this image and another one. 00318 * This implementation uses the 2D FFT for achieving reduced computation time. 00319 * \param in_img The "patch" image, which must be equal, or smaller than "this" image. This function supports gray-scale (1 channel only) images. 00320 * \param u_search_ini The "x" coordinate of the search window. 00321 * \param v_search_ini The "y" coordinate of the search window. 00322 * \param u_search_size The width of the search window. 00323 * \param v_search_size The height of the search window. 00324 * \param out_corr The output for the correlation matrix, which will be "u_search_size" x "v_search_size" 00325 * \param biasThisImg This optional parameter is a fixed "bias" value to be substracted to the pixels of "this" image before performing correlation. 00326 * \param biasInImg This optional parameter is a fixed "bias" value to be substracted to the pixels of "in_img" image before performing correlation. 00327 * Note: By default, the search area is the whole (this) image. 00328 * (by JLBC @ JAN-2006) 00329 * \sa cross_correlation 00330 */ 00331 void cross_correlation_FFT( 00332 const CImage &in_img, 00333 math::CMatrixFloat &out_corr, 00334 int u_search_ini=-1, 00335 int v_search_ini=-1, 00336 int u_search_size=-1, 00337 int v_search_size=-1, 00338 float biasThisImg = 0, 00339 float biasInImg = 0 00340 ) const; 00341 00342 00343 /** Optimize de brightness range of a image without using histogram 00344 * Only for one channel images. 00345 */ 00346 void normalize(); 00347 00348 /** Flips vertically the image. 00349 * \sa swapRB 00350 */ 00351 void flipVertical(bool also_swapRB = false); 00352 00353 /** Swaps red and blue channels. 00354 * \sa flipVertical 00355 */ 00356 void swapRB(); 00357 00358 /** Rectify (un-distort) the image according to some camera parameters, and returns an output un-distorted image. 00359 * \param out_img The output rectified image 00360 * \param cameraParams The input camera params (containing the intrinsic and distortion parameters of the camera) 00361 */ 00362 void rectifyImage( CImage &out_img, const mrpt::utils::TCamera &cameraParams) const; 00363 00364 /** Rectify (un-distort) the image according to a certain camera matrix and vector of distortion coefficients and returns an output rectified image 00365 * \param out_img The output rectified image 00366 * \param cameraMatrix The input camera matrix (containing the intrinsic parameters of the camera): [fx 0 cx; 0 fy cy; 0 0 1]: (fx,fy) focal length and (cx,cy) principal point coordinates 00367 * \param distCoeff The (input) distortion coefficients: [k1, k2, p1, p2]: k1 and k2 (radial) and p1 and p2 (tangential) 00368 */ 00369 inline void rectifyImage( CImage &out_img, const math::CMatrixDouble33 &cameraMatrix, const vector_double &distCoeff ) const 00370 { 00371 mrpt::utils::TCamera cam; 00372 cam.intrinsicParams = cameraMatrix; 00373 cam.setDistortionParamsVector(distCoeff); 00374 rectifyImage(out_img,cam); 00375 } 00376 00377 /** Rectify (un-distort) the image according to a certain camera matrix and vector of distortion coefficients, replacing "this" with the rectified image 00378 * \param cameraParams The input camera params (containing the intrinsic and distortion parameters of the camera) 00379 */ 00380 void rectifyImageInPlace(const mrpt::utils::TCamera &cameraParams ); 00381 00382 /** Rectify (un-distort) the image according to a certain camera matrix and vector of distortion coefficients, replacing "this" with the rectified image 00383 * \param cameraMatrix The input camera matrix (containing the intrinsic parameters of the camera): [fx 0 cx; 0 fy cy; 0 0 1]: (fx,fy) focal length and (cx,cy) principal point coordinates 00384 * \param distCoeff The (input) distortion coefficients: [k1, k2, p1, p2]: k1 and k2 (radial) and p1 and p2 (tangential) 00385 */ 00386 inline void rectifyImageInPlace( const math::CMatrixDouble33 &cameraMatrix, const vector_double &distCoeff ) 00387 { 00388 mrpt::utils::TCamera cam; 00389 cam.intrinsicParams = cameraMatrix; 00390 cam.setDistortionParamsVector(distCoeff); 00391 rectifyImageInPlace(cam); 00392 } 00393 00394 /** Filter the image with a Median filter with a window size WxW, returning the filtered image in out_img */ 00395 void filterMedian( CImage &out_img, int W=3 ) const; 00396 00397 /** Filter the image with a Median filter with a window size WxH, replacing "this" image by the filtered one. */ 00398 void filterMedianInPlace( int W=3 ); 00399 00400 /** Filter the image with a Gaussian filter with a window size WxH, returning the filtered image in out_img */ 00401 void filterGaussianInPlace( int W = 3, int H = 3 ); 00402 00403 /** Filter the image with a Gaussian filter with a window size WxH, replacing "this" image by the filtered one. */ 00404 void filterGaussian( CImage &out_img, int W = 3, int H = 3) const; 00405 00406 /** Draw onto this image the detected corners of a chessboard. The length of cornerCoords must be the product of the two check_sizes. 00407 * 00408 * \param cornerCoords [IN] The pixel coordinates of all the corners. 00409 * \param check_size_x [IN] The number of squares, in the X direction 00410 * \param check_size_y [IN] The number of squares, in the Y direction 00411 * 00412 * \return false if the length of cornerCoords is inconsistent (nothing is drawn then). 00413 * 00414 * \sa mrpt::vision::findChessboardCorners 00415 */ 00416 bool drawChessboardCorners( 00417 std::vector<TPixelCoordf> &cornerCoords, 00418 unsigned int check_size_x, 00419 unsigned int check_size_y ); 00420 00421 /** Joins two images side-by-side horizontally. Both images must have the same number of rows and be of the same type (i.e. depth and color mode) 00422 * 00423 * \param im1 [IN] The first image. 00424 * \param im2 [IN] The other image. 00425 */ 00426 void joinImagesHorz( 00427 const CImage &im1, 00428 const CImage &im2 ); 00429 00430 /** Compute the KLT response at a given pixel (x,y) - Only for grayscale images (for efficiency it avoids converting to grayscale internally). 00431 */ 00432 float KLT_response( 00433 const unsigned int x, 00434 const unsigned int y, 00435 const unsigned int half_window_size ) const; 00436 00437 /** @} */ 00438 // ================================================================ 00439 00440 00441 00442 // ================================================================ 00443 /** @name Copy, move & swap operations 00444 @{ */ 00445 00446 /** Copy operator 00447 * \sa copyFastFrom 00448 */ 00449 CImage& operator = (const CImage& o); 00450 00451 /** Copy operator from a gray-scale, float image: 00452 * \sa copyFastFrom 00453 */ 00454 CImage& operator = (const CImageFloat& o); 00455 00456 /** Moves an image from another object, erasing the origin image in the process (this is much faster than copying) 00457 * \sa operator = 00458 */ 00459 void copyFastFrom( CImage &o ); 00460 00461 void swap(CImage &o); //!< Very efficient swap of two images (just swap the internal pointers) 00462 00463 /** @} */ 00464 // ================================================================ 00465 00466 00467 // ================================================================ 00468 /** @name Access to image contents (IplImage structure and raw pixels). 00469 @{ */ 00470 00471 /** Returns a pointer to an T* containing the image - the idea is to call like "img.getAs<IplImage>()" so we can avoid here including OpenCV's headers. \sa getAsIplImage */ 00472 template <typename T> inline const T* getAs() const { 00473 makeSureImageIsLoaded(); 00474 return reinterpret_cast<const T*>(img); 00475 } 00476 /** Returns a pointer to an T* containing the image - the idea is to call like "img.getAs<IplImage>()" so we can avoid here including OpenCV's headers. \sa getAsIplImage */ 00477 template <typename T> inline T* getAs(){ 00478 makeSureImageIsLoaded(); 00479 return reinterpret_cast<T*>(img); 00480 } 00481 00482 /** Returns a pointer to an OpenCV's IplImage struct containing the image, which is linked to this class: free neigther that pointer nor this class until they are not required anymore, since this class is in charge of freeing the memory buffers inside of the returned image. \sa getAs */ 00483 inline void* getAsIplImage() const { 00484 makeSureImageIsLoaded(); 00485 return img; 00486 } 00487 00488 /** Access to pixels without checking boundaries - Use normally the () operator better, which checks the coordinates. 00489 \sa CImage::operator() 00490 */ 00491 unsigned char* get_unsafe( 00492 unsigned int col, 00493 unsigned int row, 00494 unsigned int channel=0) const; 00495 00496 /** Returns the contents of a given pixel at the desired channel, in float format: [0,255]->[0,1] 00497 * The coordinate origin is pixel(0,0)=top-left corner of the image. 00498 * \exception std::exception On pixel coordinates out of bounds 00499 * \sa operator() 00500 */ 00501 float getAsFloat(unsigned int col, unsigned int row, unsigned int channel) const; 00502 00503 /** Returns the contents of a given pixel (for gray-scale images, in color images the gray scale equivalent is computed for the pixel), in float format: [0,255]->[0,1] 00504 * The coordinate origin is pixel(0,0)=top-left corner of the image. 00505 * \exception std::exception On pixel coordinates out of bounds 00506 * \sa operator() 00507 */ 00508 float getAsFloat(unsigned int col, unsigned int row) const; 00509 00510 /** Returns a pointer to a given pixel information. 00511 * The coordinate origin is pixel(0,0)=top-left corner of the image. 00512 * \exception std::exception On pixel coordinates out of bounds 00513 */ 00514 unsigned char* operator()(unsigned int col, unsigned int row, unsigned int channel = 0) const; 00515 00516 /** @} */ 00517 // ================================================================ 00518 00519 00520 00521 // ================================================================ 00522 /** @name Query image properties 00523 @{ */ 00524 00525 /** Returns the width of the image in pixels 00526 * \sa getSize 00527 */ 00528 size_t getWidth() const; 00529 00530 /** Returns the height of the image in pixels 00531 * \sa getSize 00532 */ 00533 size_t getHeight() const; 00534 00535 /** Return the size of the image 00536 * \sa getWidth, getHeight 00537 */ 00538 void getSize(TImageSize &s) const; 00539 00540 /** Return the size of the image 00541 * \sa getWidth, getHeight 00542 */ 00543 inline TImageSize getSize() const { 00544 TImageSize ret; 00545 getSize(ret); 00546 return ret; 00547 } 00548 00549 /** Return the maximum pixel value of the image, as a float value in the range [0,1] 00550 * \sa getAsFloat 00551 */ 00552 float getMaxAsFloat() const; 00553 00554 /** Returns true if the image is RGB, false if it is grayscale */ 00555 bool isColor() const; 00556 00557 /** Returns true if the coordinates origin is top-left, or false if it is bottom-left */ 00558 bool isOriginTopLeft() const; 00559 00560 /** Returns a string of the form "BGR","RGB" or "GRAY" indicating the channels ordering. */ 00561 const char * getChannelsOrder()const; 00562 00563 /** Returns the number of channels, typically 1 (GRAY) or 3 (RGB) 00564 * \sa isColor 00565 */ 00566 TImageChannels getChannelCount() const; 00567 00568 /** Returns the image as a matrix with pixel grayscale values in the range [0,1] 00569 * \param doResize If set to true (default), the output matrix will be always the size of the image at output. If set to false, the matrix will be enlarged to the size of the image, but it will not be cropped if it has room enough (useful for FFT2D,...) 00570 * \param x_min The starting "x" coordinate to extract (default=0=the first column) 00571 * \param y_min The starting "y" coordinate to extract (default=0=the first row) 00572 * \param x_max The final "x" coordinate (inclusive) to extract (default=-1=the last column) 00573 * \param y_max The final "y" coordinate (inclusive) to extract (default=-1=the last row) 00574 * \sa setFromMatrix 00575 */ 00576 void getAsMatrix( 00577 mrpt::math::CMatrixFloat &outMatrix, 00578 bool doResize = true, 00579 int x_min = 0, 00580 int y_min = 0, 00581 int x_max = -1, 00582 int y_max = -1 00583 ) const; 00584 00585 /** Returns the image as a matrix, where the image is "tiled" (repeated) the required number of times to fill the entire size of the matrix on input. 00586 */ 00587 void getAsMatrixTiled( math::CMatrix &outMatrix ) const; 00588 00589 /** @} */ 00590 // ================================================================ 00591 00592 00593 // ================================================================ 00594 /** @name External storage-mode methods 00595 @{ */ 00596 00597 /** By using this method the image is marked as referenced to an external file, which will be loaded only under demand. 00598 * A CImage with external storage does not consume memory until some method trying to access the image is invoked (e.g. getWidth(), isColor(),...) 00599 * At any moment, the image can be unloaded from memory again by invoking unload. 00600 * An image becomes of type "external storage" only through calling setExternalStorage. This property remains after serializing the object. 00601 * File names can be absolute, or relative to the CImage::IMAGES_PATH_BASE directory. Filenames staring with "X:\" or "/" are considered absolute paths. 00602 * By calling this method the current contents of the image are NOT saved to that file, because this method can be also called 00603 * to let the object know where to load the image in case its contents are required. Thus, for saving images in this format (not when loading) 00604 * the proper order of commands should be: 00605 * \code 00606 * img.saveToFile( fileName ); 00607 * img.setExternalStorage( fileName ); 00608 * \endcode 00609 * 00610 * \note Modifications to the memory copy of the image are not automatically saved to disk. 00611 * \sa unload, isExternallyStored 00612 */ 00613 void setExternalStorage( const std::string &fileName ) MRPT_NO_THROWS; 00614 00615 static std::string IMAGES_PATH_BASE; //!< By default, "." \sa setExternalStorage 00616 00617 /** See setExternalStorage(). */ 00618 bool isExternallyStored() const MRPT_NO_THROWS { return m_imgIsExternalStorage; } 00619 00620 inline std::string getExternalStorageFile() const MRPT_NO_THROWS //!< Only if isExternallyStored() returns true. \sa getExternalStorageFileAbsolutePath 00621 { 00622 return m_externalFile; 00623 } 00624 00625 /** Only if isExternallyStored() returns true. \sa getExternalStorageFile */ 00626 void getExternalStorageFileAbsolutePath(std::string &out_path) const; 00627 00628 /** Only if isExternallyStored() returns true. \sa getExternalStorageFile */ 00629 inline std::string getExternalStorageFileAbsolutePath() const { 00630 std::string tmp; 00631 getExternalStorageFileAbsolutePath(tmp); 00632 return tmp; 00633 } 00634 00635 /** For external storage image objects only, this method unloads the image from memory (or does nothing if already unloaded). 00636 * It does not need to be called explicitly, unless the user wants to save memory for images that will not be used often. 00637 * If called for an image without the flag "external storage", it is simply ignored. 00638 * \sa setExternalStorage 00639 */ 00640 void unload() MRPT_NO_THROWS; 00641 00642 /** @} */ 00643 // ================================================================ 00644 00645 00646 // ================================================================ 00647 /** @name Set, load & save methods 00648 @{ */ 00649 00650 /** Reads the image from raw pixels buffer in memory. 00651 */ 00652 void loadFromMemoryBuffer( unsigned int width, unsigned int height, bool color, unsigned char *rawpixels, bool swapRedBlue = false ); 00653 00654 /** Reads a color image from three raw pixels buffers in memory. 00655 * bytesPerRow is the number of bytes per row per channel, i.e. the row increment. 00656 */ 00657 void loadFromMemoryBuffer( unsigned int width, unsigned int height, unsigned int bytesPerRow, unsigned char *red, unsigned char *green, unsigned char *blue ); 00658 00659 /** Reads the image from a OpenCV IplImage object (making a COPY). 00660 */ 00661 void loadFromIplImage( void* iplImage ); 00662 00663 /** Reads the image from a OpenCV IplImage object (WITHOUT making a copy). 00664 * This object will own the memory of the passed object and free the IplImage upon destruction, 00665 * so the caller CAN'T free the original object. 00666 * This method provides a fast method to grab images from a camera without making a copy of every frame. 00667 */ 00668 void setFromIplImage( void* iplImage ); 00669 00670 /** Reads the image from a OpenCV IplImage object (WITHOUT making a copy) and from now on the image cannot be modified, just read. 00671 * When assigning an IPLImage to this object with this method, the IPLImage will NOT be released/freed at this object destructor. 00672 * This method provides a fast method to grab images from a camera without making a copy of every frame. 00673 * \sa setFromImageReadOnly 00674 */ 00675 void setFromIplImageReadOnly( void* iplImage ); 00676 00677 /** Sets the internal IplImage pointer to that of another given image, WITHOUT making a copy, and from now on the image cannot be modified in this object (it will be neither freed, so the memory responsibility will still be of the original image object). 00678 * When assigning an IPLImage to this object with this method, the IPLImage will NOT be released/freed at this object destructor. 00679 * \sa setFromIplImageReadOnly 00680 */ 00681 inline void setFromImageReadOnly( const CImage &other_img ) { setFromIplImageReadOnly(other_img.getAsIplImage() ); } 00682 00683 /** Set the image from a matrix, interpreted as grayscale intensity values, in the range [0,1] (normalized=true) or [0,255] (normalized=false) 00684 * \sa getAsMatrix 00685 */ 00686 void setFromMatrix(const mrpt::math::CMatrixFloat &m, bool matrix_is_normalized=true); 00687 00688 /** Set the image from a matrix, interpreted as grayscale intensity values, in the range [0,1] (normalized=true) or [0,255] (normalized=false) 00689 * \sa getAsMatrix 00690 */ 00691 void setFromMatrix(const mrpt::math::CMatrixDouble &m, bool matrix_is_normalized=true); 00692 00693 00694 /** Reads the image from a binary stream containing a binary jpeg file. 00695 * \exception std::exception On pixel coordinates out of bounds 00696 */ 00697 void loadFromStreamAsJPEG( CStream &in ); 00698 00699 /** Load image from a file, whose format is determined from the extension (internally uses OpenCV). 00700 * \param fileName The file to read from. 00701 * \param isColor Specifies colorness of the loaded image: 00702 * - if >0, the loaded image is forced to be color 3-channel image; 00703 * - if 0, the loaded image is forced to be grayscale; 00704 * - if <0, the loaded image will be loaded as is (with number of channels depends on the file). 00705 * The supported formats are: 00706 * 00707 * - Windows bitmaps - BMP, DIB; 00708 * - JPEG files - JPEG, JPG, JPE; 00709 * - Portable Network Graphics - PNG; 00710 * - Portable image format - PBM, PGM, PPM; 00711 * - Sun rasters - SR, RAS; 00712 * - TIFF files - TIFF, TIF. 00713 * 00714 * \return False on any error 00715 * \sa saveToFile, setExternalStorage 00716 */ 00717 bool loadFromFile( const std::string& fileName, int isColor = -1 ); 00718 00719 /** Save the image to a file, whose format is determined from the extension (internally uses OpenCV). 00720 * \param fileName The file to write to. 00721 * 00722 * The supported formats are: 00723 * 00724 * - Windows bitmaps - BMP, DIB; 00725 * - JPEG files - JPEG, JPG, JPE; 00726 * - Portable Network Graphics - PNG; 00727 * - Portable image format - PBM, PGM, PPM; 00728 * - Sun rasters - SR, RAS; 00729 * - TIFF files - TIFF, TIF. 00730 * 00731 * \param jpeg_quality Only for JPEG files, the quality of the compression in the range [0-100]. Larger is better quality but slower. 00732 * \note jpeg_quality is only effective if MRPT is compiled against OpenCV 1.1.0 or newer. 00733 * \return False on any error 00734 * \sa loadFromFile 00735 */ 00736 bool saveToFile( const std::string& fileName, int jpeg_quality = 95 ) const; 00737 00738 /** Save image to binary stream as a JPEG (.jpg) compresed format. 00739 * \exception std::exception On number of rows or cols equal to zero, or other errors. 00740 * \sa saveToJPEG 00741 */ 00742 void saveToStreamAsJPEG( CStream &out )const; 00743 00744 /** @} */ 00745 // ================================================================ 00746 00747 00748 // ================================================================ 00749 /** @name Color/Grayscale conversion 00750 @{ */ 00751 00752 /** Returns a grayscale version of the image, or itself if it is already a grayscale image. 00753 */ 00754 CImage grayscale() const; 00755 00756 /** Returns a grayscale version of the image, or itself if it is already a grayscale image. 00757 * \sa colorImage 00758 */ 00759 void grayscale( CImage &ret ) const; 00760 00761 /** Returns a RGB version of the grayscale image, or itself if it is already a RGB image. 00762 * \sa grayscale 00763 */ 00764 void colorImage( CImage &ret ) const; 00765 00766 /** Replaces this grayscale image with a RGB version of it. 00767 * \sa grayscaleInPlace 00768 */ 00769 void colorImageInPlace(); 00770 00771 00772 /** Replaces the image with a grayscale version of it. 00773 * \sa colorImageInPlace 00774 */ 00775 void grayscaleInPlace(); 00776 00777 /** @} */ 00778 // ================================================================ 00779 00780 00781 protected: 00782 /** @name Data members 00783 @{ */ 00784 00785 void *img; //!< The internal IplImage pointer to the actual image content. 00786 00787 /** Set to true only when using setFromIplImageReadOnly. 00788 * \sa setFromIplImageReadOnly */ 00789 bool m_imgIsReadOnly; 00790 /** Set to true only when using setExternalStorage. 00791 * \sa setExternalStorage 00792 */ 00793 mutable bool m_imgIsExternalStorage; 00794 mutable std::string m_externalFile; //!< The file name of a external storage image. 00795 00796 /** @} */ 00797 00798 /** Resize the buffers in "img" to accomodate a new image size and/or format. 00799 */ 00800 void changeSize( 00801 unsigned int width, 00802 unsigned int height, 00803 TImageChannels nChannels, 00804 bool originTopLeft ); 00805 00806 /** Release the internal IPL image, if not NULL or read-only. */ 00807 void releaseIpl(bool thisIsExternalImgUnload = false) MRPT_NO_THROWS; 00808 00809 /** Checks if the image is of type "external storage", and if so and not loaded yet, load it. */ 00810 void makeSureImageIsLoaded() const throw (std::exception,utils::CExceptionExternalImageNotFound ); 00811 00812 }; // End of class 00813 00814 typedef CImage CMRPTImage; //!< Deprecated name. 00815 00816 00817 } // end of namespace utils 00818 00819 } // end of namespace mrpt 00820 00821 #endif
| Page generated by Doxygen 1.7.1 for MRPT 0.9.1 SVN:exported at Fri Aug 6 10:31:35 UTC 2010 |
