Basic Image AlgorithmS Library  2.8.0
 All Classes Namespaces Functions Variables Typedefs Enumerations Enumerator Friends Groups Pages
ImageIO.hh
1 /*
2 This file is part of the BIAS library (Basic ImageAlgorithmS).
3 
4 Copyright (C) 2003-2009 (see file CONTACT for details)
5 Multimediale Systeme der Informationsverarbeitung
6 Institut fuer Informatik
7 Christian-Albrechts-Universitaet Kiel
8 
9 
10 BIAS is free software; you can redistribute it and/or modify
11 it under the terms of the GNU Lesser General Public License as published by
12 the Free Software Foundation; either version 2.1 of the License, or
13 (at your option) any later version.
14 
15 BIAS is distributed in the hope that it will be useful,
16 but WITHOUT ANY WARRANTY; without even the implied warranty of
17 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 GNU Lesser General Public License for more details.
19 
20 You should have received a copy of the GNU Lesser General Public License
21 along with BIAS; if not, write to the Free Software
22 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
23 */
24 
25 
26 #ifndef __BIAS_IMAGEIO_H__
27 #define __BIAS_IMAGEIO_H__
28 
29 #include "bias_config.h"
30 
31 
32 #include <string>
33 #include "Image.hh"
34 #include "MetaData.hh"
35 
36 #define MIP_IDENTIFIER "MIP"
37 #define MIP_IDENTIFIER_LENGTH 3
38 
39 #define UNKNOWN_META_DATA -5
40 
41 // default quality for saving e.g. jpg images from 0..100
42 #define BIAS_DEFAULT_IMAGE_QUALITY 80
43 #define BIAS_DEFAULT_SYNC false
44 #define BIAS_DEFAULT_FORCENEWID true
45 
46 
47 // return code if no error occured
48 #define BIAS_IO_SUCCESS 0
49 
50 #ifdef BIAS_HAVE_OPENEXR
51 # ifdef WIN32
52 # pragma warning( push, 1)
53 # define PLATFORM_WINDOWS
54 # endif // WIN32
55 # include <ImfPixelType.h>
56 # ifdef WIN32
57 # pragma warning( pop)
58 # endif // WIN32
59 #endif
60 
61 
62 namespace BIAS {
63  /** @class ImageIO
64  @ingroup g_image_io
65  @brief Routines for loading and writing all kinds of image formats.
66  @note Use Load/Save and Import/ExportImage for foreign+internal file formats
67  For proprietary mip format use extension mip and Load/Save.
68  As all functions are static call them like ImageIO::Load(). */
69  class BIASImageBase_EXPORT ImageIO {
70  public:
71  /** @enum TFileFormat
72  @brief format specifier when writing an image to a file
73  Do *NOT* change order or associated enum value
74  because it may confuse IO rotines for loading old images.
75  */
76  enum TFileFormat {
77  FF_auto=4242 /* automatic format detection by filename*/
78  ,FF_unknown=9999 /* could not be detected by extension */
79  ,FF_mip=0
80  ,FF_ppm=1
81  ,FF_pgm=2
82  ,FF_jpg=3
83  ,FF_tif=4
84  ,FF_png=5
85  ,FF_viff=6
86  ,FF_exr=7
87  ,FF_dds=8
88  ,FF_raw4096=9
89  ,FF_bmp=10
90  ,FF_pbm=12
91  ,FF_Real32=13
92  ,FF_matrix=14 /* text matrix format */
93  };
94 
95 
96  /** @brief first tries a call to Read MIP image and if that fails,
97  tries to Import Image with all other available format loaders
98  and third party libraries.
99  Note: Win32 paths such as "C:/data/image.jpg" will work, backslashes not because they escape chars.
100  @return 0 on success
101  @return UNKNOWN_META_DATA if meta data could not be read
102  @author Felix Woelk, Jan Woetzel **/
103  static int Load(const std::string& FileName, ImageBase& img);
104 
105  /** @brief Try to load/import an image from a file using external libs.
106 
107  Formats supported are listed in TFileFormat.
108  More over a few other formats may be includeable like GIF.
109  The imported image is always of the type RGB.
110  @param filename name of the file to be loaded
111  @return -1 in case of error
112  @return UNKNOWN_META_DATA if meta data could not be read
113  param assumeGrey : DEPRECATED. Was used to speed up loading with imlib
114  @author Ingo Thomsen 2002 - Complete Rewrite by Jan Woetzel 2005 **/
115  static int ImportImage(const std::string& filename, ImageBase &result );
116 
117  /** @brief Export image as file using extrnal libs.
118 
119  @param filename name of the file to be loaded
120  @param img Image to be saved, not const because of setUUID side effect.
121  @param FileFormat What file format shall be used for saving
122  @param jpeg_quality Quality of a jpeg image to be saved,
123  unused in all other formats
124  @param sync does only worlk with pgm/ppm (woelk)
125  @param writeMetaData true to (try to) write meta data to disk and
126  false to drop it.
127  @return 0 on success
128  @author (Ingo Thomsen) - complete rewrite by Jan Woetzel */
129  static int Save(const std::string& filename,
130  const ImageBase &img,
131  const enum TFileFormat FileFormat=FF_auto,
132  const bool sync = BIAS_DEFAULT_SYNC,
133  const int c_jpeg_quality=BIAS_DEFAULT_IMAGE_QUALITY,
134  const bool forceNewID = BIAS_DEFAULT_FORCENEWID,
135  const bool & writeMetaData=true);
136 
137  /** Write image in binary file format needed by RealEyes.
138  \author bartczak 03/2008
139  **/
140  static int WriteRAW_IMA(const std::string& FileName,
141  const ImageBase &img_const);
142 
143  /** @brief Write a mip binary image to disk circumventing OS caches
144  as good as possible. (O_DIRECT)
145  @author Jan-Friso Evers*/
146  static int WriteUnbuffered(const std::string& FileName,
147  const ImageBase &img);
148 
149  /**
150  * \brief Import text images to BIAS.
151  * The format is:
152  * cols rows channels interleaved
153  * row1 (all channels)
154  * row2 .....
155  * .....
156  * \see ExportMatrix
157  * \author Ingo Schiller, moved here from biasconvert
158  * \date 03/2011
159  */
160  static int ImportMatrix(const std::string &FileName,
161  ImageBase &img,
162  const bool verbose);
163  /**
164  * \brief Export BIAS images to text images
165  * \note currently only one channel images are supported
166  * * The format is:
167  * cols rows channels interleaved
168  * row1 (all channels)
169  * row2 .....
170  * .....
171  * \see ImportMatrix
172  * \author Ingo Schiller, moved here from biasconvert
173  * \date 03/2011
174  */
175  static int ExportMatrix(const std::string &FileName,
176  const ImageBase &img,
177  const bool verbose);
178 
179  /** @brief appends extension to name if extension is not already extension,
180  avoids double extension like ".pgm.pgm"
181  @param oldName filename (maybe selected by user)
182  @param newExtension desired extension
183  @return a filename with extension
184  @author Jan Woetzel 04/2003 */
185  static std::string ExtensionName(const std::string & oldName,
186  const std::string & newExtension);
187 
188 #ifdef BIAS_HAVE_LIBJPEG
189  /** @brief Reads an image from disk using the LibJPEG library
190  encapsulated in ImportImage.
191 
192  @return 0 in case of success, negative value in case of error.
193  @param filename the input filename to read from.
194  @param result is the returned read image
195  @param readComment specifies if comment metadata should be read
196  @author esquivel 05/2008 */
197  static int ImportLibJPEG(const std::string &filename,
198  BIAS::ImageBase &result,
199  bool readComment = true);
200 
201  /** @brief Writes an image to disk using the LibJPEG library
202  encapsulated in ExportImage.
203 
204  @return 0 in case of success, negative value in case of error.
205  @param filename the filename to write image to
206  @param image is the image to save
207  @param quality determines the compression factor used for JPEG
208  (100: no compression, highest quality)
209  @author esquivel 05/2008 */
210  static int ExportLibJPEG(const std::string &filename,
211  const BIAS::ImageBase &image,
212  const int quality = 100);
213 #endif // BIAS_HAVE_LIBJPEG
214 
215 
216 #ifdef BIAS_HAVE_IMAGEMAGICKLIB
217  /** @brief Reads an image from disk using the ImageMagick++ library.
218  \todo Implement assumeGrey for MagickPP like for Imlib (JW).
219 
220  result image must be initialized. Thread image is automatically
221  converted to match the result image.
222 
223  @return 0 in case of succes, negative value in case of error.
224  @param FileName the input filename to read from.
225  @param img contains the read image if success.
226  @param assumeGrey not implemented for now, just for interface
227  compatibility with Bias Import functions
228  @param readMetaData try to read ASCII metadata from file comment.
229 
230  See http://www.imagemagick.org/script/formats.php for supported
231  formats.
232  @author Jan Woetzel 10/2004 */
233  static int ImportMagickPPAutoconvert(const std::string& FileName,
234  ImageBase& result,
235  const bool &assumeGrey=false,
236  const bool &readMetaData=false );
237 
238  /** @brief Reads an image from disk using the ImageMagick++ library.
239  is called automatically by ImportImage.
240  @param dummy ignored, for consistency with ImportMagickPPAutoconvert
241  @param readMetaData true to try to read metadat (from comment field)
242  @return 0 in case of succes, negative value in case of error.
243  \todo fix the error on reading reference streaming in Metadata
244  operator>>
245  e.g. on loading ibak "M34/Front/image00000000.jpg" (jw)
246  @author jw and woelk 12/2004 */
247  static int ImportMagickPP(const std::string & FileName,
248  ImageBase & result,
249  const bool & dummy = false,
250  const bool & readMetaData = true);
251 
252  /** @brief Reads an image from disk using the ImageMagick++ library.
253  \todo Implement 16bit short write with Magick++ using BLOB.
254  \todo Implement quality directive for jpg saving with Magick++.
255  \bug IMageMagick PPM files are alwyas written as ASCII instaed of
256  binary (JW)
257  @return 0 in case of succes, negative value in case of error.
258  @param FileName the input filename to read from.
259  @param img contains the image to be written to disk.
260  @param quality for saving, e.g.1-100 for jpeg, tested for jpeg. Is
261  overridden by losslessMode parameter
262  @param writeMetaData try to write ASCII MetaData as comment to file.
263  @param forceBinaryPNMformat true to write BINARY pnm/pbm/pgmp/ppm
264  instead of human readable ASCII.
265  @param losslesMode true to write in jpeg loslles mode. overrides
266  quality setting
267  @param writeGZipped true for additional gzip compression (e.g. .pgm.gz)
268  which may be useful for human readable ASCII pgm output but save disk
269  space.
270 
271  Output file type is determined automatically by file extension.
272 
273  See http://www.imagemagick.org/script/formats.php or \code identify
274  -list format \endcode for supported formats.
275  @author Jan Woetzel 10/2004 */
276  static int ExportMagickPP(const std::string& FileName,
277  const ImageBase img,
278  const int &quality=BIAS_DEFAULT_IMAGE_QUALITY,
279  const bool &writeMetaData=false,
280  const bool &forceBinaryPNMformat=true,
281  const bool &losslesJpgMode=false,
282  const bool &writeGZipped=false,
283  const std::string & comment=std::string("")
284  );
285 #endif // BIAS_HAVE_IMAGEMAGICKLIB
286 
287 
288 
289 #ifdef BIAS_HAVE_OPENCV
290 
291  /** @brief Reads an image from disk using the OpenCV library.
292  @param[in] filename Specifies the name of the file to read from.
293  @param[out] image Returns the image read from file if successful.
294  @return Returns 0 in case of success, < 0 in case of errors.
295  @author Jan Woetzel
296  */
297  static int ImportOpenCV(const std::string &filename, ImageBase &image);
298 
299  /** @brief Write an image to disk using the OpenCV library.
300  @param[in] filename Specifies the name of the file to write to.
301  @param[in] image Contains the image to write.
302  @return Returns 0 in case of success, < 0 in case of errors.
303  @author esquivel
304  */
305  static int ExportOpenCV(const std::string &filename, const ImageBase &image);
306 
307 #endif // BIAS_HAVE_OPENCV
308 
309 
310 
311 #ifdef BIAS_HAVE_OPENEXR
312  public:
313  /** @brief load an .exr OpenEXR image from disk.
314  */
315  static int ImportOpenEXR(const std::string& FileName, ImageBase& result);
316 
317  /** @brief save an .exr OpenEXR image to disk.
318  */
319  static int ExportOpenEXR(const std::string& FileName,
320  const ImageBase& input);
321 #endif // BIAS_HAVE_OPENEXR
322 
323 
324 
325 #ifdef BIAS_HAVE_DEVIL
326  /** @brief Reads an image from disk using the DevIL/OpenIL library.
327  See http://openil.sourceforge.net for details.
328  Supports reading multiple formats, including
329  - .bmp, .gif, .jpg, .pcd, .pcx, .pic, .png, .pnm
330  - .tga, .tif , .io
331  - .dds
332  - Doom graphics, ... and many other.
333 
334  @return 0 in case of succes, negative value in case of error.
335  @param FileName the input filename to read from.
336  @param tex3DplaneZ ignored for tex2D. Useful to extarct 2D texture from volumetric 2D texture.
337  @param result contains the read image if success.
338 
339  @author Jan Woetzel 12/2005 */
340  static int ImportDevIL(const std::string& FileName,
341  ImageBase& result,
342  const unsigned int & tex3DplaneZ=1);
343 
344  /** @brief Save to disk using the DevIL/OpenIL library.
345  See http://openil.sourceforge.net for details.
346  Supports writing multiple formats, including
347  - .dds
348  - .tga, .tif,
349  - .bmp, .jpg, .pcx, .png, .pnm
350  - .sgi,.tga
351  the fiel format is determined from the Filenames extension.
352  @return 0 in case of succes, negative value in case of error.
353  @param FileName the output filename to read from.
354  @param img image to be saved
355  @param fileOverwrite true to overwrite file if exists
356  @author Jan Woetzel 12/2005 */
357  static int ExportDevIL(const std::string& FileName,
358  const ImageBase& img,
359  const bool &fileOverwrite=true,
360  const bool &allowPadding=true );
361 
362  /** initialize devIL once globally.
363  Usually called by IL load and save functions automatically.
364  To speed up first load/save you can "pre-call" it on startup.
365  @author Jan Woetzel */
366  static void InitDevIL();
367 
368  /** print info in currently bound DevIL image
369  @author Jan Woetzel */
370  static void PrintInfoDevIL(std::ostream & os=std::cout);
371 
372 #endif // BIAS_HAVE_DEVIL
373 
374 
375  /** @brief Reads a proprietary .RAW format from disk
376  A typical file consists of these blocks:
377  - magick cookie + HEADER size - 7 Byte, e.g. "RAW4096"
378  thus magick cookies are "RAW8", "RAW4", "RAW2" ,"RAW1", "RAW0"
379  for 8192, 4096, 2048, 1024, 0512 Byte header inclufing cookie.
380 
381  E.g. RAW4096 is 4096 Byte text header followed by arbitrary size RAW
382  datat specicified in the header.
383  Used for most efficient write to disk on WIN32 using system calls
384  without buffering and cache with DMA.
385  E.g:
386  \code
387  Block Name - 4 Byte - RAW8[192] / RAW4[096] /RAW2[048]
388  /RAW1[024] / RAW0[512]
389  Block Length - 3/4 Byte - 8192/192 4096/096 should be 4 Byte but
390  is 3 Byte in old RAW4096 fmt witten for "Mediendom" project.
391  Block Data - binary data area begins at Byte nr. "block length+1",
392  e.g. 4096+1 from the begginning of file, including header.
393  \endcode
394  TODO: encode header information in Write routine compatible to digital
395  cameras .raw format which is very similar.
396 
397  FYI: IrFanView can read and display this format natively (on WIN32).
398 
399  Inspired by http://www.dalibor.cz/minolta/raw_file_format.htm
400  and the need to write exactly on aligned memory and disk block sizes
401  for performance reasons, in particular on WIN32.
402 
403  Works only with 8 bpp one plane Bayer pattern raw images
404  (from scorpion camera) actually.
405 
406  \bug Reading the data on Linux is broken because fopen ignores the
407  binary flag, see "man fopen".
408 
409  @return 0 in case of succes, negative value in case of error.
410  @author Jan Woetzel 2005 */
411  static int ImportRAWwithHeader(const std::string & filename,
412  BIAS::ImageBase & img);
413 
414 
415  /** helper function for ImportRAWwithHeader
416  Parses buf for tag
417  @return retVal value associated to tag in buf
418  @author Jan Woetzel 2005 */
419  static int ParseRAWwithHeader(const std::string & buf,
420  const std::string & tag,
421  unsigned int & retVal);
422 
423  //#ifdef BIAS_HAVE_RADIANCE
424  /** @brief import Greg Wards Radiance RGBE image format (.hdr, .rad)
425  A high dynamic range RGBE image contains 24 bits RGB Mantissa
426  and 8 common exponent bits that encode the dynamic range.
427  See http://radsite.lbl.gov/radiance/
428  Own implementation just for copyright reasons.
429  @author Jan Woetzel 01/2006 */
430  static int ImportRADIANCE(const std::string& FileName, ImageBase& result);
431  //#endif // BIAS_HAVE_RADIANCE
432 
433  /** Loads proprietary raw floating point 2d image from Mathematica Real32
434  values
435  Example how to export in Mathematica:
436  \verbatim
437  (* helper functions *)
438  Header[img_] := ({1, Dimensions[img][[1]], Dimensions[img][[2]], 1})
439  ExportReal32[filename_, img_] := Export[filename <> ".real32",
440  Append[Header[img], img], "Real32"]
441 
442  (* sample data *)
443  img = {
444  {1.1, 2.2},
445  {3.3, 4.4},
446  {5.5, 6.6} };
447 
448  (* final usage writing to disk in appropriate format: *)
449  ExportReal32["out_img", img]
450  \endverbatim
451  @author Jan Woetzel */
452  static int ImportReal32(const std::string& FileName, ImageBase& result);
453 
454 #ifdef WIN32
455 
456  /** @brief Reads a MS DIB BITMAP (.bmp) image from disk using Windows API directly.
457 
458  Windows API LoadImage is used to load HBITMAP and copy it to BIAS ImageBase memory.
459 
460  NOTES
461  - Seems to need absolute path in addition to working dir,
462  i.e. C:/Front258_Rgb.bmp or C:\\Front258_Rgb.bmp
463  - Colormap is ignored for now.
464  - works ast least for normal 24bit DIB
465 
466  @return 0 in case of succes, negative value in case of error.
467  @param FileName the input filename to read from.
468  @param result contains the read image if success.
469  @param flipY Windows DIB/BMP is vertically flipped w.r.t BIAS Image layout. true to compensate.
470  @author Jan Woetzel 03/2007 */
471  static int Import_BITMAP_winapi(const std::string& FileName,
472  ImageBase& result,
473  const bool flipY=true);
474 
475  /** @brief interface for shared memory image exchange with handle
476  @author Jan Woetzel */
477  static int BIAS::ImageIO::Import_HBITMAP_winapi(const HBITMAP & hbm,
478  ImageBase& result,
479  const bool flipY=true );
480 
481  /** @brief interface for shared memory image exchange with object
482  @author Jan Woetzel */
483  static int BIAS::ImageIO::Import_BITMAP_winapi(const BITMAP & bm,
484  ImageBase& result,
485  const bool flipY=true );
486 
487 #endif // WIN32
488 
489 
490 // use the same defines as in tiff.h for compatibility with new tokens
491 # define BIAS_COMPRESSION_NONE 1 /* dump mode */
492 # define BIAS_COMPRESSION_LZW 5 /* lossless Lempel Ziff Welch */
493 # define BIAS_COMPRESSION_DEFLATE 32946 /* lossless, known as zip in tiff */
494 #ifdef BIAS_HAVE_TIFF
495  /** @brief Write image to disk using TiffLib directly.
496  @param rowsPerStripArg nr of rows if strip based writing is used in contrast to scanlin or tile based TIFF format.
497  for value 0 the imageheight is used => one big strip.
498  @param compressionAlgo compression algorithm to use. better compression = slower. E.g. BIAS_COMPRESSION_LZW or BIAS_COMPRESSION_NONE
499  @return EXIT_SUCCESS on success, other on failure.
500  @author Jan Woetzel */
501  static int ExportTIFFLIB(const std::string& FileName,
502  const BIAS::ImageBase& img,
503  const unsigned int rowsPerStripArg=0,
504  const unsigned int compressionAlgo=BIAS_COMPRESSION_NONE,
505  const std::string & comment=std::string("BIAS::ImageIO Jan Woetzel") );
506 
507  /// @brief read a tiff image from disk using TiffLib directly
508  /// @author Jan Woetzel
509  static int ImportTIFFLIB(const std::string& FileName, ImageBase& img );
510 #endif
511 
512 
513  /** determines the BIAS::ImageIO::TFileFormat for a given filename/
514  extension
515  Decision based on extension comparison
516  @author Jan Woetzel */
517  static BIAS::ImageIO::TFileFormat GetFileFormat(const std::string &str);
518 
519  /** return the default extension for a given FileFormat enum
520  @author Jan Woetzel */
521  static std::string GetExtension(const BIAS::ImageIO::TFileFormat & fmt);
522 
523  protected:
524  static int ImportImagePnm_(std::ifstream& ifs, ImageBase &result,
525  int depth);
526  static int ExportImagePnm_(const std::string &FileName,
527  const ImageBase &img,
528  bool sync=false,
529  const bool & writeMetaData=true);
530 
531  /** @brief import a one channel grey float viff image (Khoros image format)
532  for compatibility to old stereo code
533  @param FileName destination filename
534  @param img BIAS ImageBase to be written to disk
535  @author Jan Woetzel 01/2003 */
536  static int ImportImageViff_(std::ifstream& ifs, ImageBase &result);
537 
538  // moved from public to protected and renamed - Fernandez 04/09
539  /** @brief Read a proprietary mip binary Image from disk and allocate
540  memory structure.
541 
542  Please note the more general purpose Load/Save interface you may want
543  to use instead.
544 
545  @param FileName complete name of file to be loaded
546  @param img object to receive the image data fro the file
547  @param id The image is assigned id if there is no id in the file
548  @author Felix Woelk **/
549  static int Read_(const std::string& FileName, ImageBase &img);
550 
551  // moved from public to protected and renamed - Fernandez 04/09
552  /** @brief Write a proprietary mip binary Image to disk.
553 
554  Please note the more general purpose Load/Save interface you may
555  want to use instead.
556 
557  @param FileName output file name. Extension .mip is added if
558  extension isn't already (case insensitive) 'mip' (JW 04/2003)
559  @author Felix Woelk
560  @param sync tries to flush all open buffers/caches **/
561  static int Write_(const std::string& FileName, const ImageBase &img,
562  const bool sync=false, const bool forceNewID = true);
563 
564 
565  // to WriteUnbuffered two members are needed
566  static char *MemAlignedBuffer_;
567  static unsigned long int MemAlignedBufferSize_;
568 
569 
570  }; // end of class
571 } // end of namespace BIAS
572 
573 #endif
Routines for loading and writing all kinds of image formats.
Definition: ImageIO.hh:69
TFileFormat
format specifier when writing an image to a file Do NOT change order or associated enum value because...
Definition: ImageIO.hh:76
static unsigned long int MemAlignedBufferSize_
Definition: ImageIO.hh:567
static char * MemAlignedBuffer_
Definition: ImageIO.hh:566
This is the base class for images in BIAS.
Definition: ImageBase.hh:102