1 /* NeuQuant Neural-Net Quantization Algorithm
2 * ------------------------------------------
3 *
4 * Copyright (c) 1994 Anthony Dekker
5 *
6 * NEUQUANT Neural-Net quantization algorithm by Anthony Dekker, 1994.
7 * See "Kohonen neural networks for optimal colour quantization"
8 * in "Network: Computation in Neural Systems" Vol. 5 (1994) pp 351-367.
9 * for a discussion of the algorithm.
10 * See also http://www.acm.org/~dekker/NEUQUANT.HTML
11 *
12 * Any party obtaining a copy of these files from the author, directly or
13 * indirectly, is granted, free of charge, a full and unrestricted irrevocable,
14 * world-wide, paid up, royalty-free, nonexclusive right and license to deal
15 * in this software and documentation files (the "Software"), including without
16 * limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
17 * and/or sell copies of the Software, and to permit persons who receive
18 * copies from any such party to do so, with the only requirement being
19 * that this copyright notice remain intact.
20 */
21
22 //-----------------------------------------------------------------------------
23 //
24 // ImageLib Sources
25 // by Denton Woods
26 // Last modified: 01/04/2009
27 //
28 // Filename: src-IL/src/il_neuquant.c
29 //
30 // Description: Heavily modified by Denton Woods.
31 //
32 //-----------------------------------------------------------------------------
33
34 #include "il_internal.h"
35
36
37 // Function definitions
38 void initnet(ILubyte *thepic, ILint len, ILint sample);
39 void unbiasnet();
40 void inxbuild();
41 ILubyte inxsearch(ILint b, ILint g, ILint r);
42 void learn();
43
44 // four primes near 500 - assume no image has a length so large
45 // that it is divisible by all four primes
46 #define prime1 499
47 #define prime2 491
48 #define prime3 487
49 #define prime4 503
50
51 #define minpicturebytes (3*prime4) // minimum size for input image
52
53
54 // Network Definitions
55 // -------------------
56
57 #define netsize 256 // number of colours used
58 #define maxnetpos (netsizethink-1)
59 #define netbiasshift 4 // bias for colour values
60 #define ncycles 100 // no. of learning cycles
61
62 // defs for freq and bias
63 #define intbiasshift 16 // bias for fractions
64 #define intbias (((ILint) 1)<<intbiasshift)
65 #define gammashift 10 // gamma = 1024
66 #define gamma (((ILint) 1)<<gammashift)
67 #define betashift 10
68 #define beta (intbias>>betashift)// beta = 1/1024
69 #define betagamma (intbias<<(gammashift-betashift))
70
71 // defs for decreasing radius factor
72 #define initrad (netsize>>3) // for 256 cols, radius starts
73 #define radiusbiasshift 6 // at 32.0 biased by 6 bits
74 #define radiusbias (((ILint) 1)<<radiusbiasshift)
75 #define initradius (initrad*radiusbias) // and decreases by a
76 #define radiusdec 30 // factor of 1/30 each cycle
77
78 // defs for decreasing alpha factor
79 #define alphabiasshift 10 // alpha starts at 1.0
80 #define initalpha (((ILint) 1)<<alphabiasshift)
81 ILint alphadec; // biased by 10 bits
82
83 // radbias and alpharadbias used for radpower calculation
84 #define radbiasshift 8
85 #define radbias (((ILint) 1)<<radbiasshift)
86 #define alpharadbshift (alphabiasshift+radbiasshift)
87 #define alpharadbias (((ILint) 1)<<alpharadbshift)
88
89
90 // Types and Global Variables
91 // --------------------------
92
93 unsigned char *thepicture; // the input image itself
94 int lengthcount; // lengthcount = H*W*3
95 int samplefac; // sampling factor 1..30
96 typedef int pixel[4]; // BGRc
97 static pixel network[netsize]; // the network itself
98 int netindex[256]; // for network lookup - really 256
99 int bias [netsize]; // bias and freq arrays for learning
100 int freq [netsize];
101 int radpower[initrad]; // radpower for precomputation
102
103 int netsizethink; // number of colors we want to reduce to, 2-256
104
105 // Initialise network in range (0,0,0) to (255,255,255) and set parameters
106 // -----------------------------------------------------------------------
107
initnet(ILubyte * thepic,ILint len,ILint sample)108 void initnet(ILubyte *thepic, ILint len, ILint sample)
109 {
110 ILint i;
111 ILint *p;
112
113 thepicture = thepic;
114 lengthcount = len;
115 samplefac = sample;
116
117 for (i=0; i<netsizethink; i++) {
118 p = network[i];
119 p[0] = p[1] = p[2] = (i << (netbiasshift+8))/netsize;
120 freq[i] = intbias/netsizethink; // 1/netsize
121 bias[i] = 0;
122 }
123 return;
124 }
125
126
127 // Unbias network to give byte values 0..255 and record position i to prepare for sort
128 // -----------------------------------------------------------------------------------
129
unbiasnet()130 void unbiasnet()
131 {
132 ILint i,j;
133
134 for (i=0; i<netsizethink; i++) {
135 for (j=0; j<3; j++)
136 network[i][j] >>= netbiasshift;
137 network[i][3] = i; // record colour no
138 }
139 return;
140 }
141
142
143 // Insertion sort of network and building of netindex[0..255] (to do after unbias)
144 // -------------------------------------------------------------------------------
145
inxbuild()146 void inxbuild()
147 {
148 ILint i,j,smallpos,smallval;
149 ILint *p,*q;
150 ILint previouscol,startpos;
151
152 previouscol = 0;
153 startpos = 0;
154 for (i=0; i<netsizethink; i++) {
155 p = network[i];
156 smallpos = i;
157 smallval = p[1]; // index on g
158 // find smallest in i..netsize-1
159 for (j=i+1; j<netsizethink; j++) {
160 q = network[j];
161 if (q[1] < smallval) { // index on g
162 smallpos = j;
163 smallval = q[1]; // index on g
164 }
165 }
166 q = network[smallpos];
167 // swap p (i) and q (smallpos) entries
168 if (i != smallpos) {
169 j = q[0]; q[0] = p[0]; p[0] = j;
170 j = q[1]; q[1] = p[1]; p[1] = j;
171 j = q[2]; q[2] = p[2]; p[2] = j;
172 j = q[3]; q[3] = p[3]; p[3] = j;
173 }
174 // smallval entry is now in position i
175 if (smallval != previouscol) {
176 netindex[previouscol] = (startpos+i)>>1;
177 for (j=previouscol+1; j<smallval; j++) netindex[j] = i;
178 previouscol = smallval;
179 startpos = i;
180 }
181 }
182 netindex[previouscol] = (startpos+maxnetpos)>>1;
183 for (j=previouscol+1; j<256; j++) netindex[j] = maxnetpos; // really 256
184 return;
185 }
186
187
188 // Search for BGR values 0..255 (after net is unbiased) and return colour index
189 // ----------------------------------------------------------------------------
190
inxsearch(ILint b,ILint g,ILint r)191 ILubyte inxsearch(ILint b, ILint g, ILint r)
192 {
193 ILint i,j,dist,a,bestd;
194 ILint *p;
195 ILint best;
196
197 bestd = 1000; // biggest possible dist is 256*3
198 best = -1;
199 i = netindex[g]; // index on g
200 j = i-1; // start at netindex[g] and work outwards
201
202 while ((i<netsizethink) || (j>=0)) {
203 if (i<netsizethink) {
204 p = network[i];
205 dist = p[1] - g; // inx key
206 if (dist >= bestd) i = netsizethink; // stop iter
207 else {
208 i++;
209 if (dist<0) dist = -dist;
210 a = p[0] - b; if (a<0) a = -a;
211 dist += a;
212 if (dist<bestd) {
213 a = p[2] - r; if (a<0) a = -a;
214 dist += a;
215 if (dist<bestd) {bestd=dist; best=p[3];}
216 }
217 }
218 }
219 if (j>=0) {
220 p = network[j];
221 dist = g - p[1]; // inx key - reverse dif
222 if (dist >= bestd) j = -1; // stop iter
223 else {
224 j--;
225 if (dist<0) dist = -dist;
226 a = p[0] - b; if (a<0) a = -a;
227 dist += a;
228 if (dist<bestd) {
229 a = p[2] - r; if (a<0) a = -a;
230 dist += a;
231 if (dist<bestd) {bestd=dist; best=p[3];}
232 }
233 }
234 }
235 }
236 return (ILubyte)best;
237 }
238
239
240 // Search for biased BGR values
241 // ----------------------------
242
contest(ILint b,ILint g,ILint r)243 ILint contest(ILint b, ILint g, ILint r)
244 {
245 // finds closest neuron (min dist) and updates freq
246 // finds best neuron (min dist-bias) and returns position
247 // for frequently chosen neurons, freq[i] is high and bias[i] is negative
248 // bias[i] = gamma*((1/netsize)-freq[i])
249
250 ILint i,dist,a,biasdist,betafreq;
251 ILint bestpos,bestbiaspos,bestd,bestbiasd;
252 ILint *p,*f, *n;
253
254 bestd = ~(((ILint) 1)<<31);
255 bestbiasd = bestd;
256 bestpos = -1;
257 bestbiaspos = bestpos;
258 p = bias;
259 f = freq;
260
261 for (i=0; i<netsizethink; i++) {
262 n = network[i];
263 dist = n[0] - b; if (dist<0) dist = -dist;
264 a = n[1] - g; if (a<0) a = -a;
265 dist += a;
266 a = n[2] - r; if (a<0) a = -a;
267 dist += a;
268 if (dist<bestd) {bestd=dist; bestpos=i;}
269 biasdist = dist - ((*p)>>(intbiasshift-netbiasshift));
270 if (biasdist<bestbiasd) {bestbiasd=biasdist; bestbiaspos=i;}
271 betafreq = (*f >> betashift);
272 *f++ -= betafreq;
273 *p++ += (betafreq<<gammashift);
274 }
275 freq[bestpos] += beta;
276 bias[bestpos] -= betagamma;
277 return(bestbiaspos);
278 }
279
280
281 // Move neuron i towards biased (b,g,r) by factor alpha
282 // ----------------------------------------------------
283
altersingle(ILint alpha,ILint i,ILint b,ILint g,ILint r)284 void altersingle(ILint alpha, ILint i, ILint b, ILint g, ILint r)
285 {
286 ILint *n;
287
288 n = network[i]; // alter hit neuron
289 *n -= (alpha*(*n - b)) / initalpha;
290 n++;
291 *n -= (alpha*(*n - g)) / initalpha;
292 n++;
293 *n -= (alpha*(*n - r)) / initalpha;
294 return;
295 }
296
297
298 // Move adjacent neurons by precomputed alpha*(1-((i-j)^2/[r]^2)) in radpower[|i-j|]
299 // ---------------------------------------------------------------------------------
300
alterneigh(ILint rad,ILint i,ILint b,ILint g,ILint r)301 void alterneigh(ILint rad, ILint i, ILint b, ILint g, ILint r)
302 {
303 ILint j,k,lo,hi,a;
304 ILint *p, *q;
305
306 lo = i-rad; if (lo<-1) lo=-1;
307 hi = i+rad; if (hi>netsizethink) hi=netsizethink;
308
309 j = i+1;
310 k = i-1;
311 q = radpower;
312 while ((j<hi) || (k>lo)) {
313 a = (*(++q));
314 if (j<hi) {
315 p = network[j];
316 *p -= (a*(*p - b)) / alpharadbias;
317 p++;
318 *p -= (a*(*p - g)) / alpharadbias;
319 p++;
320 *p -= (a*(*p - r)) / alpharadbias;
321 j++;
322 }
323 if (k>lo) {
324 p = network[k];
325 *p -= (a*(*p - b)) / alpharadbias;
326 p++;
327 *p -= (a*(*p - g)) / alpharadbias;
328 p++;
329 *p -= (a*(*p - r)) / alpharadbias;
330 k--;
331 }
332 }
333 return;
334 }
335
336
337 // Main Learning Loop
338 // ------------------
339
learn()340 void learn()
341 {
342 ILint i,j,b,g,r;
343 ILint radius,rad,alpha,step,delta,samplepixels;
344 ILubyte *p;
345 ILubyte *lim;
346
347 alphadec = 30 + ((samplefac-1)/3);
348 p = thepicture;
349 lim = thepicture + lengthcount;
350 samplepixels = lengthcount/(3*samplefac);
351 delta = samplepixels/ncycles;
352 alpha = initalpha;
353 radius = initradius;
354
355 rad = radius >> radiusbiasshift;
356 if (rad <= 1) rad = 0;
357 for (i=0; i<rad; i++)
358 radpower[i] = alpha*(((rad*rad - i*i)*radbias)/(rad*rad));
359
360 // beginning 1D learning: initial radius=rad
361
362 if ((lengthcount%prime1) != 0) step = 3*prime1;
363 else {
364 if ((lengthcount%prime2) !=0) step = 3*prime2;
365 else {
366 if ((lengthcount%prime3) !=0) step = 3*prime3;
367 else step = 3*prime4;
368 }
369 }
370
371 i = 0;
372 while (i < samplepixels) {
373 b = p[0] << netbiasshift;
374 g = p[1] << netbiasshift;
375 r = p[2] << netbiasshift;
376 j = contest(b,g,r);
377
378 altersingle(alpha,j,b,g,r);
379 if (rad) alterneigh(rad,j,b,g,r); // alter neighbours
380
381 p += step;
382 if (p >= lim) p -= lengthcount;
383
384 i++;
385 if (i%delta == 0) {
386 alpha -= alpha / alphadec;
387 radius -= radius / radiusdec;
388 rad = radius >> radiusbiasshift;
389 if (rad <= 1) rad = 0;
390 for (j=0; j<rad; j++)
391 radpower[j] = alpha*(((rad*rad - j*j)*radbias)/(rad*rad));
392 }
393 }
394 // finished 1D learning: final alpha=alpha/initalpha;
395 return;
396 }
397
398
iNeuQuant(ILimage * Image,ILuint NumCols)399 ILimage *iNeuQuant(ILimage *Image, ILuint NumCols)
400 {
401 ILimage *TempImage, *NewImage;
402 ILuint sample, i, j;
403
404 netsizethink=NumCols;
405
406 NewImage = iCurImage;
407 iCurImage = Image;
408 TempImage = iConvertImage(iCurImage, IL_BGR, IL_UNSIGNED_BYTE);
409 iCurImage = NewImage;
410 sample = ilGetInteger(IL_NEU_QUANT_SAMPLE);
411
412 if (TempImage == NULL)
413 return NULL;
414
415 initnet(TempImage->Data, TempImage->SizeOfData, sample);
416 learn();
417 unbiasnet();
418
419 NewImage = (ILimage*)icalloc(sizeof(ILimage), 1);
420 if (NewImage == NULL) {
421 ilCloseImage(TempImage);
422 return NULL;
423 }
424 NewImage->Data = (ILubyte*)ialloc(TempImage->SizeOfData / 3);
425 if (NewImage->Data == NULL) {
426 ilCloseImage(TempImage);
427 ifree(NewImage);
428 return NULL;
429 }
430 ilCopyImageAttr(NewImage, Image);
431 NewImage->Bpp = 1;
432 NewImage->Bps = Image->Width;
433 NewImage->SizeOfPlane = NewImage->Bps * Image->Height;
434 NewImage->SizeOfData = NewImage->SizeOfPlane;
435 NewImage->Format = IL_COLOUR_INDEX;
436 NewImage->Type = IL_UNSIGNED_BYTE;
437
438 NewImage->Pal.PalSize = netsizethink * 3;
439 NewImage->Pal.PalType = IL_PAL_BGR24;
440 NewImage->Pal.Palette = (ILubyte*)ialloc(256*3);
441 if (NewImage->Pal.Palette == NULL) {
442 ilCloseImage(TempImage);
443 ilCloseImage(NewImage);
444 return NULL;
445 }
446
447 for (i = 0, j = 0; i < (unsigned)netsizethink; i++, j += 3) {
448 NewImage->Pal.Palette[j ] = network[i][0];
449 NewImage->Pal.Palette[j+1] = network[i][1];
450 NewImage->Pal.Palette[j+2] = network[i][2];
451 }
452
453 inxbuild();
454 for (i = 0, j = 0; j < TempImage->SizeOfData; i++, j += 3) {
455 NewImage->Data[i] = inxsearch(
456 TempImage->Data[j], TempImage->Data[j+1], TempImage->Data[j+2]);
457 }
458
459 ilCloseImage(TempImage);
460
461 return NewImage;
462 }
463