25 #include <Base/Common/FileHandling.hh>
33 #ifdef BIAS_HAVE_IMAGEMAGICKLIB
34 # include <Base/Common/BIASpragmaStart.hh>
35 # include <Magick++.h>
36 # include <Base/Common/BIASpragmaEnd.hh>
37 # if (MagickLibVersion >= 0x650)
38 # define MagickLib MagickCore
43 #ifdef BIAS_HAVE_LIBJPEG
44 # include "CompressJpeg.hh"
49 #ifdef BIAS_HAVE_OPENEXR
51 # pragma warning( push, 1)
52 # define PLATFORM_WINDOWS
55 # include <ImfRgbaFile.h>
57 # include <ImfArray.h>
58 # include <ImathBox.h>
59 # include <ImfInputFile.h>
60 # include <ImfOutputFile.h>
61 # include <ImfChannelList.h>
62 # include <ImfPixelType.h>
63 # include <ImfStringAttribute.h>
64 # include "OpenEXRInterface.hh"
66 # pragma warning( pop)
71 #ifdef BIAS_HAVE_OPENCV
72 # include "WrapBias2Ipl.hh"
80 #ifdef BIAS_HAVE_DEVIL
84 # endif // USE_DEVIL_ILU
92 # if TIFFLIB_VERSION < 20051230
93 # error You need at least TIFF version 3.8.0 (TIFFLIB_VERSION >= 20051230) for muli plane tiff.
98 #include <Base/Debug/DebugSimple.hh>
101 # include <Base/Debug/TimeMeasurement.hh>
102 # include <Base/Debug/LogFacility.hh>
108 #include "ImageConvert.hh"
109 #include "ViffHeader.hh"
122 #ifdef BIAS_IMAGEMAGICKLIB_V2
123 # define MagickLib MagickCore
124 #endif //BIAS_IMAGEMAGICKLIB_V2
127 using namespace BIAS;
135 char myTolower(
char c) {
136 return char(tolower(c));
143 #if defined(BIAS_DEBUG) && defined(ImageIO_DEBUG_IO)
153 is.open( FileName.c_str() );
154 char identifier[IDENTIFIER_LENGTH];
156 if (!is || !is.good()){
158 #if defined(BIAS_DEBUG) || defined(ImageIO_DEBUG_IO)
163 is.read(identifier, IDENTIFIER_LENGTH);
168 if (identifier[0] ==
'M' && identifier[1] ==
'I' &&
169 identifier[2] ==
'P'){
171 #if defined(BIAS_DEBUG) && defined(ImageIO_DEBUG_IO)
172 COUT(
"MIP format detected\n");
175 result = Read_(FileName, img);
179 #if defined(BIAS_DEBUG) && defined(ImageIO_DEBUG_IO)
180 COUT(
"image not in mip format\n");
191 #ifdef BIAS_HAVE_IMAGEMAGICKLIB
196 const bool & readMetaData )
198 #if defined(BIAS_DEBUG) && defined(ImageIO_DEBUG_IO)
204 Magick::InitializeMagick(NULL);
208 image.read( FileName );
226 string sTmp = image.comment();
237 if (!image.comment().empty() && result.
GetMetaData()->size() == 0) {
248 return BIAS_IO_SUCCESS;
250 #endif // BIAS_HAVE_IMAGEMAGICKLIB
253 #ifdef BIAS_HAVE_OPENCV
258 #if defined(BIAS_DEBUG) && defined(ImageIO_DEBUG_IO)
262 IplImage* p_cv = cvLoadImage(filename.c_str(), 1);
264 #if defined(BIAS_DEBUG) && defined(ImageIO_DEBUG_IO)
265 BIASERR(
"Reading image from " << filename <<
" with OpenCV failed!");
271 if (p_cv->nChannels == 4) {
272 cvCvtColor(p_cv, p_cv, CV_BGRA2RGBA);
273 strcpy(p_cv->channelSeq,
"RGBA");
274 }
else if (p_cv->nChannels == 3) {
275 cvCvtColor(p_cv, p_cv, CV_BGR2RGB);
276 strcpy(p_cv->channelSeq,
"RGB");
281 cvReleaseImage(&p_cv);
288 #if defined(BIAS_DEBUG) && defined(ImageIO_DEBUG_IO)
292 IplImage* p_cv = NULL;
296 if (p_cv->nChannels == 4) {
297 cvCvtColor(p_cv, p_cv, CV_BGRA2RGBA);
298 strcpy(p_cv->channelSeq,
"RGBA");
299 }
else if (p_cv->nChannels == 3) {
300 cvCvtColor(p_cv, p_cv, CV_BGR2RGB);
301 strcpy(p_cv->channelSeq,
"RGB");
303 if (cvSaveImage(filename.c_str(), p_cv) == 0) {
304 #if defined(BIAS_DEBUG) && defined(ImageIO_DEBUG_IO)
305 BIASERR(
"Writing image to " << filename <<
" with OpenCV failed!");
310 if (p_cv->nChannels == 4)
311 cvCvtColor(p_cv, p_cv, CV_BGRA2RGBA);
312 else if (p_cv->nChannels == 3)
313 cvCvtColor(p_cv, p_cv, CV_BGR2RGB);
318 #endif // BIAS_HAVE_OPENCV
321 #ifdef BIAS_HAVE_OPENEXR
325 int PrintInfoEXR(
const Imf::RgbaInputFile & f, std::ostream & os)
328 using namespace Imath;
329 os<<
"OpenEXR header information: "<<endl;
330 os<<
"version: "<<f.version()<<endl;
334 const Imf::Header * h = &f.header();
337 Box2i dw = f.dataWindow();
339 os<<
"hasPreviewImage: "<<h->hasPreviewImage()<<endl;
340 os<<
"pixelAspectRatio:"<<h->pixelAspectRatio()<<endl;
342 os<<
"dw dim: "<<dw.max.x - dw.min.x + 1
344 <<dw.max.y - dw.min.y + 1
346 os<<
" dw.x: "<<dw.min.x<<
".."<<dw.max.x <<endl;
347 os<<
" dw.y: "<<dw.min.y<<
".."<<dw.max.y <<endl;
349 return BIAS_IO_SUCCESS;
357 #if defined(BIAS_DEBUG) && defined(ImageIO_DEBUG_IO)
361 return interfaceEXR.
Export(FileName, img);
367 #if defined(BIAS_DEBUG) && defined(ImageIO_DEBUG_IO)
371 return interfaceEXR.
Import(FileName, result);
374 #endif // BIAS_HAVE_OPENEXR
380 #if defined(BIAS_DEBUG) && defined(ImageIO_DEBUG_IO)
386 unsigned char tmpline[512];
389 ifs.open(filename.c_str(),ios::binary);
391 ifs.open(filename.c_str());
395 BIASERR(
"ImportImage(): open of file \""<<filename<<
"\" failed");
396 perror(filename.c_str());
405 ifs >>tmpline[0]>>tmpline[1];
408 BIASERR(
"unable to read from "<<filename);
415 if (tmpline[0] ==
'P' && tmpline[1] ==
'5') {
416 #if defined(BIAS_DEBUG) && defined(ImageIO_DEBUG_IO)
417 COUT(
"reading single channel pnm/pgm/pbm image using ImportImagePnm_\n");
419 res = ImportImagePnm_(ifs, result, 1);
420 if (res!=BIAS_IO_SUCCESS)
421 BIASERR(
"error reading "<<filename<<
" although P5 format detected.");
423 }
else if (tmpline[0] ==
'P' && tmpline[1] ==
'6') {
424 #if defined(BIAS_DEBUG) && defined(ImageIO_DEBUG_IO)
425 COUT(
"reading 3 channel pnm/pgm/pbm image using ImportImagePnm_\n");
427 res = ImportImagePnm_(ifs, result, 3);
428 if (res!= BIAS_IO_SUCCESS)
429 BIASERR(
"error reading "<<filename<<
" although P6 format detected.");
441 if(res!=BIAS_IO_SUCCESS)
442 res = ImportMatrix(filename,result,
false);
444 #ifdef BIAS_HAVE_OPENEXR
445 if (res!=BIAS_IO_SUCCESS)
446 res=ImportOpenEXR(filename, result);
449 #ifdef BIAS_HAVE_IMAGEMAGICKLIB
450 if (res!=BIAS_IO_SUCCESS)
451 res=ImportMagickPP(filename, result);
454 #ifdef BIAS_HAVE_DEVIL
455 if (res!=BIAS_IO_SUCCESS)
456 res=ImportDevIL(filename, result);
459 #ifdef BIAS_HAVE_LIBJPEG
460 if (res!=BIAS_IO_SUCCESS)
461 res=ImportLibJPEG(filename, result);
464 #ifdef BIAS_HAVE_OPENCV
465 if (res!=BIAS_IO_SUCCESS)
466 res=ImportOpenCV(filename, result);
470 if (res!=BIAS_IO_SUCCESS)
471 res=ImportRADIANCE(filename, result);
475 if (res!=BIAS_IO_SUCCESS)
476 res=ImportRAWwithHeader(filename, result);
478 #ifdef WIN32 // winapi
479 if (res!=BIAS_IO_SUCCESS)
480 res=Import_BITMAP_winapi(filename, result);
490 if (res!=BIAS_IO_SUCCESS) {
492 std::ifstream ifs(filename.c_str(), std::ios::binary );
494 BIASERR(
"could not open "<<filename);
497 res=ImportImageViff_(ifs, result );
510 ad.
sdata.erase(0, 1);
511 if (ad.
sdata.length()>36)
517 BIASERR(
"UUID is no meta datum in binary images");
518 BIASERR(
"possibly two concurrent UUIDs in one image");
525 # ifdef BIAS_EXTRA_WARN
526 BIASERR(
"warning, no valid UID read, UUID must be set manually");
538 #ifdef BIAS_HAVE_LIBJPEG
543 #if defined(BIAS_DEBUG) && defined(ImageIO_DEBUG_IO)
557 res = jHandler.
Init();
562 res = jHandler.
Decompress(image, readComment);
570 return (res == 0 ? BIAS_IO_SUCCESS : -1);
577 #if defined(BIAS_DEBUG) && defined(ImageIO_DEBUG_IO)
581 int xres=-1, yres=-1, maxval=-1, read=0;
587 ifs.seekg(0,ios::beg);
592 BIASERR(
"invalid magic cookie");
597 if (c!=
'5' && c!=
'6'){
598 BIASERR(
"invalid magic cookie");
609 BIASERR(
"error reading meta data");
612 }
else if (c>29 || c<40){
630 BIASERR(
"funny error: "
631 <<
"there should be only 3 numerical values in pgm header");
636 BIASERR(
"corrupted image header "<<c);
639 ifs.read(&c, 1*
sizeof(
char));
646 BIASERR(
"warning trying to load an unsigned char image into an image of"
653 ifs.read(reinterpret_cast<char *>(result.
GetImageData()), xres * yres * depth);
654 }
else if (maxval==4095){
658 BIASERR(
"WARNING: Trying to load an unsigned short int image into an "
664 ifs.read(reinterpret_cast<char *>(result.
GetImageData()),
665 sizeof(
unsigned short int) * xres * yres * depth);
667 unsigned short int *p=(
unsigned short int *)result.
GetImageData(), *pe;
671 while (p<pe) { swap = (swap || (*p > maxval)); p++; }
674 BIASERR(
"Max. value > "<<maxval<<
" : Swapping LSB and MSB!");
676 cpe=(
char *)((
unsigned short int *)cp + result.
GetPixelCount()*
680 c=cp[0]; cp[0]=cp[1]; cp[1]=c;
684 }
else if(maxval==65535){
688 BIASERR(
"WARNING: Trying to load an unsigned short int image into an "
694 ifs.read(reinterpret_cast<char *>(result.
GetImageData()),
695 sizeof(
unsigned short int) * xres * yres * depth);
697 unsigned short int *p=(
unsigned short int *)result.
GetImageData(), *pe;
701 while (p<pe) { swap = (swap || (*p > maxval)); p++; }
704 BIASERR(
"Max. value > "<<maxval<<
" : Swapping LSB and MSB!");
706 cpe=(
char *)((
unsigned short int *)cp + result.
GetPixelCount()*
710 c=cp[0]; cp[0]=cp[1]; cp[1]=c;
717 BIASERR(
"error reading from ifs");
729 const int c_jpeg_quality,
730 const bool forceNewID,
731 const bool & writeMetaData)
733 #if defined(BIAS_DEBUG) && defined(ImageIO_DEBUG_IO)
736 bool TriedIt =
false;
740 #if defined(BIAS_HAVE_IMAGEMAGICKLIB) || defined(BIAS_HAVE_LIBJPEG)
741 int quality = c_jpeg_quality;
746 if (FileFormat==FF_auto)
749 FileFormat=GetFileFormat(c_filename);
752 if (FileFormat==FF_unknown)
757 string filename(c_filename);
761 BIASERR(
"cannot save images with StoragType ST_invalid. ");
787 BIASWARN(
"UUID assignment required. Please fix your code and assign a UID in the calling function if desired.");
804 if (result!=BIAS_IO_SUCCESS)
815 result = Write_(filename, img, sync, forceNewID);
820 result = ExportMatrix(filename, img,
false);
826 filename = ExtensionName( filename, GetExtension(FileFormat) );
835 result = ExportImagePnm_(filename,greyIMG,sync,writeMetaData);
839 result = ExportImagePnm_(filename,img,sync,writeMetaData);
846 #if defined(BIAS_HAVE_IMAGEMAGICKLIB) || defined(BIAS_HAVE_LIBJPEG)
848 if (c_jpeg_quality < 0 || c_jpeg_quality > 100)
850 BIASERR(
"The quality "<<c_jpeg_quality
851 <<
" is out of valid range 0..100 % falling back to 100% full quality." );
855 BIASERR(
"No JPEG support activated in BIAS. Switch on ImageMagick or LibJPEG in BIAS to enable jpeg support.");
862 BIASERR(
"writing raw4096 is not (yet) implemented in BIAS, only on WIN32 scorpion grab application.");
875 filename = ExtensionName( filename, GetExtension(FileFormat) );
878 BIASERR(
"Unknown image file format for saving "<<c_filename<<
" with format:"<<FileFormat<<
" Nothing saved!");
887 if (result!=BIAS_IO_SUCCESS) {
888 if (FileFormat==FF_matrix) {
889 result= ExportMatrix(filename,img,
false);
893 #ifdef BIAS_HAVE_OPENEXR
894 if (result!=BIAS_IO_SUCCESS) {
896 if (FileFormat==FF_exr) {
897 result=ExportOpenEXR(filename, img );
903 #ifdef BIAS_HAVE_IMAGEMAGICKLIB
905 if (result!=BIAS_IO_SUCCESS) {
908 if ((FileFormat!=FF_dds) && (FileFormat!=FF_exr) &&
909 (FileFormat!=FF_mip) && (FileFormat!=FF_raw4096))
911 result=ExportMagickPP (filename, img, quality, writeMetaData);
917 #ifdef BIAS_HAVE_DEVIL
919 if (result!=BIAS_IO_SUCCESS) {
920 if ((FileFormat!=FF_exr) && (FileFormat!=FF_mip) &&
921 (FileFormat!=FF_raw4096))
923 result=ExportDevIL(filename, img);
929 #ifdef BIAS_HAVE_LIBJPEG
931 if (result!=BIAS_IO_SUCCESS){
932 if (FileFormat == FF_jpg) {
933 result=ExportLibJPEG(filename, img);
939 #ifdef BIAS_HAVE_OPENCV
941 if (result != BIAS_IO_SUCCESS) {
942 result = ExportOpenCV(filename, img);
948 BIASERR(
"Image not even tried to be written");
954 #ifdef BIAS_HAVE_LIBJPEG
960 #if defined(BIAS_DEBUG) && defined(ImageIO_DEBUG_IO)
964 if (quality < 0 || quality > 100) {
965 BIASERR(
"Invalid quality " << quality <<
" given for JPEG compression!");
977 res = jHandler.
Init();
979 res = jHandler.
Compress(image_UC, quality);
986 return (res == 0 ? BIAS_IO_SUCCESS : -1);
994 const bool & writeMetaData)
996 #if defined(BIAS_DEBUG) && defined(ImageIO_DEBUG_IO)
1003 ofs.open(FileName.c_str(),ios::binary);
1005 ofs.open(FileName.c_str());
1009 BIASERR(
"ExportImagePnm_() : open of file "<<FileName<<
" failed");
1010 perror(FileName.c_str());
1016 BIASERR(FUNCNAME <<
" supports only 8 bit per Channel images. Please call "
1017 <<
"ExportImage or Save instead.");
1029 BIASERR(
"ExportImagePnm_() : unsupported number of channels: "<<
1037 BIASERR(
"writing MetaData failed");
1047 BIASERR(
"ExportImagePnm_() : write failed");
1057 fsync(ofs.rdbuf()->fd());
1059 ofs.rdbuf()->pubsync();
1062 ofs.rdbuf()->pubsync();
1073 const std::string & newExtension)
1075 string name = oldName;
1085 if (ext!=newExtLC) {
1087 if (name[name.size()-1] !=
'.')
1097 bool sync,
bool forceNewID)
1099 #if defined(BIAS_DEBUG) && defined(ImageIO_DEBUG_IO)
1117 os.open(file.c_str(),ios::binary);
1119 os.open(file.c_str());
1123 string Errorstring=
"Error opening "+file+
" writing";
1124 perror(Errorstring.c_str());
1131 res = (os.good())?(0):(-5);
1138 BIASERR(
"writing MetaData failed");
1148 # if __GNUC__ < 3 // in gcc 2.9x we can get a POSIX file descriptor
1149 fsync(os.rdbuf()->fd());
1150 # else // in gcc 3.x this is prohibited :-(
1151 os.rdbuf()->pubsync();
1163 #ifndef _WIN32 // alternative way to sync, reopen file to get a handle
1164 int fd = open(file.c_str(),O_APPEND);
1175 #if defined(BIAS_DEBUG) && defined(ImageIO_DEBUG_IO)
1185 BIASERR(
"need planar image!");
1189 short width =
static_cast<short>(img.
GetWidth());
1190 short height =
static_cast<short>(img.
GetHeight());
1192 unsigned char* pel = (
unsigned char*)img.
GetImageData();
1199 os.open(file.c_str(),ios::binary);
1203 string Errorstring=
"Error opening "+file+
" writing";
1204 perror(Errorstring.c_str());
1209 os.write((
char*)&intro,
sizeof(
short));
1210 os.write((
char*)&width,
sizeof(
short));
1211 os.write((
char*)&channels,
sizeof(
short));
1212 for(
unsigned int i=0; i<(
unsigned int)width*height*3; i++) {
1213 unsigned char out = 255 - pel[i] ;
1214 os.write((
char*)&(out),
sizeof(
unsigned char));
1219 res = (os.good())?(0):(-5);
1223 #ifndef _WIN32 // alternative way to sync, reopen file to get a handle
1224 int fd = open(file.c_str(),O_APPEND);
1237 if(verbose) cout<<
"converting textfile to image matrix...\n";
1238 ifstream in(FileName.c_str());
1240 BIASERR(
"could not load"<<FileName);
1243 unsigned int rows,cols,cc, interleaved;
1244 in >> rows >> cols >> cc >> interleaved;
1247 cout<<
"Rows:"<<rows<<
" Cols:"<<cols
1248 <<
" Channelcount:"<<cc<<
" Interleaved:"<<interleaved<<
"\n";
1252 for (
unsigned int h=0; h<rows; h++) {
1253 for (
unsigned int w=0; w<cols; w++) {
1254 for (
unsigned int c=0; c<cc; c++) {
1256 in >> data[h][w*cc+c];
1258 in >> data[h+rows*c][w];
1269 const ImageBase &ipic,
const bool verbose)
1275 if(verbose) cout<<
"converting image matrix to textfile...\n";
1277 BIASERR(
"conversion only implemented for single channel images");
1280 unsigned int rows,cols,cc, interleaved;
1286 cout<<
"Rows:"<<rows<<
" Cols:"<<cols
1287 <<
" Channelcount:"<<
" interleaved:"<<interleaved<<cc<<
"\n";
1289 ofstream ofs(FileName.c_str());
1291 BIASERR(
"Could not open stream to "<<FileName);
1294 ofs<<rows<<
" "<<cols<<
" "<<cc<<
" "<<interleaved<<endl;
1301 for(
unsigned int h = 0; h< rows; h++) {
1303 for(
unsigned w = 0; w< cols; w++) {
1304 for(
unsigned c = 0; c< cc; c++) {
1306 ofs<<imageDataArray[h][w*cc+c];
1308 ofs<<imageDataArray[h+rows*c][w];
1317 for(
unsigned int h = 0; h< rows; h++) {
1319 for(
unsigned w = 0; w< cols; w++) {
1320 for(
unsigned c = 0; c< cc; c++) {
1322 ofs<<imageDataArray[h][w*cc+c];
1324 ofs<<imageDataArray[h+rows*c][w];
1331 BIASERR(
"Unsupported storage type of input image");
1335 if (verbose) cout <<
"done"<<endl;
1343 #if defined(BIAS_DEBUG) && defined(ImageIO_DEBUG_IO)
1351 is.open(FileName.c_str(),ios::binary);
1353 is.open(FileName.c_str());
1357 string Errorstring=
"Error opening "+FileName+
" for reading";
1358 perror(Errorstring.c_str());
1364 res = (is.good())?(0):(-5);
1369 if (!is && !is.eof()){
1370 BIASERR(
"error reading MetaData");
1388 #if defined(BIAS_DEBUG) && defined(ImageIO_DEBUG_IO)
1396 ifs.seekg(0, ios::beg);
1399 ifs.read((
char*)&viff,
sizeof(viff));
1400 #if defined(BIAS_DEBUG) && defined(ImageIO_DEBUG_IO)
1405 const unsigned long maxUsefulDim=4096*2;
1406 const unsigned long minUsefulDim=8;
1414 #if defined(BIAS_DEBUG) && defined(ImageIO_DEBUG_IO)
1416 "viff image dim "<<viff.
row_size<<
"x"<<viff.
col_size<<
" is not useful(>"<<maxUsefulDim<<
"),"<<endl
1417 <<
"handling it as error. Skipping viff read. Adapt maxUsefulDim if you feel this behavior is wrong. "
1440 #ifdef BIAS_HAVE_IMAGEMAGICKLIB
1453 const bool &readMetaData )
1455 #if defined(BIAS_DEBUG) && defined(ImageIO_DEBUG_IO)
1461 Magick::InitializeMagick(NULL);
1466 Magick::Image image;
1469 image.read( FileName );
1471 #if defined(BIAS_DEBUG) && defined(ImageIO_DEBUG_IO)
1473 "DBG Read "<<image.columns()<<
"x"<<image.rows()<<
" "
1474 <<image.magick()<<
" image "
1475 <<FileName<<
" using ImageMagick++"<<endl
1476 <<
" depth: "<<image.depth()<<
" bit."<<endl
1477 <<
" comment: "<<endl<<image.comment()<<endl
1482 Magick::StorageType outputST=Magick::CharPixel;
1495 BIASERR(
"invalid Storagetype ST_invalid FileName="<<FileName<<endl);
1501 if (image.depth() != 8*
sizeof(char)){
1502 BIASERR(
"StorageType is "<<8*
sizeof(
char)<<
" bit but data has "<<image.depth()<<
" bit depth. FileName="<<FileName<<endl);
1509 outputST=Magick::CharPixel;
1510 COUT(
"is an "<<8*
sizeof(
char)<<
" bit (u)char image\n");
1517 if (image.depth()!=8*
sizeof(short)){
1518 BIASERR(
"StorageType is "<<8*
sizeof(
short)<<
" bit "
1519 <<
"but data has "<<image.depth()<<
" bit depth. "
1520 <<
"FileName="<<FileName<<endl);
1523 outputST=Magick::ShortPixel;
1524 COUT(
"is a "<<8*
sizeof(
short)<<
" bit (u)short image\n");
1531 if (image.depth()==8*
sizeof(int)){
1532 BIASERR(
"StorageType is "<<8*
sizeof(
int)<<
" bit but data has "<<image.depth()<<
" bit depth. FileName="<<FileName<<endl);
1535 outputST=Magick::IntegerPixel;
1536 COUT(
"is a "<<8*
sizeof(
int)<<
" bit (u)int image\n");
1543 if (image.depth()!=8*
sizeof(float)) {
1544 BIASERR(
"StorageType is "<<8*
sizeof(
float)<<
" bit but data has "<<image.depth()<<
" bit depth. FileName="<<FileName<<endl);
1547 outputST=Magick::FloatPixel;
1548 COUT(
"is a "<<8*
sizeof(
float)<<
" bit float image\n");
1549 BIASERR(
"warning: You are using ImageMagick to read a float image. Be aware that ImageMagick float values are normalized to 0..1 !!!"<<endl);
1555 if (image.depth()!=8*
sizeof(double)){
1556 BIASERR(
"StorageType is "<<8*
sizeof(
double)<<
" bit but data has "<<image.depth()<<
" bit depth. FileName="<<FileName<<endl);
1559 outputST=Magick::DoublePixel;
1560 COUT(
"is a "<<8*
sizeof(
double)<<
" bit float image\n");
1561 BIASERR(
"warning: You are using ImageMagick to read a double image. Be aware that ImageMagick float values are normalized to 0..1 !!!"<<endl);
1566 BIASERR(
"StorageType "<<result.
GetStorageType()<<
" not supported. FileName="<<FileName<<endl);
1574 string magickMap=
"RGB";
1575 unsigned int nChannels=3;
1579 COUT(
"DBG CM_invalid. Setting default map RGB\n");
1585 COUT(
"DBG CM_Grey\n");
1611 BIASERR(
"unknown result Color Model "<<result.
GetColorModel()<<
" "
1612 <<
"reading "<<FileName<<endl);
1617 result.
Init((
unsigned int)image.columns(), (
unsigned int)image.rows(), nChannels);
1622 unsigned char* p_imageData = (
unsigned char*)result.
GetImageData();
1623 BIASASSERT( p_imageData != NULL);
1634 BIASERR(
"reading of MetaData is not implemented for IMageMagick++ but could be done using BIAS::ImageAttributes class(10/2004)\n");
1637 catch( Magick::Exception &error_ ) {
1638 BIASERR(
"Reading "<<FileName<<
" with Magick++ failed."<<endl
1639 <<
" Caught exception: "<<endl
1640 <<
" "<<error_.what()<<endl );
1644 BIASERR(
"Reading "<<FileName<<
" with Magick++ failed."<<endl);
1647 return BIAS_IO_SUCCESS;
1655 const bool &writeMetaData,
1656 const bool &forceBinaryPNMformat,
1657 const bool &losslesJpgMode,
1658 const bool &writeGZipped,
1659 const string & comment
1662 #if defined(BIAS_DEBUG) && defined(ImageIO_DEBUG_IO)
1671 string FileName(FileNameStr);
1673 commentTmp.append(comment);
1677 Magick::InitializeMagick(NULL);
1682 if (ext ==
".jpg" || ext ==
".png"){
1683 cout <<
"One channel and file suffix is" << ext << endl;
1685 BIASWARN(
"JPEG / PNG does not support grey scale images. Converting image to RGB.");
1697 Magick::Image image;
1700 if(ret != 0)
return ret;
1704 image.quality(quality);
1706 if (forceBinaryPNMformat){
1709 if ((ext==
".pnm")|| (ext==
".pbm")|| (ext==
".pgm")|| (ext==
".ppm")) {
1722 image.compressType(Magick::RLECompression);
1726 image.compressType(Magick::NoCompression);
1729 if (losslesJpgMode){
1730 image.compressType(MagickLib::LosslessJPEGCompression);
1743 #if defined(BIAS_DEBUG) && defined(ImageIO_DEBUG_IO)
1745 <<FileName <<
"\" using ImageMagick++ "<<endl);
1746 #endif // BIAS_DEBUG
1748 if (writeMetaData) {
1756 commentTmp.append(ss.str());
1759 #if defined(BIAS_DEBUG) && defined(ImageIO_DEBUG_IO)
1760 BIASERR(
"writing MetaData using ImageMagick IO is not implemented.");
1765 if (commentTmp.size()>=4096){
1766 BIASWARN(
"comment size "<<comment.size()<<
" is >= 4096 characters. This may be too long for some image formats.");
1768 image.comment( commentTmp );
1771 image.write(FileName);
1773 catch( Magick::Exception &error_ ) {
1774 BIASERR(
"Writing "<<FileName<<
" with Magick++ failed."<<endl
1775 <<
" Caught exception: "<<endl
1776 <<
" "<<error_.what()<<endl );
1780 BIASERR(
"Writing "<<FileName<<
" with Magick++ failed."<<endl);
1784 return BIAS_IO_SUCCESS;
1787 #endif // BIAS_HAVE_IMAGEMAGICKLIB
1794 #if defined(BIAS_DEBUG) && defined(ImageIO_DEBUG_IO)
1799 unsigned int hdrSZ=0;
1801 unsigned int Cols=0;
1802 unsigned int Rows=0;
1807 is.open(filename.c_str());
1811 #if defined(BIAS_DEBUG) && defined(ImageIO_DEBUG_IO)
1812 BIASERR(
"could not open image file: "<<filename);
1821 if (line.size()<3)
return -2;
1824 string ref7(
"RAW4096");
1825 string ref(
"RAW04096");
1826 if ( (0==line.compare(0, ref.size(), ref))
1827 || (0==line.compare(0, ref7.size(), ref7)) )
1829 COUT(
"RAW04096/RAW4096 found."<<endl);
1833 if (0==line.compare(0, ref.size(), ref)){
1837 if (0==line.compare(0, ref.size(), ref)){
1841 if (0==line.compare(0, ref.size(), ref)){
1845 if (0==line.compare(0, ref.size(), ref)){
1848 #if defined(BIAS_DEBUG) && defined(ImageIO_DEBUG_IO)
1849 BIASERR(filename<<
" is no RAW4096/RAWnnnn image. aborting.");
1860 string hdr(hdrSZ,
' ');
1863 is.read(&(hdr[0]), hdrSZ);
1867 ok = ok && (0==ParseRAWwithHeader(hdr,
"RowInc=", Cols));
1868 ok = ok && (0==ParseRAWwithHeader(hdr,
"Rows=", Rows));
1870 if (ok) cout<<
"found dim "<<Cols<<
"x"<<Rows<<endl;
1876 img.
Init(Cols, Rows, 1);
1886 if (fopen_s(&fp, filename.c_str(),
"rt") != 0) {
1887 cout<<
"could not open "<<filename<<
" for C reading"<<endl;
1891 fp = fopen(filename.c_str(),
"rt");
1893 cout<<
"could not open "<<filename<<
" for C reading"<<endl;
1898 unsigned int dataSZ=Cols*Rows;
1901 char * p_data =
new char[dataSZ];
1902 memset(p_data, 0, dataSZ);
1905 fread( p_data, hdrSZ, 1, fp );
1908 fread( p_data, dataSZ, 1, fp );
1923 const std::string & tag,
1924 unsigned int & retVal)
1926 string::size_type posStart, posEnd;
1928 posStart=buf.find(tag, 0);
1929 if (posStart!=string::npos){
1931 posEnd = buf.find(
string(
"\n"), posStart);
1932 if (posEnd!=string::npos){
1933 valueStr=buf.substr(posStart+tag.size(), posEnd-posStart-tag.size());
1937 cout<<
"valueStr="<<valueStr<<
" : "<<retVal<<endl;
1940 cout<<
"not found!"<<endl;
1949 # pragma warning (push)
1950 # pragma warning (disable: 4702) // unreachable code
1955 BIASERR(
"ImageIO::WriteUnbuffered() not implemented in Win32");
1959 # pragma warning (pop)
1967 BIASERR(
"ImageIO::WriteUnbuffered() not implemented in Win32");
1978 #if defined(BIAS_DEBUG) && defined(ImageIO_DEBUG_IO)
1980 #endif // defined(BIAS_DEBUG) && defined(ImageIO_DEBUG_IO)
1987 std::ostringstream FlatImage;
1991 unsigned long int is = FlatImage.str().size();
1993 if (MemAlignedBufferSize_ < is) {
1994 if (MemAlignedBuffer_ != NULL) free(MemAlignedBuffer_);
1995 MemAlignedBufferSize_ = 512;
1996 while (MemAlignedBufferSize_ < is)
1997 MemAlignedBufferSize_ +=512;
2002 char** bufferPointer = &MemAlignedBuffer_;
2003 int r = posix_memalign((
void**)bufferPointer, 512,
2004 MemAlignedBufferSize_);
2006 BIASERR(
"posix_memalign failed: "<<r);
2010 if (MemAlignedBuffer_ == NULL) {
2011 BIASERR(
"Can not posix_memalign()"<<MemAlignedBufferSize_<<
" bytes");
2016 memcpy(MemAlignedBuffer_, FlatImage.str().c_str(), is);
2018 int fd = open(FileName.c_str(), O_WRONLY | O_CREAT | O_DIRECT, 0644);
2020 BIASERR(
"Can not open/create file ");
2021 perror(FileName.c_str());
2024 fchmod(fd,S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH);
2025 int res = write(fd,MemAlignedBuffer_, MemAlignedBufferSize_);
2027 BIASERR(
"Can not write with O_DIRECT to file ");
2028 perror(FileName.c_str());
2036 # endif // __APPLE__
2041 #ifdef BIAS_HAVE_DEVIL
2045 static bool il_initialized=
false;
2047 if (!il_initialized)
2049 #if defined(BIAS_DEBUG) && defined(ImageIO_DEBUG_IO)
2051 if (ilGetInteger(IL_VERSION_NUM) < IL_VERSION) {
2052 BIASERR(
"DevIL/OpenIL: "<<endl
2053 <<
"IL versions of run-and compiletime are different. "<<endl
2054 <<
"compile time IL_VERSION ="<<IL_VERSION<<endl
2055 <<
"runtime IL_VERSION_NUM="<<ilGetInteger(IL_VERSION_NUM)<<endl
2056 <<
"There is a risk that the headers dont match the shared library/DLL. ");
2058 # ifdef USE_DEVIL_ILU
2059 if (iluGetInteger(ILU_VERSION_NUM) < ILU_VERSION) {
2060 BIASERR(
"DevIL/OpenIL: "
2061 <<
"ILU versions of run-and compiletime are different. "
2062 <<
" There is a risk that the headers dont match the DLL. ");
2064 # endif // USE_DEVIL_ILU
2065 #endif // BIAS_DEBUG && ImageIO_DEBUG_IO
2069 #ifdef USE_DEVIL_ILU
2074 il_initialized=
true;
2076 #if defined(BIAS_DEBUG) && defined(ImageIO_DEBUG_IO)
2077 COUT(
"initialized DevIL(OpenIL) runtime version: "
2078 <<ilGetInteger(IL_VERSION_NUM)<<endl );
2088 <<
"dim: "<<ilGetInteger(IL_IMAGE_WIDTH)<<
"x"
2089 <<ilGetInteger(IL_IMAGE_HEIGHT)<<
" pixel"<<endl
2090 <<
"depth=planes "<<ilGetInteger(IL_IMAGE_DEPTH)<<
" plane(s) ";
2091 if (ilGetInteger(IL_IMAGE_DEPTH)>1)
2094 os<<
"size of data "<<ilGetInteger(IL_IMAGE_SIZE_OF_DATA)<<
" Byte total"<<endl
2095 <<
"BytePerPixel "<<ilGetInteger(IL_IMAGE_BPP)<<endl
2096 <<
"Bytes/Pixel "<<ilGetInteger(IL_IMAGE_BYTES_PER_PIXEL)<<endl
2097 <<
"Bits/Pixel "<<ilGetInteger(IL_IMAGE_BITS_PER_PIXEL)<<endl
2098 <<
"num images "<<ilGetInteger(IL_NUM_IMAGES)<<endl
2099 <<
"num mipmaps "<<ilGetInteger(IL_NUM_MIPMAPS)<<endl
2101 <<
"origin_set "<<ilGetInteger(IL_ORIGIN_SET)<<
" "
2102 <<
"image_origin "<<ilGetInteger(IL_IMAGE_ORIGIN)<<
" "
2104 switch (ilGetInteger(IL_IMAGE_ORIGIN)) {
2106 os<<
"IL_ORIGIN_SET";
break;
2107 case IL_ORIGIN_LOWER_LEFT:
2108 os<<
"IL_ORIGIN_LOWER_LEFT";
break;
2109 case IL_ORIGIN_UPPER_LEFT:
2110 os<<
"IL_ORIGIN_UPPER_LEFT";
break;
2111 case IL_ORIGIN_MODE:
2112 os<<
"IL_ORIGIN_MODE";
break;
2117 <<ilGetInteger(IL_IMAGE_OFFX)<<
" "<<ilGetInteger(IL_IMAGE_OFFY)<<endl
2124 const unsigned int & tex3DplaneZ )
2126 #if defined(BIAS_DEBUG) && defined(ImageIO_DEBUG_IO)
2133 ILuint id(0), err(0);
2134 ilGenImages(1, &
id);
2137 bool ok = (IL_TRUE==ilLoadImage( (
char*)(FileName.c_str()) ));
2140 if (err!=IL_NO_ERROR || !ok) {
2141 #if defined(BIAS_DEBUG) && defined(ImageIO_DEBUG_IO)
2143 ss<<
"could not load "<<FileName<<
" ";
2144 # ifdef USE_DEVIL_ILU
2146 if (err!=IL_NO_ERROR)
2147 ss<<
": "<<iluErrorString(err);
2150 #endif // BIAS_DEBUG && ImageIO_DEBUG_IO
2151 ilDeleteImages(1, &
id);
2155 #if defined(BIAS_DEBUG) && defined(ImageIO_DEBUG_IO)
2160 const int nDepthPlanes = int( ilGetInteger(IL_IMAGE_DEPTH) );
2161 if (nDepthPlanes>1){
2163 BIASERR(
"detected tex3D with "<<nDepthPlanes<<
" planes. It is a volume, not a 2D texture. NOT implemented.");
2165 ilDeleteImages(1, &
id);
2170 if (nDepthPlanes<(
int)tex3DplaneZ ){
2171 BIASERR(
"Image has only "<<nDepthPlanes<<
" z planes, but you requested tex3DplaneZ="<<tex3DplaneZ);
2173 ilDeleteImages(1, &
id);
2179 const int typeIL = (int)ilGetInteger(IL_IMAGE_TYPE);
2184 case IL_UNSIGNED_BYTE:
2188 case IL_UNSIGNED_SHORT:
2192 case IL_UNSIGNED_INT:
2199 BIASERR(
"unsupported storage type");
2202 unsigned int channels=3;
2205 int formatIL = (int)ilGetInteger(IL_IMAGE_FORMAT);
2228 case IL_LUMINANCE_ALPHA:
2233 BIASERR(
"unsupported format");
2237 const bool interleaved =
true;
2239 const unsigned int w = ilGetInteger(IL_IMAGE_WIDTH);
2240 const unsigned int h = ilGetInteger(IL_IMAGE_HEIGHT);
2251 const int bytePerPixIL = int(ilGetInteger(IL_IMAGE_BYTES_PER_PIXEL));
2252 const int bitPerPixIL = int(ilGetInteger(IL_IMAGE_BITS_PER_PIXEL ));
2257 const int ilSZ = ilGetInteger(IL_IMAGE_SIZE_OF_DATA);
2262 if (ilGetData() == NULL){
2263 BIASERR(
"ilGetData NULL");
2264 ilDeleteImages(1, &
id);
2281 ilDeleteImages(1, &
id);
2283 return BIAS_IO_SUCCESS;
2290 const bool &fileOverwrite,
2291 const bool &allowPadding )
2293 #if defined(BIAS_DEBUG) && defined(ImageIO_DEBUG_IO)
2301 ilGenImages(1, &
id);
2308 ILenum ilFormat=IL_RGB;
2309 ILenum ilType =IL_BYTE;
2312 if (fileOverwrite) {
2313 ilEnable(IL_FILE_OVERWRITE);
2315 ilDisable(IL_FILE_OVERWRITE);
2323 ilType=IL_BYTE;
break;
2325 ilType=IL_UNSIGNED_BYTE;
break;
2327 ilType=IL_SHORT;
break;
2329 ilType=IL_UNSIGNED_SHORT;
break;
2331 ilType=IL_INT;
break;
2333 ilType=IL_UNSIGNED_INT;
break;
2335 ilType=IL_FLOAT;
break;
2337 ilType=IL_DOUBLE;
break;
2339 BIASERR(
"unsupported storage type");
2366 ilFormat=IL_LUMINANCE;
2370 ilFormat=IL_LUMINANCE_ALPHA;
2374 BIASERR(
"unsupported color model/channelcount/ DevIL type");
2385 ILubyte (BytePerPixel),
2392 BIASERR(
"could not set DevIL attributes for saving "<<FileName);
2393 ilDeleteImages(1, &
id);
2399 ilRegisterOrigin(IL_ORIGIN_UPPER_LEFT);
2407 if (err!=IL_NO_ERROR) {
2409 ss<<
"could not set DevIL for saving "<<FileName<<
" ";
2410 #ifdef USE_DEVIL_ILU
2411 ss<<
": "<<iluErrorString(err);
2414 ilDeleteImages(1, &
id);
2418 BIASASSERT(
int(img.
GetDepth())==
int(ilGetInteger(IL_IMAGE_DEPTH)) );
2421 const int ilSZ = ilGetInteger(IL_IMAGE_SIZE_OF_DATA);
2429 if (err!=IL_NO_ERROR) {
2431 ss<<
"could not save to file "<<FileName<<
" ";
2432 #ifdef USE_DEVIL_ILU
2433 ss<<
": "<<iluErrorString(err);
2437 ilDeleteImages(1, &
id);
2442 bool ok = (IL_TRUE==ilSaveImage( (
char*)(FileName.c_str()) ));
2446 if (err!=IL_NO_ERROR || !ok)
2449 ss<<
"could not save to file "<<FileName<<
" ";
2450 #ifdef USE_DEVIL_ILU
2451 ss<<
": "<<iluErrorString(err);
2453 if (err==IL_BAD_DIMENSIONS && allowPadding) {
2459 int resultPadded=ExportDevIL(
2464 if (resultPadded==0)
2467 ss<<endl<<
"Some formats (e.g. DDS) require power of two size (and depth) "<<endl
2468 <<
"Padding from dim "<<w<<
"x"<<h<<
" "
2472 <<
"was required to save "<<FileName;
2477 ilDeleteImages(1, &
id);
2483 ilDeleteImages(1, &
id);
2490 ilDeleteImages(1, &
id);
2492 return BIAS_IO_SUCCESS;
2494 #endif // BIAS_HAVE_DEVIL
2535 BIASERR(
"Unknown FileFormat "<<fmt<<
" Please add switch case");
2549 if (ext==
"mip" || ext ==
"") {
2557 }
else if (ext==
"pgm") {
2559 }
else if (ext==
"pbm") {
2574 }
else if (ext==
"png") {
2582 }
else if (ext==
"exr") {
2603 }
else if ((ext==
"real32") || (ext==
"f32")){
2606 }
else if (ext==
"bmp") {
2608 }
else if (ext==
"matrix") {
2627 is.open(FileName.c_str(), ios::binary);
2629 #if defined(BIAS_DEBUG) && defined(ImageIO_DEBUG_IO)
2630 BIASERR(
"Could not open file "<<FileName);
2636 unsigned int line=0;
2637 getline(is, buf); line++;
2640 const string signatureRAD(
"#?RADIANCE");
2641 if (buf!= signatureRAD )
2643 #if defined(BIAS_DEBUG) && defined(ImageIO_DEBUG_IO)
2644 BIASERR(
"signatureRAD "<<signatureRAD<<
" not found in file "<<FileName);
2650 bool flipY=
false, flipX=
false;
2651 unsigned int width=0, height=0;
2656 getline(is, buf); line++;
2659 if (0==buf.compare(0,1,
"#")) {
2663 if (0==buf.compare(0,6,
"FORMAT")) {
2665 if (0==buf.compare(
"FORMAT=32-bit_rle_rgbe")){
2668 BIASERR(
"Only 32-bit_rle_rgbe FORMAT supported but "<<buf<<
" found. Failed to load.");
2676 getline(is, buf); line++;
2679 if (0==buf.compare(0,1,
"#")) {
2683 if (0==buf.compare(0,2,
"-Y")
2684 || 0==buf.compare(0,2,
"-Y"))
2687 stringstream ss(buf);
2692 }
else if (dummy==
"-Y") {
2695 BIASERR(
"expected +Y or -Y but failed.");
2704 }
else if (dummy==
"-X") {
2707 BIASERR(
"expected +X or -X but failed.");
2715 cout<<FUNCNAME<<
" found "<<width<<
"x"<<height<<
" RADIANCE rle RGBE image. "<<FileName<<endl;
2727 for (y=0; y<height; y++) {
2738 BIASERR(
"unsupported new RADIANCE compression detected in line y="<<y);
2742 }
else if ( (col[0]==0x1)
2746 BIASERR(
"unsupported old RADIANCE run scheme in line y="<<y);
2751 BIASERR(
"sorry, RADAINCE not completely implemented TODO: RLE (un-)compression is missing.");
2790 #if defined(BIAS_DEBUG) && defined(ImageIO_DEBUG_IO)
2795 is.open(FileName.c_str(), ios::binary);
2797 BIASERR(
"Could not open file "<<FileName);
2804 vector<float> header(4, 0);
2807 is.read( (
char*)(&(header[0])), header.size()*
sizeof(float) );
2813 const float fmt=header[0];
2814 if ((1.0f <= fmt) && (fmt<=1.01f)) {
2819 unsigned int width = (
unsigned int)( header[1] );
2820 unsigned int height = (
unsigned int)( header[2] );
2821 unsigned int nchannels = (
unsigned int)( header[3] );
2835 if (!(nchannels<=4))
2845 sizeof(
float)*width*height*nchannels );
2857 Import_BITMAP_winapi(
const std::string& FileName,
2861 #if defined(BIAS_DEBUG) && defined(ImageIO_DEBUG_IO)
2870 LPCSTR szFileName = FileName.c_str();
2874 LoadImage( NULL, szFileName, IMAGE_BITMAP, 0, 0,
2875 LR_LOADFROMFILE | LR_CREATEDIBSECTION | LR_DEFAULTSIZE );
2879 #if defined(BIAS_DEBUG) && defined(ImageIO_DEBUG_IO)
2880 BIASERR(
"could not load "<<FileName );
2887 return BIAS::ImageIO::Import_HBITMAP_winapi(hbm,
2894 Import_HBITMAP_winapi(
const HBITMAP & hbm,
2900 const int nBytesHeader =
2901 GetObject( hbm,
sizeof(BITMAP), &bm );
2902 if (nBytesHeader==0) {
2903 BIASERR(
"could not GetObject");
2910 return BIAS::ImageIO::Import_BITMAP_winapi(bm,
2917 Import_BITMAP_winapi(
const BITMAP & bm,
2922 if( ( bm.bmBitsPixel * bm.bmPlanes ) <= 8 ){
2923 #if defined(BIAS_DEBUG) && defined(ImageIO_DEBUG_IO)
2924 BIASERR(
"Could not load winapi BITMAP because it contains a color table (not implemented)" );
2930 if (bm.bmPlanes != 1){
2931 #if defined(BIAS_DEBUG) && defined(ImageIO_DEBUG_IO)
2932 BIASERR(
"Could not load winapi BITMAP because it contains more than one plane." );
2945 const int nBytes = bm.bmWidthBytes*bm.bmHeight;
2946 memcpy(img.
GetImageData(), (
unsigned char*)bm.bmBits, nBytes );
2956 return EXIT_SUCCESS;
2964 #ifdef BIAS_HAVE_TIFF
2969 const unsigned int rowsPerStripArg,
2970 const unsigned int compressionAlgo,
2971 const string & comment )
2973 #if defined(BIAS_DEBUG) && defined(ImageIO_DEBUG_IO)
2978 TIFF* tif = TIFFOpen(FileName.c_str(),
"w");
2980 #if defined(BIAS_DEBUG) && defined(ImageIO_DEBUG_IO)
2981 BIASERR(
"Could not open image for TIFFLIB for writing:" << FileName);
2985 BIASASSERT(tif!=NULL);
2988 TIFFSetField(tif, TIFFTAG_IMAGEWIDTH, img.
GetWidth() );
2989 TIFFSetField(tif, TIFFTAG_IMAGELENGTH, img.
GetHeight() );
2991 const unsigned short bitspersample =
2993 TIFFSetField(tif, TIFFTAG_BITSPERSAMPLE, bitspersample );
2994 TIFFSetField(tif, TIFFTAG_ORIENTATION, ORIENTATION_TOPLEFT);
2997 TIFFSetField(tif, TIFFTAG_PLANARCONFIG, PLANARCONFIG_CONTIG);
3003 TIFFSetField(tif, TIFFTAG_COMPRESSION, compressionAlgo);
3006 unsigned int rowsPerStrip = rowsPerStripArg;
3007 if (rowsPerStrip <= 0)
3010 BIASERR(
"rowsPerStrip="<<rowsPerStrip<<
" exceed limit. resetting to img height="<<img.
GetHeight());
3014 BIASASSERT(rowsPerStrip >= 0 );
3015 BIASASSERT(rowsPerStrip <= img.
GetHeight() );
3016 TIFFSetField(tif, TIFFTAG_ROWSPERSTRIP, rowsPerStrip);
3023 TIFFSetField(tif, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_MINISBLACK);
break;
3026 TIFFSetField(tif, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_RGB);
break;
3030 BIASERR(
"unhandled nr. of channels.");
3036 TIFFSetField(tif, TIFFTAG_IMAGEDESCRIPTION,
"written Jan Woetzel");
3037 const string cvsVersion =
"CVS $Revision: 2.170 $";
3039 swSS <<
"BIAS::ImageIO "
3040 <<
"BIAS-"<<BIAS_VERSION_MAJOR<<
"."<<BIAS_VERSION_MINOR<<
"."<<BIAS_VERSION_PATCH
3041 <<
" "<<cvsVersion<<
" (Jan Woetzel)";
3042 TIFFSetField(tif, TIFFTAG_SOFTWARE, swSS.str().c_str() );
3073 for (
unsigned int y=0; y<img.
GetHeight(); y+=rowsPerStrip){
3076 BIASASSERT((
int)res==(
int)nBytes);
3082 return EXIT_SUCCESS;
3085 BIASERR(
"catched tifflib exception");
3185 #endif // BIAS_HAVE_TIFF
EColorModel
These are the most often used color models.
Wrapper for fast libjpeg methods.
void SetBitDepth(unsigned bitdepth)
needed by ImageIO
static int ExportDevIL(const std::string &FileName, const ImageBase &img, const bool &fileOverwrite=true, const bool &allowPadding=true)
Save to disk using the DevIL/OpenIL library.
static int ExportOpenEXR(const std::string &FileName, const ImageBase &input)
save an .exr OpenEXR image to disk.
void GetString(std::string &sUUID) const
writes the UUID into a string object
static int ParseRAWwithHeader(const std::string &buf, const std::string &tag, unsigned int &retVal)
helper function for ImportRAWwithHeader Parses buf for tag
static int ImportOpenEXR(const std::string &FileName, ImageBase &result)
load an .exr OpenEXR image from disk.
static int ExportImagePnm_(const std::string &FileName, const ImageBase &img, bool sync=false, const bool &writeMetaData=true)
(16bit) unsigned integer image storage type
static int ImportImage(const std::string &filename, ImageBase &result)
Try to load/import an image from a file using external libs.
unsigned int GetDepth() const
returns the bytes per channel, which is the sizeof(StorageType) Should match GetSizeDepth(GetStorageT...
static int ExportMatrix(const std::string &FileName, const ImageBase &img, const bool verbose)
Export BIAS images to text images.
bool IsEmpty() const
check if ImageData_ points to allocated image buffer or not
void CopyIn_NoInit(void *data)
Take some data and fill it into the Image.
bool IsInterleaved() const
int ReadJPEG(const std::string &filename)
Read JPEG file named filename and store its informations in compressed data field.
(8bit) signed char image storage type
int WriteJPEG(const std::string &filename)
Write previously compressed data to file named filename.
static int ImportImageViff_(std::ifstream &ifs, ImageBase &result)
import a one channel grey float viff image (Khoros image format) for compatibility to old stereo code...
void SetColorModel(EColorModel Model)
unsigned int GetSizeByte() const
returns the nr.
Bayer_RGGB, 1 channel RGB image Bayer tile.
static std::string ExtensionName(const std::string &oldName, const std::string &newExtension)
appends extension to name if extension is not already extension, avoids double extension like "...
double image storage type
static int CreateBiasImageCopy(const IplImage *p_src, BIAS::ImageBase &dest)
helper function to create a copy (!) BIAS image from a master Ipl image Data area is NOT shared but...
static BIAS::ImageIO::TFileFormat GetFileFormat(const std::string &str)
determines the BIAS::ImageIO::TFileFormat for a given filename/ extension Decision based on extension...
static int ImportMagickPP(const std::string &FileName, ImageBase &result, const bool &dummy=false, const bool &readMetaData=true)
Reads an image from disk using the ImageMagick++ library.
unsigned int GetWidth() const
unsigned int GetBitDepth() const
returns the bits per channel Is not necessairily 8*sizeof(StorageType), could be fewer bits...
std::string sdata
the data as given in ascii meta data
static int ImportImagePnm_(std::ifstream &ifs, ImageBase &result, int depth)
static std::string GetCwd()
Return current working directory as string.
const BIAS::UUID & GetUID() const
returns the UUID of the image
static void InitDevIL()
initialize devIL once globally.
static int ImportRAWwithHeader(const std::string &filename, BIAS::ImageBase &img)
Reads a proprietary .RAW format from disk A typical file consists of these blocks: ...
static int WriteUnbuffered(const std::string &FileName, const ImageBase &img)
Write a mip binary image to disk circumventing OS caches as good as possible.
invalid not set image storage type
(16bit) signed integer image storage type
color values, 3 channels, order: blue,green,red
const void * GetImageData() const
int Compress(BIAS::Image< unsigned char > &srcImg, int quality=60)
Start compression for given BIAS::Image into buffer.
static int Read_(const std::string &FileName, ImageBase &img)
Read a proprietary mip binary Image from disk and allocate memory structure.
static int ImportMagickPPAutoconvert(const std::string &FileName, ImageBase &result, const bool &assumeGrey=false, const bool &readMetaData=false)
Reads an image from disk using the ImageMagick++ library.
static int ImportOpenCV(const std::string &filename, ImageBase &image)
Reads an image from disk using the OpenCV library.
static int CreateIplImageShared(const BIAS::ImageBase *p_src, IplImage *&p_dest)
helper function to create a slave ipl image which shares the data area with the master ref...
void ** GetImageDataArray() const
Get an array of pointers to image data.
static int ExportOpenCV(const std::string &filename, const ImageBase &image)
Write an image to disk using the OpenCV library.
Methods for reading and writing OpenEXR files into and from BIAS ImageBase.
static int ConvertST(const BIAS::ImageBase &source, BIAS::ImageBase &dest, ImageBase::EStorageType targetST)
Function to convert the storage type of images e.g.
unsigned int GetChannelCount() const
returns the number of Color channels, e.g.
color values, 3 channels, order: red,green,blue
int Import(const std::string &FileName, ImageBase &result)
TFileFormat
format specifier when writing an image to a file Do NOT change order or associated enum value because...
void SetVerbose(const bool verbose)
Print error messages to standard output or keep quiet?
int Export(const std::string &FileName, const ImageBase &input, const Imf::Compression &compression=Imf::ZIP_COMPRESSION)
unsigned int GetHeight() const
int Decompress(BIAS::Image< unsigned char > &destImg, bool readComment=false)
Start decompression of previously given data (from ReadJPEG() or SetCompressedData()), results will be stored in destination image.
static int ImportLibJPEG(const std::string &filename, BIAS::ImageBase &result, bool readComment=true)
Reads an image from disk using the LibJPEG library encapsulated in ImportImage.
static int Write_(const std::string &FileName, const ImageBase &img, const bool sync=false, const bool forceNewID=true)
Write a proprietary mip binary Image to disk.
static int ExportMagickPP(const std::string &FileName, const ImageBase img, const int &quality=BIAS_DEFAULT_IMAGE_QUALITY, const bool &writeMetaData=false, const bool &forceBinaryPNMformat=true, const bool &losslesJpgMode=false, const bool &writeGZipped=false, const std::string &comment=std::string(""))
Reads an image from disk using the ImageMagick++ library.
void Release()
Releases allocated memory.
static int Save(const std::string &filename, const ImageBase &img, const enum TFileFormat FileFormat=FF_auto, const bool sync=BIAS_DEFAULT_SYNC, const int c_jpeg_quality=BIAS_DEFAULT_IMAGE_QUALITY, const bool forceNewID=BIAS_DEFAULT_FORCENEWID, const bool &writeMetaData=true)
Export image as file using extrnal libs.
enum TAppData tag
The tag defines the type of data, e.g.
static int FilenameExpansion(const std::string &in, std::string &out)
Expand filename, e.g.
static int ImportRADIANCE(const std::string &FileName, ImageBase &result)
import Greg Wards Radiance RGBE image format (.hdr, .rad) A high dynamic range RGBE image contains 24...
static std::string DirectoryAndBasename(const std::string &fullname)
Get path and file base name (without suffix) from given path and filename.
void InvalidateUID()
sets the image's uid to invalid
const StorageType * GetImageData() const
overloaded GetImageData() from ImageBase
void SetUID(const BIAS::UUID &id)
RGBA, 4 channels, order: red,green,blue,alpha.
void Release(const bool reset_storage_type=false)
Free the allocated data structures Hands off: Do !!NOT!! change the default of reset_storage_type: Im...
enum EColorModel GetColorModel() const
static std::string GetExtension(const BIAS::ImageIO::TFileFormat &fmt)
return the default extension for a given FileFormat enum
(32bit) signed integer image storage type
static std::string Extension(const std::string &fullname)
Get file extension (without dot!) from given path and filename.
static std::string Suffix(const std::string &fullname)
Get file suffix (including dot!) from given path and filename.
static int ImportTIFFLIB(const std::string &FileName, ImageBase &img)
read a tiff image from disk using TiffLib directly
static int ImportReal32(const std::string &FileName, ImageBase &result)
Loads proprietary raw floating point 2d image from Mathematica Real32 values Example how to export in...
void Init(unsigned int width, unsigned int height, unsigned int nChannels=1, enum EStorageType storageType=ST_unsignedchar, const bool interleaved=true)
Initialize image size and channels.
static int ImportDevIL(const std::string &FileName, ImageBase &result, const unsigned int &tex3DplaneZ=1)
Reads an image from disk using the DevIL/OpenIL library.
static int Load(const std::string &FileName, ImageBase &img)
first tries a call to Read MIP image and if that fails, tries to Import Image with all other availabl...
int Init(long size=10485760)
Initialize object with standard values and limit shared memory area to given size (in byte...
static unsigned long int MemAlignedBufferSize_
static int BIAS2ImageMagick(const BIAS::ImageBase &input, Magick::Image &dest)
Returns a new, separate ImageMagick Image for use with ImageMagick created from the source BIAS Image...
static void PrintInfoDevIL(std::ostream &os=std::cout)
print info in currently bound DevIL image
invalid (not set) image format
enum EStorageType GetStorageType() const
(8bit) unsigned char image storage type
int UpdateImageDataArrayFromImageData_()
recomputes pointer array returned by GetImageDataArray
static char * MemAlignedBuffer_
static int ImportMatrix(const std::string &FileName, ImageBase &img, const bool verbose)
Import text images to BIAS.
int Flip()
flips the image vertically (row order is inverted) In place function return 0 in case of success...
static int ExportTIFFLIB(const std::string &FileName, const BIAS::ImageBase &img, const unsigned int rowsPerStripArg=0, const unsigned int compressionAlgo=BIAS_COMPRESSION_NONE, const std::string &comment=std::string("BIAS::ImageIO Jan Woetzel"))
Write image to disk using TiffLib directly.
static int ImageMagick2BIAS(Magick::Image &image, BIAS::ImageBase &result)
Returns a new, separate BIAS Image created from the source ImageMagick Image.
static int ExportLibJPEG(const std::string &filename, const BIAS::ImageBase &image, const int quality=100)
Writes an image to disk using the LibJPEG library encapsulated in ExportImage.
interface class for producing/storing Universally Unique IDentifiers
static int WriteRAW_IMA(const std::string &FileName, const ImageBase &img_const)
Write image in binary file format needed by RealEyes.
unsigned long int GetPixelCount() const
returns number of pixels in image
GreyA, 2 channels, grey plus Alpha.
This is the base class for images in BIAS.
static std::string LowerCase(const std::string &input)
Return lower case string of input.
static int ToRGB(const Image< StorageType > &source, Image< StorageType > &dest)
Create a RGB converted copy of source image in this.
int PadToPowerOfTwo(BIAS::ImageBase &dest, const int &padVal=0) const
increase the size of this image to next power of two (e.g.
static UUID GenerateUUID(const bool &consecutively=DEFAULT_UUID_CONSECUTIVELY)
static function which simply produces a uuid and returns
bool IsValid() const
checks whether this uuid is valid(true) or unitialized(false)
static int IP_ToGrey(Image< StorageType > &img)
In place conversion to gray image.
this is a chunk of metadata, also see MetaData
BGRA color values, 4 channels, order: blue,green,red,alpha.
(32bit) unsigned integer image storage type