]> git.saurik.com Git - wxWidgets.git/blob - src/tiff/tools/raw2tiff.c
Define __VISUALC__ for ICC under Windows again.
[wxWidgets.git] / src / tiff / tools / raw2tiff.c
1 *
2 * Project: libtiff tools
3 * Purpose: Convert raw byte sequences in TIFF images
4 * Author: Andrey Kiselev, dron@ak4719.spb.edu
5 *
6 ******************************************************************************
7 * Copyright (c) 2002, Andrey Kiselev <dron@ak4719.spb.edu>
8 *
9 * Permission to use, copy, modify, distribute, and sell this software and
10 * its documentation for any purpose is hereby granted without fee, provided
11 * that (i) the above copyright notices and this permission notice appear in
12 * all copies of the software and related documentation, and (ii) the names of
13 * Sam Leffler and Silicon Graphics may not be used in any advertising or
14 * publicity relating to the software without the specific, prior written
15 * permission of Sam Leffler and Silicon Graphics.
16 *
17 * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND,
18 * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY
19 * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.
20 *
21 * IN NO EVENT SHALL SAM LEFFLER OR SILICON GRAPHICS BE LIABLE FOR
22 * ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND,
23 * OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
24 * WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF
25 * LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
26 * OF THIS SOFTWARE.
27 */
28
29 #include "tif_config.h"
30
31 #include <stdio.h>
32 #include <stdlib.h>
33 #include <string.h>
34 #include <sys/stat.h>
35 #include <sys/types.h>
36 #include <math.h>
37 #include <ctype.h>
38
39 #ifdef HAVE_UNISTD_H
40 # include <unistd.h>
41 #endif
42
43 #if HAVE_FCNTL_H
44 # include <fcntl.h>
45 #endif
46
47 #if HAVE_SYS_TYPES_H
48 # include <sys/types.h>
49 #endif
50
51 #if HAVE_IO_H
52 # include <io.h>
53 #endif
54
55 #ifdef NEED_LIBPORT
56 # include "libport.h"
57 #endif
58
59 #include "tiffio.h"
60
61 #ifndef HAVE_GETOPT
62 extern int getopt(int, char**, char*);
63 #endif
64
65 #ifndef O_BINARY
66 # define O_BINARY 0
67 #endif
68
69 typedef enum {
70 PIXEL,
71 BAND
72 } InterleavingType;
73
74 static uint16 compression = (uint16) -1;
75 static int jpegcolormode = JPEGCOLORMODE_RGB;
76 static int quality = 75; /* JPEG quality */
77 static uint16 predictor = 0;
78
79 static void swapBytesInScanline(void *, uint32, TIFFDataType);
80 static int guessSize(int, TIFFDataType, off_t, uint32, int,
81 uint32 *, uint32 *);
82 static double correlation(void *, void *, uint32, TIFFDataType);
83 static void usage(void);
84 static int processCompressOptions(char*);
85
86 int
87 main(int argc, char* argv[])
88 {
89 uint32 width = 0, length = 0, linebytes, bufsize;
90 uint32 nbands = 1; /* number of bands in input image*/
91 off_t hdr_size = 0; /* size of the header to skip */
92 TIFFDataType dtype = TIFF_BYTE;
93 int16 depth = 1; /* bytes per pixel in input image */
94 int swab = 0; /* byte swapping flag */
95 InterleavingType interleaving = 0; /* interleaving type flag */
96 uint32 rowsperstrip = (uint32) -1;
97 uint16 photometric = PHOTOMETRIC_MINISBLACK;
98 uint16 config = PLANARCONFIG_CONTIG;
99 uint16 fillorder = FILLORDER_LSB2MSB;
100 int fd;
101 char *outfilename = NULL;
102 TIFF *out;
103
104 uint32 row, col, band;
105 int c;
106 unsigned char *buf = NULL, *buf1 = NULL;
107 extern int optind;
108 extern char* optarg;
109
110 while ((c = getopt(argc, argv, "c:r:H:w:l:b:d:LMp:si:o:h")) != -1) {
111 switch (c) {
112 case 'c': /* compression scheme */
113 if (!processCompressOptions(optarg))
114 usage();
115 break;
116 case 'r': /* rows/strip */
117 rowsperstrip = atoi(optarg);
118 break;
119 case 'H': /* size of input image file header */
120 hdr_size = atoi(optarg);
121 break;
122 case 'w': /* input image width */
123 width = atoi(optarg);
124 break;
125 case 'l': /* input image length */
126 length = atoi(optarg);
127 break;
128 case 'b': /* number of bands in input image */
129 nbands = atoi(optarg);
130 break;
131 case 'd': /* type of samples in input image */
132 if (strncmp(optarg, "byte", 4) == 0)
133 dtype = TIFF_BYTE;
134 else if (strncmp(optarg, "short", 5) == 0)
135 dtype = TIFF_SHORT;
136 else if (strncmp(optarg, "long", 4) == 0)
137 dtype = TIFF_LONG;
138 else if (strncmp(optarg, "sbyte", 5) == 0)
139 dtype = TIFF_SBYTE;
140 else if (strncmp(optarg, "sshort", 6) == 0)
141 dtype = TIFF_SSHORT;
142 else if (strncmp(optarg, "slong", 5) == 0)
143 dtype = TIFF_SLONG;
144 else if (strncmp(optarg, "float", 5) == 0)
145 dtype = TIFF_FLOAT;
146 else if (strncmp(optarg, "double", 6) == 0)
147 dtype = TIFF_DOUBLE;
148 else
149 dtype = TIFF_BYTE;
150 depth = TIFFDataWidth(dtype);
151 break;
152 case 'L': /* input has lsb-to-msb fillorder */
153 fillorder = FILLORDER_LSB2MSB;
154 break;
155 case 'M': /* input has msb-to-lsb fillorder */
156 fillorder = FILLORDER_MSB2LSB;
157 break;
158 case 'p': /* photometric interpretation */
159 if (strncmp(optarg, "miniswhite", 10) == 0)
160 photometric = PHOTOMETRIC_MINISWHITE;
161 else if (strncmp(optarg, "minisblack", 10) == 0)
162 photometric = PHOTOMETRIC_MINISBLACK;
163 else if (strncmp(optarg, "rgb", 3) == 0)
164 photometric = PHOTOMETRIC_RGB;
165 else if (strncmp(optarg, "cmyk", 4) == 0)
166 photometric = PHOTOMETRIC_SEPARATED;
167 else if (strncmp(optarg, "ycbcr", 5) == 0)
168 photometric = PHOTOMETRIC_YCBCR;
169 else if (strncmp(optarg, "cielab", 6) == 0)
170 photometric = PHOTOMETRIC_CIELAB;
171 else if (strncmp(optarg, "icclab", 6) == 0)
172 photometric = PHOTOMETRIC_ICCLAB;
173 else if (strncmp(optarg, "itulab", 6) == 0)
174 photometric = PHOTOMETRIC_ITULAB;
175 else
176 photometric = PHOTOMETRIC_MINISBLACK;
177 break;
178 case 's': /* do we need to swap bytes? */
179 swab = 1;
180 break;
181 case 'i': /* type of interleaving */
182 if (strncmp(optarg, "pixel", 4) == 0)
183 interleaving = PIXEL;
184 else if (strncmp(optarg, "band", 6) == 0)
185 interleaving = BAND;
186 else
187 interleaving = 0;
188 break;
189 case 'o':
190 outfilename = optarg;
191 break;
192 case 'h':
193 usage();
194 default:
195 break;
196 }
197 }
198
199 if (argc - optind < 2)
200 usage();
201
202 fd = open(argv[optind], O_RDONLY|O_BINARY, 0);
203 if (fd < 0) {
204 fprintf(stderr, "%s: %s: Cannot open input file.\n",
205 argv[0], argv[optind]);
206 return (-1);
207 }
208
209 if (guessSize(fd, dtype, hdr_size, nbands, swab, &width, &length) < 0)
210 return 1;
211
212 if (outfilename == NULL)
213 outfilename = argv[optind+1];
214 out = TIFFOpen(outfilename, "w");
215 if (out == NULL) {
216 fprintf(stderr, "%s: %s: Cannot open file for output.\n",
217 argv[0], outfilename);
218 return (-1);
219 }
220 TIFFSetField(out, TIFFTAG_IMAGEWIDTH, width);
221 TIFFSetField(out, TIFFTAG_IMAGELENGTH, length);
222 TIFFSetField(out, TIFFTAG_ORIENTATION, ORIENTATION_TOPLEFT);
223 TIFFSetField(out, TIFFTAG_SAMPLESPERPIXEL, nbands);
224 TIFFSetField(out, TIFFTAG_BITSPERSAMPLE, depth * 8);
225 TIFFSetField(out, TIFFTAG_FILLORDER, fillorder);
226 TIFFSetField(out, TIFFTAG_PLANARCONFIG, config);
227 TIFFSetField(out, TIFFTAG_PHOTOMETRIC, photometric);
228 switch (dtype) {
229 case TIFF_BYTE:
230 case TIFF_SHORT:
231 case TIFF_LONG:
232 TIFFSetField(out, TIFFTAG_SAMPLEFORMAT, SAMPLEFORMAT_UINT);
233 break;
234 case TIFF_SBYTE:
235 case TIFF_SSHORT:
236 case TIFF_SLONG:
237 TIFFSetField(out, TIFFTAG_SAMPLEFORMAT, SAMPLEFORMAT_INT);
238 break;
239 case TIFF_FLOAT:
240 case TIFF_DOUBLE:
241 TIFFSetField(out, TIFFTAG_SAMPLEFORMAT, SAMPLEFORMAT_IEEEFP);
242 break;
243 default:
244 TIFFSetField(out, TIFFTAG_SAMPLEFORMAT, SAMPLEFORMAT_VOID);
245 break;
246 }
247 if (compression == (uint16) -1)
248 compression = COMPRESSION_PACKBITS;
249 TIFFSetField(out, TIFFTAG_COMPRESSION, compression);
250 switch (compression) {
251 case COMPRESSION_JPEG:
252 if (photometric == PHOTOMETRIC_RGB
253 && jpegcolormode == JPEGCOLORMODE_RGB)
254 photometric = PHOTOMETRIC_YCBCR;
255 TIFFSetField(out, TIFFTAG_JPEGQUALITY, quality);
256 TIFFSetField(out, TIFFTAG_JPEGCOLORMODE, jpegcolormode);
257 break;
258 case COMPRESSION_LZW:
259 case COMPRESSION_DEFLATE:
260 if (predictor != 0)
261 TIFFSetField(out, TIFFTAG_PREDICTOR, predictor);
262 break;
263 }
264 switch(interleaving) {
265 case BAND: /* band interleaved data */
266 linebytes = width * depth;
267 buf = (unsigned char *)_TIFFmalloc(linebytes);
268 break;
269 case PIXEL: /* pixel interleaved data */
270 default:
271 linebytes = width * nbands * depth;
272 break;
273 }
274 bufsize = width * nbands * depth;
275 buf1 = (unsigned char *)_TIFFmalloc(bufsize);
276
277 rowsperstrip = TIFFDefaultStripSize(out, rowsperstrip);
278 if (rowsperstrip > length) {
279 rowsperstrip = length;
280 }
281 TIFFSetField(out, TIFFTAG_ROWSPERSTRIP, rowsperstrip );
282
283 lseek(fd, hdr_size, SEEK_SET); /* Skip the file header */
284 for (row = 0; row < length; row++) {
285 switch(interleaving) {
286 case BAND: /* band interleaved data */
287 for (band = 0; band < nbands; band++) {
288 lseek(fd,
289 hdr_size + (length*band+row)*linebytes,
290 SEEK_SET);
291 if (read(fd, buf, linebytes) < 0) {
292 fprintf(stderr,
293 "%s: %s: scanline %lu: Read error.\n",
294 argv[0], argv[optind],
295 (unsigned long) row);
296 break;
297 }
298 if (swab) /* Swap bytes if needed */
299 swapBytesInScanline(buf, width, dtype);
300 for (col = 0; col < width; col++)
301 memcpy(buf1 + (col*nbands+band)*depth,
302 buf + col * depth, depth);
303 }
304 break;
305 case PIXEL: /* pixel interleaved data */
306 default:
307 if (read(fd, buf1, bufsize) < 0) {
308 fprintf(stderr,
309 "%s: %s: scanline %lu: Read error.\n",
310 argv[0], argv[optind],
311 (unsigned long) row);
312 break;
313 }
314 if (swab) /* Swap bytes if needed */
315 swapBytesInScanline(buf1, width, dtype);
316 break;
317 }
318
319 if (TIFFWriteScanline(out, buf1, row, 0) < 0) {
320 fprintf(stderr, "%s: %s: scanline %lu: Write error.\n",
321 argv[0], outfilename, (unsigned long) row);
322 break;
323 }
324 }
325 if (buf)
326 _TIFFfree(buf);
327 if (buf1)
328 _TIFFfree(buf1);
329 TIFFClose(out);
330 return (0);
331 }
332
333 static void
334 swapBytesInScanline(void *buf, uint32 width, TIFFDataType dtype)
335 {
336 switch (dtype) {
337 case TIFF_SHORT:
338 case TIFF_SSHORT:
339 TIFFSwabArrayOfShort((uint16*)buf,
340 (unsigned long)width);
341 break;
342 case TIFF_LONG:
343 case TIFF_SLONG:
344 TIFFSwabArrayOfLong((uint32*)buf,
345 (unsigned long)width);
346 break;
347 /* case TIFF_FLOAT: */ /* FIXME */
348 case TIFF_DOUBLE:
349 TIFFSwabArrayOfDouble((double*)buf,
350 (unsigned long)width);
351 break;
352 default:
353 break;
354 }
355 }
356
357 static int
358 guessSize(int fd, TIFFDataType dtype, off_t hdr_size, uint32 nbands,
359 int swab, uint32 *width, uint32 *length)
360 {
361 const float longt = 40.0; /* maximum possible height/width ratio */
362 char *buf1, *buf2;
363 struct stat filestat;
364 uint32 w, h, scanlinesize, imagesize;
365 uint32 depth = TIFFDataWidth(dtype);
366 float cor_coef = 0, tmp;
367
368 fstat(fd, &filestat);
369
370 if (filestat.st_size < hdr_size) {
371 fprintf(stderr, "Too large header size specified.\n");
372 return -1;
373 }
374
375 imagesize = (filestat.st_size - hdr_size) / nbands / depth;
376
377 if (*width != 0 && *length == 0) {
378 fprintf(stderr, "Image height is not specified.\n");
379
380 *length = imagesize / *width;
381
382 fprintf(stderr, "Height is guessed as %lu.\n",
383 (unsigned long)*length);
384
385 return 1;
386 } else if (*width == 0 && *length != 0) {
387 fprintf(stderr, "Image width is not specified.\n");
388
389 *width = imagesize / *length;
390
391 fprintf(stderr, "Width is guessed as %lu.\n",
392 (unsigned long)*width);
393
394 return 1;
395 } else if (*width == 0 && *length == 0) {
396 fprintf(stderr, "Image width and height are not specified.\n");
397
398 for (w = (uint32) sqrt(imagesize / longt);
399 w < sqrt(imagesize * longt);
400 w++) {
401 if (imagesize % w == 0) {
402 scanlinesize = w * depth;
403 buf1 = _TIFFmalloc(scanlinesize);
404 buf2 = _TIFFmalloc(scanlinesize);
405 h = imagesize / w;
406 lseek(fd, hdr_size + (int)(h/2)*scanlinesize,
407 SEEK_SET);
408 read(fd, buf1, scanlinesize);
409 read(fd, buf2, scanlinesize);
410 if (swab) {
411 swapBytesInScanline(buf1, w, dtype);
412 swapBytesInScanline(buf2, w, dtype);
413 }
414 tmp = (float) fabs(correlation(buf1, buf2,
415 w, dtype));
416 if (tmp > cor_coef) {
417 cor_coef = tmp;
418 *width = w, *length = h;
419 }
420
421 _TIFFfree(buf1);
422 _TIFFfree(buf2);
423 }
424 }
425
426 fprintf(stderr,
427 "Width is guessed as %lu, height is guessed as %lu.\n",
428 (unsigned long)*width, (unsigned long)*length);
429
430 return 1;
431 } else {
432 if (filestat.st_size<(off_t)(hdr_size+(*width)*(*length)*nbands*depth)) {
433 fprintf(stderr, "Input file too small.\n");
434 return -1;
435 }
436 }
437
438 return 1;
439 }
440
441 /* Calculate correlation coefficient between two numeric vectors */
442 static double
443 correlation(void *buf1, void *buf2, uint32 n_elem, TIFFDataType dtype)
444 {
445 double X, Y, M1 = 0.0, M2 = 0.0, D1 = 0.0, D2 = 0.0, K = 0.0;
446 uint32 i;
447
448 switch (dtype) {
449 case TIFF_BYTE:
450 default:
451 for (i = 0; i < n_elem; i++) {
452 X = ((unsigned char *)buf1)[i];
453 Y = ((unsigned char *)buf2)[i];
454 M1 += X, M2 += Y;
455 D1 += X * X, D2 += Y * Y;
456 K += X * Y;
457 }
458 break;
459 case TIFF_SBYTE:
460 for (i = 0; i < n_elem; i++) {
461 X = ((signed char *)buf1)[i];
462 Y = ((signed char *)buf2)[i];
463 M1 += X, M2 += Y;
464 D1 += X * X, D2 += Y * Y;
465 K += X * Y;
466 }
467 break;
468 case TIFF_SHORT:
469 for (i = 0; i < n_elem; i++) {
470 X = ((uint16 *)buf1)[i];
471 Y = ((uint16 *)buf2)[i];
472 M1 += X, M2 += Y;
473 D1 += X * X, D2 += Y * Y;
474 K += X * Y;
475 }
476 break;
477 case TIFF_SSHORT:
478 for (i = 0; i < n_elem; i++) {
479 X = ((int16 *)buf1)[i];
480 Y = ((int16 *)buf2)[i];
481 M1 += X, M2 += Y;
482 D1 += X * X, D2 += Y * Y;
483 K += X * Y;
484 }
485 break;
486 case TIFF_LONG:
487 for (i = 0; i < n_elem; i++) {
488 X = ((uint32 *)buf1)[i];
489 Y = ((uint32 *)buf2)[i];
490 M1 += X, M2 += Y;
491 D1 += X * X, D2 += Y * Y;
492 K += X * Y;
493 }
494 break;
495 case TIFF_SLONG:
496 for (i = 0; i < n_elem; i++) {
497 X = ((int32 *)buf1)[i];
498 Y = ((int32 *)buf2)[i];
499 M1 += X, M2 += Y;
500 D1 += X * X, D2 += Y * Y;
501 K += X * Y;
502 }
503 break;
504 case TIFF_FLOAT:
505 for (i = 0; i < n_elem; i++) {
506 X = ((float *)buf1)[i];
507 Y = ((float *)buf2)[i];
508 M1 += X, M2 += Y;
509 D1 += X * X, D2 += Y * Y;
510 K += X * Y;
511 }
512 break;
513 case TIFF_DOUBLE:
514 for (i = 0; i < n_elem; i++) {
515 X = ((double *)buf1)[i];
516 Y = ((double *)buf2)[i];
517 M1 += X, M2 += Y;
518 D1 += X * X, D2 += Y * Y;
519 K += X * Y;
520 }
521 break;
522 }
523
524 M1 /= n_elem;
525 M2 /= n_elem;
526 D1 -= M1 * M1 * n_elem;
527 D2 -= M2 * M2 * n_elem;
528 K = (K - M1 * M2 * n_elem) / sqrt(D1 * D2);
529
530 return K;
531 }
532
533 static int
534 processCompressOptions(char* opt)
535 {
536 if (strcmp(opt, "none") == 0)
537 compression = COMPRESSION_NONE;
538 else if (strcmp(opt, "packbits") == 0)
539 compression = COMPRESSION_PACKBITS;
540 else if (strncmp(opt, "jpeg", 4) == 0) {
541 char* cp = strchr(opt, ':');
542
543 compression = COMPRESSION_JPEG;
544 while( cp )
545 {
546 if (isdigit((int)cp[1]))
547 quality = atoi(cp+1);
548 else if (cp[1] == 'r' )
549 jpegcolormode = JPEGCOLORMODE_RAW;
550 else
551 usage();
552
553 cp = strchr(cp+1,':');
554 }
555 } else if (strncmp(opt, "lzw", 3) == 0) {
556 char* cp = strchr(opt, ':');
557 if (cp)
558 predictor = atoi(cp+1);
559 compression = COMPRESSION_LZW;
560 } else if (strncmp(opt, "zip", 3) == 0) {
561 char* cp = strchr(opt, ':');
562 if (cp)
563 predictor = atoi(cp+1);
564 compression = COMPRESSION_DEFLATE;
565 } else
566 return (0);
567 return (1);
568 }
569
570 static char* stuff[] = {
571 "raw2tiff --- tool for converting raw byte sequences in TIFF images",
572 "usage: raw2tiff [options] input.raw output.tif",
573 "where options are:",
574 " -L input data has LSB2MSB bit order (default)",
575 " -M input data has MSB2LSB bit order",
576 " -r # make each strip have no more than # rows",
577 " -H # size of input image file header in bytes (0 by default)",
578 " -w # width of input image in pixels",
579 " -l # length of input image in lines",
580 " -b # number of bands in input image (1 by default)",
581 "",
582 " -d data_type type of samples in input image",
583 "where data_type may be:",
584 " byte 8-bit unsigned integer (default)",
585 " short 16-bit unsigned integer",
586 " long 32-bit unsigned integer",
587 " sbyte 8-bit signed integer",
588 " sshort 16-bit signed integer",
589 " slong 32-bit signed integer",
590 " float 32-bit IEEE floating point",
591 " double 64-bit IEEE floating point",
592 "",
593 " -p photo photometric interpretation (color space) of the input image",
594 "where photo may be:",
595 " miniswhite white color represented with 0 value",
596 " minisblack black color represented with 0 value (default)",
597 " rgb image has RGB color model",
598 " cmyk image has CMYK (separated) color model",
599 " ycbcr image has YCbCr color model",
600 " cielab image has CIE L*a*b color model",
601 " icclab image has ICC L*a*b color model",
602 " itulab image has ITU L*a*b color model",
603 "",
604 " -s swap bytes fetched from input file",
605 "",
606 " -i config type of samples interleaving in input image",
607 "where config may be:",
608 " pixel pixel interleaved data (default)",
609 " band band interleaved data",
610 "",
611 " -c lzw[:opts] compress output with Lempel-Ziv & Welch encoding",
612 " -c zip[:opts] compress output with deflate encoding",
613 " -c jpeg[:opts] compress output with JPEG encoding",
614 " -c packbits compress output with packbits encoding",
615 " -c none use no compression algorithm on output",
616 "",
617 "JPEG options:",
618 " # set compression quality level (0-100, default 75)",
619 " r output color image as RGB rather than YCbCr",
620 "For example, -c jpeg:r:50 to get JPEG-encoded RGB data with 50% comp. quality",
621 "",
622 "LZW and deflate options:",
623 " # set predictor value",
624 "For example, -c lzw:2 to get LZW-encoded data with horizontal differencing",
625 " -o out.tif write output to out.tif",
626 " -h this help message",
627 NULL
628 };
629
630 static void
631 usage(void)
632 {
633 char buf[BUFSIZ];
634 int i;
635
636 setbuf(stderr, buf);
637 fprintf(stderr, "%s\n\n", TIFFGetVersion());
638 for (i = 0; stuff[i] != NULL; i++)
639 fprintf(stderr, "%s\n", stuff[i]);
640 exit(-1);
641 }
642
643 /* vim: set ts=8 sts=8 sw=8 noet: */
644 /*
645 * Local Variables:
646 * mode: c
647 * c-basic-offset: 8
648 * fill-column: 78
649 * End:
650 */