summaryrefslogtreecommitdiff
path: root/src/pnmlcms.c
blob: 41b304712edf212379c11890a23c28c92f2cc6fe (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
#include <pam.h>
#include <lcms.h>

static int
pam_transform(struct pam *inpam, struct pam *outpam, cmsHTRANSFORM *hTransform);

int
main(int argc, char **argv) {
	int c, i, nProf = 0;
	char *in_prof = NULL, *out_prof = NULL;
	double gamma = 0.0;
	cmsHTRANSFORM hTransform;
	cmsHPROFILE profiles[3];
	struct pam inpam, outpam;

	while ((c = getopt(argc, argv, "i:o:g:")) != EOF) {
		switch (c) {  
			case 'i':
				in_prof = optarg;
				break;
			case 'o':
				out_prof = optarg;
				break;
			case 'g':
				gamma = atof(optarg);
				break;
			default:
				break;
		}
	}


	if (in_prof) {
		profiles[nProf++] = cmsOpenProfileFromFile(in_prof, "r");
	} else {
		profiles[nProf++] = cmsCreate_sRGBProfile();
	}

	if (gamma) {
		LPGAMMATABLE gTable[3];

		gTable[0] = cmsBuildGamma(256, gamma);
		gTable[1] = gTable[2] = cmsBuildGamma(256, 1.0);

		profiles[nProf++] = cmsCreateLinearizationDeviceLink(
			icSigLabData,
			gTable);
	}

	if (out_prof) {
		profiles[nProf++] = cmsOpenProfileFromFile(out_prof, "r");
	} else {
		profiles[nProf++] = cmsCreate_sRGBProfile();
	}


	hTransform = cmsCreateMultiprofileTransform(
		profiles,
		nProf,
		TYPE_RGB_16,
		TYPE_RGB_16,
		INTENT_PERCEPTUAL,
		0);
	
	pm_init(argv[0], 0);

	pnm_readpaminit(stdin, &inpam, PAM_STRUCT_SIZE(tuple_type));

	outpam = inpam; outpam.file = stdout;

	pnm_writepaminit(&outpam);

	pam_transform(&inpam, &outpam, &hTransform);

	cmsDeleteTransform(hTransform);
	
	for (i = 0; i < nProf; i++) {
		cmsCloseProfile(profiles[i]);
	}

	return 0;
}

static int
pam_transform(struct pam *inpam, struct pam *outpam, cmsHTRANSFORM *hTransform)
{
	tuple *inrow, *outrow;
	int row, col;


	inrow = pnm_allocpamrow(inpam);
	outrow = pnm_allocpamrow(outpam);

	for (row = 0; row < inpam->height; row++) {
		pnm_readpamrow(inpam, inrow);
		for (col = 0; col < inpam->width; col++) {
			int i;
			unsigned short inpix[3], outpix[3];
			
			for (i = 0; i < 3; i++) {
				inpix[i] = (unsigned short) inrow[col][i];
			}

			cmsDoTransform(*hTransform, inpix, outpix, 1);

			for (i = 0; i < 3; i++) {
				 outrow[col][i] = (sample) outpix[i];
			}
		}


		pnm_writepamrow(outpam, outrow); 
	}

	pnm_freepamrow(inrow);
	pnm_freepamrow(outrow);

	return 0;
}