il_neuquant.c
Upload User: wmy0603
Upload Date: 2022-05-02
Package Size: 1808k
Code Size: 12k
Development Platform:

Visual C++

  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. // ImageLib Sources
  24. // by Denton Woods
  25. // Last modified: 01/04/2009
  26. //
  27. // Filename: src-IL/src/il_neuquant.c
  28. //
  29. // Description: Heavily modified by Denton Woods.
  30. //
  31. //-----------------------------------------------------------------------------
  32. #include "il_internal.h"
  33. // Function definitions
  34. void initnet(ILubyte *thepic, ILint len, ILint sample);
  35. void unbiasnet();
  36. void inxbuild();
  37. ILubyte inxsearch(ILint b, ILint g, ILint r);
  38. void learn();
  39. // four primes near 500 - assume no image has a length so large
  40. // that it is divisible by all four primes
  41. #define prime1 499
  42. #define prime2 491
  43. #define prime3 487
  44. #define prime4 503
  45. #define minpicturebytes (3*prime4) // minimum size for input image
  46. // Network Definitions
  47. // -------------------
  48.    
  49. #define netsize 256 // number of colours used
  50. #define maxnetpos (netsizethink-1)
  51. #define netbiasshift 4 // bias for colour values
  52. #define ncycles 100 // no. of learning cycles
  53. // defs for freq and bias
  54. #define intbiasshift 16 // bias for fractions
  55. #define intbias (((ILint) 1)<<intbiasshift)
  56. #define gammashift 10 // gamma = 1024
  57. #define gamma (((ILint) 1)<<gammashift)
  58. #define betashift 10
  59. #define beta (intbias>>betashift)// beta = 1/1024
  60. #define betagamma (intbias<<(gammashift-betashift))
  61. // defs for decreasing radius factor
  62. #define initrad (netsize>>3) // for 256 cols, radius starts
  63. #define radiusbiasshift 6 // at 32.0 biased by 6 bits
  64. #define radiusbias (((ILint) 1)<<radiusbiasshift)
  65. #define initradius (initrad*radiusbias) // and decreases by a
  66. #define radiusdec 30 // factor of 1/30 each cycle
  67. // defs for decreasing alpha factor
  68. #define alphabiasshift 10 // alpha starts at 1.0
  69. #define initalpha (((ILint) 1)<<alphabiasshift)
  70. ILint alphadec; // biased by 10 bits
  71. // radbias and alpharadbias used for radpower calculation
  72. #define radbiasshift 8
  73. #define radbias (((ILint) 1)<<radbiasshift)
  74. #define alpharadbshift (alphabiasshift+radbiasshift)
  75. #define alpharadbias (((ILint) 1)<<alpharadbshift)
  76. // Types and Global Variables
  77. // --------------------------
  78.    
  79. unsigned char *thepicture; // the input image itself
  80. int lengthcount; // lengthcount = H*W*3
  81. int samplefac; // sampling factor 1..30
  82. typedef int pixel[4]; // BGRc
  83. static pixel network[netsize]; // the network itself
  84. int netindex[256]; // for network lookup - really 256
  85. int bias [netsize]; // bias and freq arrays for learning
  86. int freq [netsize];
  87. int radpower[initrad]; // radpower for precomputation
  88. int netsizethink; // number of colors we want to reduce to, 2-256
  89. // Initialise network in range (0,0,0) to (255,255,255) and set parameters
  90. // -----------------------------------------------------------------------
  91. void initnet(ILubyte *thepic, ILint len, ILint sample)
  92. {
  93. ILint i;
  94. ILint *p;
  95. thepicture = thepic;
  96. lengthcount = len;
  97. samplefac = sample;
  98. for (i=0; i<netsizethink; i++) {
  99. p = network[i];
  100. p[0] = p[1] = p[2] = (i << (netbiasshift+8))/netsize;
  101. freq[i] = intbias/netsizethink; // 1/netsize
  102. bias[i] = 0;
  103. }
  104. return;
  105. }
  106. // Unbias network to give byte values 0..255 and record position i to prepare for sort
  107. // -----------------------------------------------------------------------------------
  108. void unbiasnet()
  109. {
  110. ILint i,j;
  111. for (i=0; i<netsizethink; i++) {
  112. for (j=0; j<3; j++)
  113. network[i][j] >>= netbiasshift;
  114. network[i][3] = i; // record colour no
  115. }
  116. return;
  117. }
  118. // Insertion sort of network and building of netindex[0..255] (to do after unbias)
  119. // -------------------------------------------------------------------------------
  120. void inxbuild()
  121. {
  122. ILint i,j,smallpos,smallval;
  123. ILint *p,*q;
  124. ILint previouscol,startpos;
  125. previouscol = 0;
  126. startpos = 0;
  127. for (i=0; i<netsizethink; i++) {
  128. p = network[i];
  129. smallpos = i;
  130. smallval = p[1]; // index on g
  131. // find smallest in i..netsize-1
  132. for (j=i+1; j<netsizethink; j++) {
  133. q = network[j];
  134. if (q[1] < smallval) { // index on g
  135. smallpos = j;
  136. smallval = q[1]; // index on g
  137. }
  138. }
  139. q = network[smallpos];
  140. // swap p (i) and q (smallpos) entries
  141. if (i != smallpos) {
  142. j = q[0];   q[0] = p[0];   p[0] = j;
  143. j = q[1];   q[1] = p[1];   p[1] = j;
  144. j = q[2];   q[2] = p[2];   p[2] = j;
  145. j = q[3];   q[3] = p[3];   p[3] = j;
  146. }
  147. // smallval entry is now in position i
  148. if (smallval != previouscol) {
  149. netindex[previouscol] = (startpos+i)>>1;
  150. for (j=previouscol+1; j<smallval; j++) netindex[j] = i;
  151. previouscol = smallval;
  152. startpos = i;
  153. }
  154. }
  155. netindex[previouscol] = (startpos+maxnetpos)>>1;
  156. for (j=previouscol+1; j<256; j++) netindex[j] = maxnetpos; // really 256
  157. return;
  158. }
  159. // Search for BGR values 0..255 (after net is unbiased) and return colour index
  160. // ----------------------------------------------------------------------------
  161. ILubyte inxsearch(ILint b, ILint g, ILint r)
  162. {
  163. ILint i,j,dist,a,bestd;
  164. ILint *p;
  165. ILint best;
  166. bestd = 1000; // biggest possible dist is 256*3
  167. best = -1;
  168. i = netindex[g]; // index on g
  169. j = i-1; // start at netindex[g] and work outwards
  170. while ((i<netsizethink) || (j>=0)) {
  171. if (i<netsizethink) {
  172. p = network[i];
  173. dist = p[1] - g; // inx key
  174. if (dist >= bestd) i = netsizethink; // stop iter
  175. else {
  176. i++;
  177. if (dist<0) dist = -dist;
  178. a = p[0] - b;   if (a<0) a = -a;
  179. dist += a;
  180. if (dist<bestd) {
  181. a = p[2] - r;   if (a<0) a = -a;
  182. dist += a;
  183. if (dist<bestd) {bestd=dist; best=p[3];}
  184. }
  185. }
  186. }
  187. if (j>=0) {
  188. p = network[j];
  189. dist = g - p[1]; // inx key - reverse dif
  190. if (dist >= bestd) j = -1; // stop iter
  191. else {
  192. j--;
  193. if (dist<0) dist = -dist;
  194. a = p[0] - b;   if (a<0) a = -a;
  195. dist += a;
  196. if (dist<bestd) {
  197. a = p[2] - r;   if (a<0) a = -a;
  198. dist += a;
  199. if (dist<bestd) {bestd=dist; best=p[3];}
  200. }
  201. }
  202. }
  203. }
  204. return (ILubyte)best;
  205. }
  206. // Search for biased BGR values
  207. // ----------------------------
  208. ILint contest(ILint b, ILint g, ILint r)
  209. {
  210. // finds closest neuron (min dist) and updates freq
  211. // finds best neuron (min dist-bias) and returns position
  212. // for frequently chosen neurons, freq[i] is high and bias[i] is negative
  213. // bias[i] = gamma*((1/netsize)-freq[i])
  214. ILint i,dist,a,biasdist,betafreq;
  215. ILint bestpos,bestbiaspos,bestd,bestbiasd;
  216. ILint *p,*f, *n;
  217. bestd = ~(((ILint) 1)<<31);
  218. bestbiasd = bestd;
  219. bestpos = -1;
  220. bestbiaspos = bestpos;
  221. p = bias;
  222. f = freq;
  223. for (i=0; i<netsizethink; i++) {
  224. n = network[i];
  225. dist = n[0] - b;   if (dist<0) dist = -dist;
  226. a = n[1] - g;   if (a<0) a = -a;
  227. dist += a;
  228. a = n[2] - r;   if (a<0) a = -a;
  229. dist += a;
  230. if (dist<bestd) {bestd=dist; bestpos=i;}
  231. biasdist = dist - ((*p)>>(intbiasshift-netbiasshift));
  232. if (biasdist<bestbiasd) {bestbiasd=biasdist; bestbiaspos=i;}
  233. betafreq = (*f >> betashift);
  234. *f++ -= betafreq;
  235. *p++ += (betafreq<<gammashift);
  236. }
  237. freq[bestpos] += beta;
  238. bias[bestpos] -= betagamma;
  239. return(bestbiaspos);
  240. }
  241. // Move neuron i towards biased (b,g,r) by factor alpha
  242. // ----------------------------------------------------
  243. void altersingle(ILint alpha, ILint i, ILint b, ILint g, ILint r)
  244. {
  245. ILint *n;
  246. n = network[i]; // alter hit neuron
  247. *n -= (alpha*(*n - b)) / initalpha;
  248. n++;
  249. *n -= (alpha*(*n - g)) / initalpha;
  250. n++;
  251. *n -= (alpha*(*n - r)) / initalpha;
  252. return;
  253. }
  254. // Move adjacent neurons by precomputed alpha*(1-((i-j)^2/[r]^2)) in radpower[|i-j|]
  255. // ---------------------------------------------------------------------------------
  256. void alterneigh(ILint rad, ILint i, ILint b, ILint g, ILint r)
  257. {
  258. ILint j,k,lo,hi,a;
  259. ILint *p, *q;
  260. lo = i-rad;   if (lo<-1) lo=-1;
  261. hi = i+rad;   if (hi>netsizethink) hi=netsizethink;
  262. j = i+1;
  263. k = i-1;
  264. q = radpower;
  265. while ((j<hi) || (k>lo)) {
  266. a = (*(++q));
  267. if (j<hi) {
  268. p = network[j];
  269. *p -= (a*(*p - b)) / alpharadbias;
  270. p++;
  271. *p -= (a*(*p - g)) / alpharadbias;
  272. p++;
  273. *p -= (a*(*p - r)) / alpharadbias;
  274. j++;
  275. }
  276. if (k>lo) {
  277. p = network[k];
  278. *p -= (a*(*p - b)) / alpharadbias;
  279. p++;
  280. *p -= (a*(*p - g)) / alpharadbias;
  281. p++;
  282. *p -= (a*(*p - r)) / alpharadbias;
  283. k--;
  284. }
  285. }
  286. return;
  287. }
  288. // Main Learning Loop
  289. // ------------------
  290. void learn()
  291. {
  292. ILint i,j,b,g,r;
  293. ILint radius,rad,alpha,step,delta,samplepixels;
  294. ILubyte *p;
  295. ILubyte *lim;
  296. alphadec = 30 + ((samplefac-1)/3);
  297. p = thepicture;
  298. lim = thepicture + lengthcount;
  299. samplepixels = lengthcount/(3*samplefac);
  300. delta = samplepixels/ncycles;
  301. alpha = initalpha;
  302. radius = initradius;
  303. rad = radius >> radiusbiasshift;
  304. if (rad <= 1) rad = 0;
  305. for (i=0; i<rad; i++) 
  306. radpower[i] = alpha*(((rad*rad - i*i)*radbias)/(rad*rad));
  307. // beginning 1D learning: initial radius=rad
  308. if ((lengthcount%prime1) != 0) step = 3*prime1;
  309. else {
  310. if ((lengthcount%prime2) !=0) step = 3*prime2;
  311. else {
  312. if ((lengthcount%prime3) !=0) step = 3*prime3;
  313. else step = 3*prime4;
  314. }
  315. }
  316. i = 0;
  317. while (i < samplepixels) {
  318. b = p[0] << netbiasshift;
  319. g = p[1] << netbiasshift;
  320. r = p[2] << netbiasshift;
  321. j = contest(b,g,r);
  322. altersingle(alpha,j,b,g,r);
  323. if (rad) alterneigh(rad,j,b,g,r);   // alter neighbours
  324. p += step;
  325. if (p >= lim) p -= lengthcount;
  326. i++;
  327. if (i%delta == 0) {
  328. alpha -= alpha / alphadec;
  329. radius -= radius / radiusdec;
  330. rad = radius >> radiusbiasshift;
  331. if (rad <= 1) rad = 0;
  332. for (j=0; j<rad; j++) 
  333. radpower[j] = alpha*(((rad*rad - j*j)*radbias)/(rad*rad));
  334. }
  335. }
  336. // finished 1D learning: final alpha=alpha/initalpha;
  337. return;
  338. }
  339. ILimage *iNeuQuant(ILimage *Image, ILuint NumCols)
  340. {
  341. ILimage *TempImage, *NewImage;
  342. ILuint sample, i, j;
  343. netsizethink=NumCols;
  344. NewImage = iCurImage;
  345. iCurImage = Image;
  346. TempImage = iConvertImage(iCurImage, IL_BGR, IL_UNSIGNED_BYTE);
  347. iCurImage = NewImage;
  348. sample = ilGetInteger(IL_NEU_QUANT_SAMPLE);
  349. if (TempImage == NULL)
  350. return NULL;
  351. initnet(TempImage->Data, TempImage->SizeOfData, sample);
  352. learn();
  353. unbiasnet();
  354. NewImage = (ILimage*)icalloc(sizeof(ILimage), 1);
  355. if (NewImage == NULL) {
  356. ilCloseImage(TempImage);
  357. return NULL;
  358. }
  359. NewImage->Data = (ILubyte*)ialloc(TempImage->SizeOfData / 3);
  360. if (NewImage->Data == NULL) {
  361. ilCloseImage(TempImage);
  362. ifree(NewImage);
  363. return NULL;
  364. }
  365. ilCopyImageAttr(NewImage, Image);
  366. NewImage->Bpp = 1;
  367. NewImage->Bps = Image->Width;
  368. NewImage->SizeOfPlane = NewImage->Bps * Image->Height;
  369. NewImage->SizeOfData = NewImage->SizeOfPlane;
  370. NewImage->Format = IL_COLOUR_INDEX;
  371. NewImage->Type = IL_UNSIGNED_BYTE;
  372. NewImage->Pal.PalSize = netsizethink * 3;
  373. NewImage->Pal.PalType = IL_PAL_BGR24;
  374. NewImage->Pal.Palette = (ILubyte*)ialloc(256*3);
  375. if (NewImage->Pal.Palette == NULL) {
  376. ilCloseImage(TempImage);
  377. ilCloseImage(NewImage);
  378. return NULL;
  379. }
  380. for (i = 0, j = 0; i < (unsigned)netsizethink; i++, j += 3) {
  381. NewImage->Pal.Palette[j  ] = network[i][0];
  382. NewImage->Pal.Palette[j+1] = network[i][1];
  383. NewImage->Pal.Palette[j+2] = network[i][2];
  384. }
  385. inxbuild();
  386. for (i = 0, j = 0; j < TempImage->SizeOfData; i++, j += 3) {
  387. NewImage->Data[i] = inxsearch(
  388. TempImage->Data[j], TempImage->Data[j+1], TempImage->Data[j+2]);
  389. }
  390. ilCloseImage(TempImage);
  391. return NewImage;
  392. }