1 /* $Id: raw2tiff.c,v 1.29 2017-01-14 13:12:33 erouault Exp $
3 * Project: libtiff tools
4 * Purpose: Convert raw byte sequences in TIFF images
5 * Author: Andrey Kiselev, dron@ak4719.spb.edu
7 ******************************************************************************
8 * Copyright (c) 2002, Andrey Kiselev <dron@ak4719.spb.edu>
10 * Permission to use, copy, modify, distribute, and sell this software and
11 * its documentation for any purpose is hereby granted without fee, provided
12 * that (i) the above copyright notices and this permission notice appear in
13 * all copies of the software and related documentation, and (ii) the names of
14 * Sam Leffler and Silicon Graphics may not be used in any advertising or
15 * publicity relating to the software without the specific, prior written
16 * permission of Sam Leffler and Silicon Graphics.
18 * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND,
19 * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY
20 * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.
22 * IN NO EVENT SHALL SAM LEFFLER OR SILICON GRAPHICS BE LIABLE FOR
23 * ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND,
24 * OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
25 * WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF
26 * LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
30 #include "tif_config.h"
36 #include <sys/types.h>
49 # include <sys/types.h>
64 extern int getopt(int, char**, char*);
76 static uint16 compression = (uint16) -1;
77 static int jpegcolormode = JPEGCOLORMODE_RGB;
78 static int quality = 75; /* JPEG quality */
79 static uint16 predictor = 0;
81 static void swapBytesInScanline(void *, uint32, TIFFDataType);
82 static int guessSize(int, TIFFDataType, _TIFF_off_t, uint32, int,
84 static double correlation(void *, void *, uint32, TIFFDataType);
85 static void usage(void);
86 static int processCompressOptions(char*);
89 main(int argc, char* argv[])
91 uint32 width = 0, length = 0, linebytes, bufsize;
92 uint32 nbands = 1; /* number of bands in input image*/
93 _TIFF_off_t hdr_size = 0; /* size of the header to skip */
94 TIFFDataType dtype = TIFF_BYTE;
95 int16 depth = 1; /* bytes per pixel in input image */
96 int swab = 0; /* byte swapping flag */
97 InterleavingType interleaving = 0; /* interleaving type flag */
98 uint32 rowsperstrip = (uint32) -1;
99 uint16 photometric = PHOTOMETRIC_MINISBLACK;
100 uint16 config = PLANARCONFIG_CONTIG;
101 uint16 fillorder = FILLORDER_LSB2MSB;
103 char *outfilename = NULL;
106 uint32 row, col, band;
108 unsigned char *buf = NULL, *buf1 = NULL;
109 #if !HAVE_DECL_OPTARG
114 while ((c = getopt(argc, argv, "c:r:H:w:l:b:d:LMp:si:o:h")) != -1) {
116 case 'c': /* compression scheme */
117 if (!processCompressOptions(optarg))
120 case 'r': /* rows/strip */
121 rowsperstrip = atoi(optarg);
123 case 'H': /* size of input image file header */
124 hdr_size = atoi(optarg);
126 case 'w': /* input image width */
127 width = atoi(optarg);
129 case 'l': /* input image length */
130 length = atoi(optarg);
132 case 'b': /* number of bands in input image */
133 nbands = atoi(optarg);
135 case 'd': /* type of samples in input image */
136 if (strncmp(optarg, "byte", 4) == 0)
138 else if (strncmp(optarg, "short", 5) == 0)
140 else if (strncmp(optarg, "long", 4) == 0)
142 else if (strncmp(optarg, "sbyte", 5) == 0)
144 else if (strncmp(optarg, "sshort", 6) == 0)
146 else if (strncmp(optarg, "slong", 5) == 0)
148 else if (strncmp(optarg, "float", 5) == 0)
150 else if (strncmp(optarg, "double", 6) == 0)
154 depth = TIFFDataWidth(dtype);
156 case 'L': /* input has lsb-to-msb fillorder */
157 fillorder = FILLORDER_LSB2MSB;
159 case 'M': /* input has msb-to-lsb fillorder */
160 fillorder = FILLORDER_MSB2LSB;
162 case 'p': /* photometric interpretation */
163 if (strncmp(optarg, "miniswhite", 10) == 0)
164 photometric = PHOTOMETRIC_MINISWHITE;
165 else if (strncmp(optarg, "minisblack", 10) == 0)
166 photometric = PHOTOMETRIC_MINISBLACK;
167 else if (strncmp(optarg, "rgb", 3) == 0)
168 photometric = PHOTOMETRIC_RGB;
169 else if (strncmp(optarg, "cmyk", 4) == 0)
170 photometric = PHOTOMETRIC_SEPARATED;
171 else if (strncmp(optarg, "ycbcr", 5) == 0)
172 photometric = PHOTOMETRIC_YCBCR;
173 else if (strncmp(optarg, "cielab", 6) == 0)
174 photometric = PHOTOMETRIC_CIELAB;
175 else if (strncmp(optarg, "icclab", 6) == 0)
176 photometric = PHOTOMETRIC_ICCLAB;
177 else if (strncmp(optarg, "itulab", 6) == 0)
178 photometric = PHOTOMETRIC_ITULAB;
180 photometric = PHOTOMETRIC_MINISBLACK;
182 case 's': /* do we need to swap bytes? */
185 case 'i': /* type of interleaving */
186 if (strncmp(optarg, "pixel", 4) == 0)
187 interleaving = PIXEL;
188 else if (strncmp(optarg, "band", 6) == 0)
194 outfilename = optarg;
203 if (argc - optind < 2)
206 fd = open(argv[optind], O_RDONLY|O_BINARY, 0);
208 fprintf(stderr, "%s: %s: Cannot open input file.\n",
209 argv[0], argv[optind]);
213 if (guessSize(fd, dtype, hdr_size, nbands, swab, &width, &length) < 0)
216 if (outfilename == NULL)
217 outfilename = argv[optind+1];
218 out = TIFFOpen(outfilename, "w");
220 fprintf(stderr, "%s: %s: Cannot open file for output.\n",
221 argv[0], outfilename);
224 TIFFSetField(out, TIFFTAG_IMAGEWIDTH, width);
225 TIFFSetField(out, TIFFTAG_IMAGELENGTH, length);
226 TIFFSetField(out, TIFFTAG_ORIENTATION, ORIENTATION_TOPLEFT);
227 TIFFSetField(out, TIFFTAG_SAMPLESPERPIXEL, nbands);
228 TIFFSetField(out, TIFFTAG_BITSPERSAMPLE, depth * 8);
229 TIFFSetField(out, TIFFTAG_FILLORDER, fillorder);
230 TIFFSetField(out, TIFFTAG_PLANARCONFIG, config);
231 TIFFSetField(out, TIFFTAG_PHOTOMETRIC, photometric);
236 TIFFSetField(out, TIFFTAG_SAMPLEFORMAT, SAMPLEFORMAT_UINT);
241 TIFFSetField(out, TIFFTAG_SAMPLEFORMAT, SAMPLEFORMAT_INT);
245 TIFFSetField(out, TIFFTAG_SAMPLEFORMAT, SAMPLEFORMAT_IEEEFP);
248 TIFFSetField(out, TIFFTAG_SAMPLEFORMAT, SAMPLEFORMAT_VOID);
251 if (compression == (uint16) -1)
252 compression = COMPRESSION_PACKBITS;
253 TIFFSetField(out, TIFFTAG_COMPRESSION, compression);
254 switch (compression) {
255 case COMPRESSION_JPEG:
256 if (photometric == PHOTOMETRIC_RGB
257 && jpegcolormode == JPEGCOLORMODE_RGB)
258 photometric = PHOTOMETRIC_YCBCR;
259 TIFFSetField(out, TIFFTAG_JPEGQUALITY, quality);
260 TIFFSetField(out, TIFFTAG_JPEGCOLORMODE, jpegcolormode);
262 case COMPRESSION_LZW:
263 case COMPRESSION_DEFLATE:
265 TIFFSetField(out, TIFFTAG_PREDICTOR, predictor);
268 switch(interleaving) {
269 case BAND: /* band interleaved data */
270 linebytes = width * depth;
271 buf = (unsigned char *)_TIFFmalloc(linebytes);
273 case PIXEL: /* pixel interleaved data */
275 linebytes = width * nbands * depth;
278 bufsize = width * nbands * depth;
279 buf1 = (unsigned char *)_TIFFmalloc(bufsize);
281 rowsperstrip = TIFFDefaultStripSize(out, rowsperstrip);
282 if (rowsperstrip > length) {
283 rowsperstrip = length;
285 TIFFSetField(out, TIFFTAG_ROWSPERSTRIP, rowsperstrip );
287 _TIFF_lseek_f(fd, hdr_size, SEEK_SET); /* Skip the file header */
288 for (row = 0; row < length; row++) {
289 switch(interleaving) {
290 case BAND: /* band interleaved data */
291 for (band = 0; band < nbands; band++) {
292 if (_TIFF_lseek_f(fd,
293 hdr_size + (length*band+row)*linebytes,
294 SEEK_SET) == (_TIFF_off_t)-1) {
296 "%s: %s: scanline %lu: seek error.\n",
297 argv[0], argv[optind],
298 (unsigned long) row);
301 if (read(fd, buf, linebytes) < 0) {
303 "%s: %s: scanline %lu: Read error.\n",
304 argv[0], argv[optind],
305 (unsigned long) row);
308 if (swab) /* Swap bytes if needed */
309 swapBytesInScanline(buf, width, dtype);
310 for (col = 0; col < width; col++)
311 memcpy(buf1 + (col*nbands+band)*depth,
312 buf + col * depth, depth);
315 case PIXEL: /* pixel interleaved data */
317 if (read(fd, buf1, bufsize) < 0) {
319 "%s: %s: scanline %lu: Read error.\n",
320 argv[0], argv[optind],
321 (unsigned long) row);
324 if (swab) /* Swap bytes if needed */
325 swapBytesInScanline(buf1, width, dtype);
329 if (TIFFWriteScanline(out, buf1, row, 0) < 0) {
330 fprintf(stderr, "%s: %s: scanline %lu: Write error.\n",
331 argv[0], outfilename, (unsigned long) row);
344 swapBytesInScanline(void *buf, uint32 width, TIFFDataType dtype)
349 TIFFSwabArrayOfShort((uint16*)buf,
350 (unsigned long)width);
354 TIFFSwabArrayOfLong((uint32*)buf,
355 (unsigned long)width);
357 /* case TIFF_FLOAT: */ /* FIXME */
359 TIFFSwabArrayOfDouble((double*)buf,
360 (unsigned long)width);
368 guessSize(int fd, TIFFDataType dtype, _TIFF_off_t hdr_size, uint32 nbands,
369 int swab, uint32 *width, uint32 *length)
371 const float longt = 40.0; /* maximum possible height/width ratio */
373 _TIFF_stat_s filestat;
374 uint32 w, h, scanlinesize, imagesize;
375 uint32 depth = TIFFDataWidth(dtype);
376 float cor_coef = 0, tmp;
378 if (_TIFF_fstat_f(fd, &filestat) == -1) {
379 fprintf(stderr, "Failed to obtain file size.\n");
383 if (filestat.st_size < hdr_size) {
384 fprintf(stderr, "Too large header size specified.\n");
388 imagesize = (filestat.st_size - hdr_size) / nbands / depth;
390 if (*width != 0 && *length == 0) {
391 fprintf(stderr, "Image height is not specified.\n");
393 *length = imagesize / *width;
395 fprintf(stderr, "Height is guessed as %lu.\n",
396 (unsigned long)*length);
399 } else if (*width == 0 && *length != 0) {
400 fprintf(stderr, "Image width is not specified.\n");
402 *width = imagesize / *length;
404 fprintf(stderr, "Width is guessed as %lu.\n",
405 (unsigned long)*width);
408 } else if (*width == 0 && *length == 0) {
409 unsigned int fail = 0;
410 fprintf(stderr, "Image width and height are not specified.\n");
411 w = (uint32) sqrt(imagesize / longt);
414 fprintf(stderr, "Too small image size.\n");
419 w < sqrt(imagesize * longt);
421 if (imagesize % w == 0) {
422 scanlinesize = w * depth;
423 buf1 = _TIFFmalloc(scanlinesize);
424 buf2 = _TIFFmalloc(scanlinesize);
427 if (_TIFF_lseek_f(fd, hdr_size + (int)(h/2)*scanlinesize,
428 SEEK_SET) == (_TIFF_off_t)-1) {
429 fprintf(stderr, "seek error.\n");
433 if (read(fd, buf1, scanlinesize) !=
434 (long) scanlinesize) {
435 fprintf(stderr, "read error.\n");
439 if (read(fd, buf2, scanlinesize) !=
440 (long) scanlinesize) {
441 fprintf(stderr, "read error.\n");
446 swapBytesInScanline(buf1, w, dtype);
447 swapBytesInScanline(buf2, w, dtype);
449 tmp = (float) fabs(correlation(buf1, buf2,
451 if (tmp > cor_coef) {
453 *width = w, *length = h;
467 "Width is guessed as %lu, height is guessed as %lu.\n",
468 (unsigned long)*width, (unsigned long)*length);
472 if (filestat.st_size<(_TIFF_off_t)(hdr_size+(*width)*(*length)*nbands*depth)) {
473 fprintf(stderr, "Input file too small.\n");
481 /* Calculate correlation coefficient between two numeric vectors */
483 correlation(void *buf1, void *buf2, uint32 n_elem, TIFFDataType dtype)
485 double X, Y, M1 = 0.0, M2 = 0.0, D1 = 0.0, D2 = 0.0, K = 0.0;
491 for (i = 0; i < n_elem; i++) {
492 X = ((unsigned char *)buf1)[i];
493 Y = ((unsigned char *)buf2)[i];
495 D1 += X * X, D2 += Y * Y;
500 for (i = 0; i < n_elem; i++) {
501 X = ((signed char *)buf1)[i];
502 Y = ((signed char *)buf2)[i];
504 D1 += X * X, D2 += Y * Y;
509 for (i = 0; i < n_elem; i++) {
510 X = ((uint16 *)buf1)[i];
511 Y = ((uint16 *)buf2)[i];
513 D1 += X * X, D2 += Y * Y;
518 for (i = 0; i < n_elem; i++) {
519 X = ((int16 *)buf1)[i];
520 Y = ((int16 *)buf2)[i];
522 D1 += X * X, D2 += Y * Y;
527 for (i = 0; i < n_elem; i++) {
528 X = ((uint32 *)buf1)[i];
529 Y = ((uint32 *)buf2)[i];
531 D1 += X * X, D2 += Y * Y;
536 for (i = 0; i < n_elem; i++) {
537 X = ((int32 *)buf1)[i];
538 Y = ((int32 *)buf2)[i];
540 D1 += X * X, D2 += Y * Y;
545 for (i = 0; i < n_elem; i++) {
546 X = ((float *)buf1)[i];
547 Y = ((float *)buf2)[i];
549 D1 += X * X, D2 += Y * Y;
554 for (i = 0; i < n_elem; i++) {
555 X = ((double *)buf1)[i];
556 Y = ((double *)buf2)[i];
558 D1 += X * X, D2 += Y * Y;
566 D1 -= M1 * M1 * n_elem;
567 D2 -= M2 * M2 * n_elem;
568 K = (K - M1 * M2 * n_elem) / sqrt(D1 * D2);
574 processCompressOptions(char* opt)
576 if (strcmp(opt, "none") == 0)
577 compression = COMPRESSION_NONE;
578 else if (strcmp(opt, "packbits") == 0)
579 compression = COMPRESSION_PACKBITS;
580 else if (strncmp(opt, "jpeg", 4) == 0) {
581 char* cp = strchr(opt, ':');
583 compression = COMPRESSION_JPEG;
586 if (isdigit((int)cp[1]))
587 quality = atoi(cp+1);
588 else if (cp[1] == 'r' )
589 jpegcolormode = JPEGCOLORMODE_RAW;
593 cp = strchr(cp+1,':');
595 } else if (strncmp(opt, "lzw", 3) == 0) {
596 char* cp = strchr(opt, ':');
598 predictor = atoi(cp+1);
599 compression = COMPRESSION_LZW;
600 } else if (strncmp(opt, "zip", 3) == 0) {
601 char* cp = strchr(opt, ':');
603 predictor = atoi(cp+1);
604 compression = COMPRESSION_DEFLATE;
610 static char* stuff[] = {
611 "raw2tiff --- tool for converting raw byte sequences in TIFF images",
612 "usage: raw2tiff [options] input.raw output.tif",
613 "where options are:",
614 " -L input data has LSB2MSB bit order (default)",
615 " -M input data has MSB2LSB bit order",
616 " -r # make each strip have no more than # rows",
617 " -H # size of input image file header in bytes (0 by default)",
618 " -w # width of input image in pixels",
619 " -l # length of input image in lines",
620 " -b # number of bands in input image (1 by default)",
622 " -d data_type type of samples in input image",
623 "where data_type may be:",
624 " byte 8-bit unsigned integer (default)",
625 " short 16-bit unsigned integer",
626 " long 32-bit unsigned integer",
627 " sbyte 8-bit signed integer",
628 " sshort 16-bit signed integer",
629 " slong 32-bit signed integer",
630 " float 32-bit IEEE floating point",
631 " double 64-bit IEEE floating point",
633 " -p photo photometric interpretation (color space) of the input image",
634 "where photo may be:",
635 " miniswhite white color represented with 0 value",
636 " minisblack black color represented with 0 value (default)",
637 " rgb image has RGB color model",
638 " cmyk image has CMYK (separated) color model",
639 " ycbcr image has YCbCr color model",
640 " cielab image has CIE L*a*b color model",
641 " icclab image has ICC L*a*b color model",
642 " itulab image has ITU L*a*b color model",
644 " -s swap bytes fetched from input file",
646 " -i config type of samples interleaving in input image",
647 "where config may be:",
648 " pixel pixel interleaved data (default)",
649 " band band interleaved data",
651 " -c lzw[:opts] compress output with Lempel-Ziv & Welch encoding",
652 " -c zip[:opts] compress output with deflate encoding",
653 " -c jpeg[:opts] compress output with JPEG encoding",
654 " -c packbits compress output with packbits encoding",
655 " -c none use no compression algorithm on output",
658 " # set compression quality level (0-100, default 75)",
659 " r output color image as RGB rather than YCbCr",
660 "For example, -c jpeg:r:50 to get JPEG-encoded RGB data with 50% comp. quality",
662 "LZW and deflate options:",
663 " # set predictor value",
664 "For example, -c lzw:2 to get LZW-encoded data with horizontal differencing",
665 " -o out.tif write output to out.tif",
666 " -h this help message",
677 fprintf(stderr, "%s\n\n", TIFFGetVersion());
678 for (i = 0; stuff[i] != NULL; i++)
679 fprintf(stderr, "%s\n", stuff[i]);
683 /* vim: set ts=8 sts=8 sw=8 noet: */