1 /* $Id: raw2tiff.c,v 1.9 2003/11/22 08:42:06 dron Exp $
2  *
3  * Project:  libtiff tools
4  * Purpose:  Convert raw byte sequences in TIFF images
5  * Author:   Andrey Kiselev, dron@remotesensing.org
6  *
7  ******************************************************************************
8  * Copyright (c) 2002, Andrey Kiselev <dron@remotesensing.org>
9  *
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.
17  *
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.
21  *
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
27  * OF THIS SOFTWARE.
28  */
29 
30 #include <stdio.h>
31 #include <stdlib.h>
32 #include <string.h>
33 #include <sys/stat.h>
34 #include <math.h>
35 #include <ctype.h>
36 
37 #include "tiffio.h"
38 
39 typedef enum {
40 	PIXEL,
41 	BAND
42 } InterleavingType;
43 
44 static	uint16 compression = (uint16) -1;
45 static	int jpegcolormode = JPEGCOLORMODE_RGB;
46 static	int quality = 75;		/* JPEG quality */
47 static	uint16 predictor = 0;
48 
49 static void swapBytesInScanline(void *, uint32, TIFFDataType);
50 static int guessSize(FILE *, TIFFDataType, uint32, int, int,
51 		     uint32 *, uint32 *);
52 static double correlation(void *, void *, uint32, TIFFDataType);
53 static void usage(void);
54 static	int processCompressOptions(char*);
55 
56 int
main(int argc,char * argv[])57 main(int argc, char* argv[])
58 {
59 	uint32	width = 0, length = 0, hdr_size = 0, linebytes, bufsize;
60 	int	nbands = 1;		    /* number of bands in input image*/
61 	TIFFDataType dtype = TIFF_BYTE;
62 	int	depth = 1;		    /* bytes per pixel in input image */
63 	int	swab = 0;		    /* byte swapping flag */
64 	InterleavingType interleaving = 0;  /* interleaving type flag */
65 	uint32 rowsperstrip = (uint32) -1;
66 	uint16	photometric = PHOTOMETRIC_MINISBLACK;
67 	uint16	config = PLANARCONFIG_CONTIG;
68 	uint16	fillorder = FILLORDER_LSB2MSB;
69 	FILE	*in;
70 	char	*outfilename = NULL;
71 	TIFF	*out;
72 
73 	uint32 row, col, band;
74 	int	c;
75 	unsigned char *buf = NULL, *buf1 = NULL;
76 	extern int optind;
77 	extern char* optarg;
78 
79 
80 	while ((c = getopt(argc, argv, "c:r:H:w:l:b:d:LMp:si:o:h")) != -1)
81 		switch (c) {
82 		case 'c':		/* compression scheme */
83 			if (!processCompressOptions(optarg))
84 				usage();
85 			break;
86 		case 'r':		/* rows/strip */
87 			rowsperstrip = atoi(optarg);
88 			break;
89 		case 'H':		/* size of input image file header */
90 			hdr_size = atoi(optarg);
91 			break;
92 		case 'w':		/* input image width */
93 			width = atoi(optarg);
94 			break;
95 		case 'l':		/* input image length */
96 			length = atoi(optarg);
97 			break;
98 		case 'b':		/* number of bands in input image */
99 			nbands = atoi(optarg);
100 			break;
101 		case 'd':		/* type of samples in input image */
102 			if (strncmp(optarg, "byte", 4) == 0)
103 				dtype = TIFF_BYTE;
104 			else if (strncmp(optarg, "short", 5) == 0)
105 				dtype = TIFF_SHORT;
106 			else if  (strncmp(optarg, "long", 4) == 0)
107 				dtype = TIFF_LONG;
108 			else if  (strncmp(optarg, "sbyte", 5) == 0)
109 				dtype = TIFF_SBYTE;
110 			else if  (strncmp(optarg, "sshort", 6) == 0)
111 				dtype = TIFF_SSHORT;
112 			else if  (strncmp(optarg, "slong", 5) == 0)
113 				dtype = TIFF_SLONG;
114 			else if  (strncmp(optarg, "float", 5) == 0)
115 				dtype = TIFF_FLOAT;
116 			else if  (strncmp(optarg, "double", 6) == 0)
117 				dtype = TIFF_DOUBLE;
118 			else
119 				dtype = TIFF_BYTE;
120 			depth = TIFFDataWidth(dtype);
121 			break;
122 		case 'L':		/* input has lsb-to-msb fillorder */
123 			fillorder = FILLORDER_LSB2MSB;
124 			break;
125 		case 'M':		/* input has msb-to-lsb fillorder */
126 			fillorder = FILLORDER_MSB2LSB;
127 			break;
128 		case 'p':		/* photometric interpretation */
129 			if (strncmp(optarg, "miniswhite", 10) == 0)
130 				photometric = PHOTOMETRIC_MINISWHITE;
131 			else if (strncmp(optarg, "minisblack", 10) == 0)
132 				photometric = PHOTOMETRIC_MINISBLACK;
133 			else if (strncmp(optarg, "rgb", 3) == 0)
134 				photometric = PHOTOMETRIC_RGB;
135 			else if (strncmp(optarg, "cmyk", 4) == 0)
136 				photometric = PHOTOMETRIC_SEPARATED;
137 			else if (strncmp(optarg, "ycbcr", 5) == 0)
138 				photometric = PHOTOMETRIC_YCBCR;
139 			else if (strncmp(optarg, "cielab", 6) == 0)
140 				photometric = PHOTOMETRIC_CIELAB;
141 			else if (strncmp(optarg, "icclab", 6) == 0)
142 				photometric = PHOTOMETRIC_ICCLAB;
143 			else if (strncmp(optarg, "itulab", 6) == 0)
144 				photometric = PHOTOMETRIC_ITULAB;
145 			else
146 				photometric = PHOTOMETRIC_MINISBLACK;
147 			break;
148 		case 's':		/* do we need to swap bytes? */
149 			swab = 1;
150 			break;
151 		case 'i':		/* type of interleaving */
152 			if (strncmp(optarg, "pixel", 4) == 0)
153 				interleaving = PIXEL;
154 			else if  (strncmp(optarg, "band", 6) == 0)
155 				interleaving = BAND;
156 			else
157 				interleaving = 0;
158 			break;
159 		case 'o':
160 			outfilename = optarg;
161 			break;
162 		case 'h':
163 			usage();
164 		default:
165 			break;
166 		}
167 	if (argc - optind < 2)
168 		usage();
169 	in = fopen(argv[optind], "rb");
170 	if (in == NULL) {
171 		fprintf(stderr, "%s: %s: Cannot open input file.\n",
172 			argv[0], argv[optind]);
173 		return (-1);
174 	}
175 
176 	if (guessSize(in, dtype, hdr_size, nbands, swab, &width, &length) < 0)
177 		return 1;
178 
179 	if (outfilename == NULL)
180 		outfilename = argv[optind+1];
181 	out = TIFFOpen(outfilename, "w");
182 	if (out == NULL) {
183 		fprintf(stderr, "%s: %s: Cannot open file for output.\n",
184 			argv[0], outfilename);
185 		return (-1);
186 	}
187 	TIFFSetField(out, TIFFTAG_IMAGEWIDTH, width);
188 	TIFFSetField(out, TIFFTAG_IMAGELENGTH, length);
189 	TIFFSetField(out, TIFFTAG_ORIENTATION, ORIENTATION_TOPLEFT);
190 	TIFFSetField(out, TIFFTAG_SAMPLESPERPIXEL, nbands);
191 	TIFFSetField(out, TIFFTAG_BITSPERSAMPLE, depth * 8);
192 	TIFFSetField(out, TIFFTAG_FILLORDER, fillorder);
193 	TIFFSetField(out, TIFFTAG_PLANARCONFIG, config);
194 	TIFFSetField(out, TIFFTAG_PHOTOMETRIC, photometric);
195 	switch (dtype) {
196 	case TIFF_BYTE:
197 	case TIFF_SHORT:
198 	case TIFF_LONG:
199 		TIFFSetField(out, TIFFTAG_SAMPLEFORMAT, SAMPLEFORMAT_UINT);
200 		break;
201 	case TIFF_SBYTE:
202 	case TIFF_SSHORT:
203 	case TIFF_SLONG:
204 		TIFFSetField(out, TIFFTAG_SAMPLEFORMAT, SAMPLEFORMAT_INT);
205 		break;
206 	case TIFF_FLOAT:
207 	case TIFF_DOUBLE:
208 		TIFFSetField(out, TIFFTAG_SAMPLEFORMAT, SAMPLEFORMAT_IEEEFP);
209 		break;
210 	default:
211 		TIFFSetField(out, TIFFTAG_SAMPLEFORMAT, SAMPLEFORMAT_VOID);
212 		break;
213 	}
214 	if (compression == (uint16) -1)
215 		compression = COMPRESSION_PACKBITS;
216 	TIFFSetField(out, TIFFTAG_COMPRESSION, compression);
217 	switch (compression) {
218 	case COMPRESSION_JPEG:
219 		if (photometric == PHOTOMETRIC_RGB
220 		    && jpegcolormode == JPEGCOLORMODE_RGB)
221 			photometric = PHOTOMETRIC_YCBCR;
222 		TIFFSetField(out, TIFFTAG_JPEGQUALITY, quality);
223 		TIFFSetField(out, TIFFTAG_JPEGCOLORMODE, jpegcolormode);
224 		break;
225 	case COMPRESSION_LZW:
226 	case COMPRESSION_DEFLATE:
227 		if (predictor != 0)
228 			TIFFSetField(out, TIFFTAG_PREDICTOR, predictor);
229 		break;
230 	}
231 	switch(interleaving) {
232 	case BAND:				/* band interleaved data */
233 		linebytes = width * depth;
234 		buf = (unsigned char *)_TIFFmalloc(linebytes);
235 		break;
236 	case PIXEL:				/* pixel interleaved data */
237 	default:
238 		linebytes = width * nbands * depth;
239 		break;
240 	}
241 	bufsize = width * nbands * depth;
242 	buf1 = (unsigned char *)_TIFFmalloc(bufsize);
243 	TIFFSetField(out, TIFFTAG_ROWSPERSTRIP,
244 	    TIFFDefaultStripSize(out, rowsperstrip));
245 	fseek(in, hdr_size, SEEK_SET);		/* Skip the file header */
246 	for (row = 0; row < length; row++) {
247 		switch(interleaving) {
248 		case BAND:			/* band interleaved data */
249 			for (band = 0; band < nbands; band++) {
250 				fseek(in,
251 				      hdr_size + (length*band+row)*linebytes,
252 				      SEEK_SET);
253 				if (fread(buf, linebytes, 1, in) != 1) {
254 					fprintf(stderr,
255 					"%s: %s: scanline %lu: Read error.\n",
256 					argv[0], argv[optind],
257 					(unsigned long) row);
258 				break;
259 				}
260 				if (swab)	/* Swap bytes if needed */
261 					swapBytesInScanline(buf, width, dtype);
262 				for (col = 0; col < width; col++)
263 					memcpy(buf1 + (col*nbands+band)*depth,
264 					       buf + col * depth, depth);
265 			}
266 			break;
267 		case PIXEL:			/* pixel interleaved data */
268 		default:
269 			if (fread(buf1, bufsize, 1, in) != 1) {
270 				fprintf(stderr,
271 					"%s: %s: scanline %lu: Read error.\n",
272 					argv[0], argv[optind],
273 					(unsigned long) row);
274 				break;
275 			}
276 			if (swab)		/* Swap bytes if needed */
277 				swapBytesInScanline(buf1, width, dtype);
278 			break;
279 		}
280 
281 		if (TIFFWriteScanline(out, buf1, row, 0) < 0) {
282 			fprintf(stderr,	"%s: %s: scanline %lu: Write error.\n",
283 				argv[0], outfilename, (unsigned long) row);
284 			break;
285 		}
286 	}
287 	if (buf)
288 		_TIFFfree(buf);
289 	if (buf1)
290 		_TIFFfree(buf1);
291 	TIFFClose(out);
292 	return (0);
293 }
294 
295 static void
swapBytesInScanline(void * buf,uint32 width,TIFFDataType dtype)296 swapBytesInScanline(void *buf, uint32 width, TIFFDataType dtype)
297 {
298 	switch (dtype) {
299 		case TIFF_SHORT:
300 		case TIFF_SSHORT:
301 			TIFFSwabArrayOfShort((uint16*)buf, width);
302 			break;
303 		case TIFF_LONG:
304 		case TIFF_SLONG:
305 			TIFFSwabArrayOfLong((uint32*)buf, width);
306 			break;
307 		/* case TIFF_FLOAT: */	/* FIXME */
308 		case TIFF_DOUBLE:
309 			TIFFSwabArrayOfDouble((double*)buf, width);
310 			break;
311 		default:
312 			break;
313 	}
314 }
315 
316 static int
guessSize(FILE * fp,TIFFDataType dtype,uint32 hdr_size,int nbands,int swab,uint32 * width,uint32 * length)317 guessSize(FILE *fp, TIFFDataType dtype, uint32 hdr_size, int nbands, int swab,
318 	  uint32 *width, uint32 *length)
319 {
320 	const float longt = 40.0;    /* maximum possible height/width ratio */
321 	char	    *buf1, *buf2;
322 	struct stat filestat;
323 	uint32	    w, h, scanlinesize, imagesize;
324 	int	    depth = TIFFDataWidth(dtype);
325 	float	    cor_coef = 0, tmp;
326 
327 	fstat(fileno(fp), &filestat);
328 
329 	if (filestat.st_size < hdr_size) {
330 		fprintf(stderr, "Too large header size specified.\n");
331 		return -1;
332 	}
333 
334 	imagesize = (filestat.st_size - hdr_size) / nbands / depth;
335 
336 	if (*width != 0 && *length == 0) {
337 		fprintf(stderr,	"Image height is not specified.\n");
338 
339 		*length = imagesize / *width;
340 
341 		fprintf(stderr, "Height is guessed as %ld.\n", *length);
342 
343 		return 1;
344 	} else if (*width == 0 && *length != 0) {
345 		fprintf(stderr, "Image width is not specified.\n");
346 
347 		*width = imagesize / *length;
348 
349 		fprintf(stderr,	"Width is guessed as %ld.\n", *width);
350 
351 		return 1;
352 	} else if (*width == 0 && *length == 0) {
353 		fprintf(stderr,	"Image width and height are not specified.\n");
354 
355 		for (w = sqrt(imagesize / longt);
356 		     w < sqrt(imagesize * longt);
357 		     w++) {
358 			if (imagesize % w == 0) {
359 				scanlinesize = w * depth;
360 				buf1 = _TIFFmalloc(scanlinesize);
361 				buf2 = _TIFFmalloc(scanlinesize);
362 				h = imagesize / w;
363 				fseek(fp, hdr_size + (int)(h/2)*scanlinesize,
364 				      SEEK_SET);
365 				fread(buf1, scanlinesize, 1, fp);
366 				fread(buf2, scanlinesize, 1, fp);
367 				if (swab) {
368 					swapBytesInScanline(buf1, w, dtype);
369 					swapBytesInScanline(buf2, w, dtype);
370 				}
371 				tmp = fabs(correlation(buf1, buf2, w, dtype));
372 				if (tmp > cor_coef) {
373 					cor_coef = tmp;
374 					*width = w, *length = h;
375 				}
376 
377 				_TIFFfree(buf1);
378 				_TIFFfree(buf2);
379 			}
380 		}
381 
382 		fprintf(stderr,
383 			"Width is guessed as %ld, height is guessed as %ld.\n",
384 			*width, *length);
385 
386 		return 1;
387 	} else {
388 		if (filestat.st_size<hdr_size+(*width)*(*length)*nbands*depth) {
389 			fprintf(stderr, "Input file too small.\n");
390 		return -1;
391 		}
392 	}
393 
394 	return 1;
395 }
396 
397 /* Calculate correlation coefficient between two numeric vectors */
398 static double
correlation(void * buf1,void * buf2,uint32 n_elem,TIFFDataType dtype)399 correlation(void *buf1, void *buf2, uint32 n_elem, TIFFDataType dtype)
400 {
401 	float	X, Y, M1 = 0.0, M2 = 0.0, D1 = 0.0, D2 = 0.0, K = 0.0;
402 	int	i;
403 
404 	switch (dtype) {
405 		case TIFF_BYTE:
406 		default:
407                         for (i = 0; i < n_elem; i++) {
408 				X = ((u_char *)buf1)[i];
409 				Y = ((u_char *)buf2)[i];
410 				M1 += X, M2 += Y;
411 				D1 += X * X, D2 += Y * Y;
412 				K += X * Y;
413                         }
414 			break;
415 		case TIFF_SBYTE:
416                         for (i = 0; i < n_elem; i++) {
417 				X = ((signed char *)buf1)[i];
418 				Y = ((signed char *)buf2)[i];
419 				M1 += X, M2 += Y;
420 				D1 += X * X, D2 += Y * Y;
421 				K += X * Y;
422                         }
423 			break;
424 		case TIFF_SHORT:
425                         for (i = 0; i < n_elem; i++) {
426 				X = ((uint16 *)buf1)[i];
427 				Y = ((uint16 *)buf2)[i];
428 				M1 += X, M2 += Y;
429 				D1 += X * X, D2 += Y * Y;
430 				K += X * Y;
431                         }
432 			break;
433 		case TIFF_SSHORT:
434                         for (i = 0; i < n_elem; i++) {
435 				X = ((int16 *)buf1)[i];
436 				Y = ((int16 *)buf2)[i];
437 				M1 += X, M2 += Y;
438 				D1 += X * X, D2 += Y * Y;
439 				K += X * Y;
440                         }
441 			break;
442 		case TIFF_LONG:
443                         for (i = 0; i < n_elem; i++) {
444 				X = ((uint32 *)buf1)[i];
445 				Y = ((uint32 *)buf2)[i];
446 				M1 += X, M2 += Y;
447 				D1 += X * X, D2 += Y * Y;
448 				K += X * Y;
449                         }
450 			break;
451 		case TIFF_SLONG:
452                         for (i = 0; i < n_elem; i++) {
453 				X = ((int32 *)buf1)[i];
454 				Y = ((int32 *)buf2)[i];
455 				M1 += X, M2 += Y;
456 				D1 += X * X, D2 += Y * Y;
457 				K += X * Y;
458                         }
459 			break;
460 		case TIFF_FLOAT:
461                         for (i = 0; i < n_elem; i++) {
462 				X = ((float *)buf1)[i];
463 				Y = ((float *)buf2)[i];
464 				M1 += X, M2 += Y;
465 				D1 += X * X, D2 += Y * Y;
466 				K += X * Y;
467                         }
468 			break;
469 		case TIFF_DOUBLE:
470                         for (i = 0; i < n_elem; i++) {
471 				X = ((double *)buf1)[i];
472 				Y = ((double *)buf2)[i];
473 				M1 += X, M2 += Y;
474 				D1 += X * X, D2 += Y * Y;
475 				K += X * Y;
476                         }
477 			break;
478 	}
479 
480 	M1 /= n_elem;
481 	M2 /= n_elem;
482 	D1 -= M1 * M1 * n_elem;
483 	D2 -= M2 * M2 * n_elem;
484 	K = (K - M1 * M2 * n_elem) / sqrt(D1 * D2);
485 
486 	return K;
487 }
488 
489 static int
processCompressOptions(char * opt)490 processCompressOptions(char* opt)
491 {
492 	if (strcmp(opt, "none") == 0)
493 		compression = COMPRESSION_NONE;
494 	else if (strcmp(opt, "packbits") == 0)
495 		compression = COMPRESSION_PACKBITS;
496 	else if (strncmp(opt, "jpeg", 4) == 0) {
497 		char* cp = strchr(opt, ':');
498 		if (cp && isdigit(cp[1]))
499 			quality = atoi(cp+1);
500 		if (cp && strchr(cp, 'r'))
501 			jpegcolormode = JPEGCOLORMODE_RAW;
502 		compression = COMPRESSION_JPEG;
503 	} else if (strncmp(opt, "lzw", 3) == 0) {
504 		char* cp = strchr(opt, ':');
505 		if (cp)
506 			predictor = atoi(cp+1);
507 		compression = COMPRESSION_LZW;
508 	} else if (strncmp(opt, "zip", 3) == 0) {
509 		char* cp = strchr(opt, ':');
510 		if (cp)
511 			predictor = atoi(cp+1);
512 		compression = COMPRESSION_DEFLATE;
513 	} else
514 		return (0);
515 	return (1);
516 }
517 
518 char* stuff[] = {
519 "raw2tiff --- tool to converting raw byte sequences in TIFF images",
520 "usage: raw2tiff [options] input.raw output.tif",
521 "where options are:",
522 " -L		input data has LSB2MSB bit order (default)",
523 " -M		input data has MSB2LSB bit order",
524 " -r #		make each strip have no more than # rows",
525 " -H #		size of input image file header in bytes (0 by default)",
526 " -w #		width of input image in pixels",
527 " -l #		length of input image in lines",
528 " -b #		number of bands in input image (1 by default)",
529 "",
530 " -d data_type	type of samples in input image",
531 "where data_type may be:",
532 " byte		8-bit unsigned integer (default)",
533 " short		16-bit unsigned integer",
534 " long		32-bit unsigned integer",
535 " sbyte		8-bit signed integer",
536 " sshort		16-bit signed integer",
537 " slong		32-bit signed integer",
538 " float		32-bit IEEE floating point",
539 " double		64-bit IEEE floating point",
540 "",
541 " -p photo	photometric interpretation (color space) of the input image",
542 "where photo may be:",
543 " miniswhite	white color represented with 0 value",
544 " minisblack	black color represented with 0 value (default)",
545 " rgb		image has RGB color model",
546 " cmyk		image has CMYK (separated) color model",
547 " ycbcr		image has YCbCr color model",
548 " cielab		image has CIE L*a*b color model",
549 " icclab		image has ICC L*a*b color model",
550 " itulab		image has ITU L*a*b color model",
551 "",
552 " -s		swap bytes fetched from input file",
553 "",
554 " -i config	type of samples interleaving in input image",
555 "where config may be:",
556 " pixel		pixel interleaved data (default)",
557 " band		band interleaved data",
558 "",
559 " -c lzw[:opts]	compress output with Lempel-Ziv & Welch encoding",
560 "               (no longer supported by default due to Unisys patent enforcement)",
561 " -c zip[:opts]	compress output with deflate encoding",
562 " -c jpeg[:opts]compress output with JPEG encoding",
563 " -c packbits	compress output with packbits encoding",
564 " -c none	use no compression algorithm on output",
565 "",
566 "JPEG options:",
567 " #		set compression quality level (0-100, default 75)",
568 " r		output color image as RGB rather than YCbCr",
569 "For example, -c jpeg:r:50 to get JPEG-encoded RGB data with 50% comp. quality",
570 "",
571 "LZW and deflate options:",
572 " #		set predictor value",
573 "For example, -c lzw:2 to get LZW-encoded data with horizontal differencing",
574 " -o out.tif	write output to out.tif",
575 " -h		this help message",
576 NULL
577 };
578 
579 static void
usage(void)580 usage(void)
581 {
582 	char buf[BUFSIZ];
583 	int i;
584 
585 	setbuf(stderr, buf);
586         fprintf(stderr, "%s\n\n", TIFFGetVersion());
587 	for (i = 0; stuff[i] != NULL; i++)
588 		fprintf(stderr, "%s\n", stuff[i]);
589 	exit(-1);
590 }
591 
592