#include #include #include #include #include #include "matlab.h" void error(const char * str) { printf("Error: %s\n", str); exit(1); } // Read a TIFF directory (contiguous floating-point samples, 3 channels) // into an array. Then call writeFile to write the data out void readDirectory(TIFF * tiff, const char * name, const char * input, const char * varname) { uint32 width, height; uint16 config, samples, format; float * bigArray; float * pos; tstrip_t strip; if (!TIFFGetField(tiff, TIFFTAG_IMAGEWIDTH, &width)) exit(1); if (!TIFFGetField(tiff, TIFFTAG_IMAGELENGTH, &height)) exit(1); if (!TIFFGetField(tiff, TIFFTAG_PLANARCONFIG, &config)) exit(1); if (!TIFFGetField(tiff, TIFFTAG_SAMPLESPERPIXEL, &samples)) exit(1); if (!TIFFGetField(tiff, TIFFTAG_SAMPLEFORMAT, &format)) exit(1); bigArray = _TIFFmalloc(width * height * 3 * sizeof(float)); if (bigArray == NULL) error("malloc failed"); pos = bigArray; if (config != PLANARCONFIG_CONTIG || samples != 3) error("image is stored strangely"); if (format != 3) error("samples are not floating-point"); for (strip = 0; strip < TIFFNumberOfStrips(tiff); strip++) { // All samples for a pixel are grouped together (PLANARCONFIG_CONTIG) TIFFReadEncodedStrip(tiff, strip, pos, (tsize_t)-1); pos += TIFFStripSize(tiff) / sizeof(float); } writeFile(bigArray, width, height, name, input, varname); _TIFFfree(bigArray); } int main(int argc, char ** argv) { TIFF * tiff; char * input; char * name; char * idx; if (argc != 3) error("syntax is tiff2mat file.tif arrayname"); tiff = TIFFOpen(argv[1], "r"); if (tiff == NULL) return 1; input = strdup(argv[1]); name = malloc(strlen(argv[1]) + 20); if (name == NULL || input == NULL) error("out of memory"); idx = input + strlen(input); // Get rid of the file extension while (idx != input) { if (*idx == '.') { *idx = 0; break; } idx--; } if (TIFFLastDirectory(tiff)) { sprintf(name, "%s.mat", input); readDirectory(tiff, name, argv[1], argv[2]); } else do { sprintf(name, "%s%d.mat", input, TIFFCurrentDirectory(tiff) + 1); readDirectory(tiff, name, argv[1], argv[2]); } while (TIFFReadDirectory(tiff)); TIFFClose(tiff); return 0; }