- Main Page
- Data Structures
- Files

- File List

# E:/DevIL/src-IL/src/il_neuquant.c

    00001 /* NeuQuant Neural-Net Quantization Algorithm
    00002  * ------------------------------------------
    00003  *
    00004  * Copyright (c) 1994 Anthony Dekker
    00005  *
    00006  * NEUQUANT Neural-Net quantization algorithm by Anthony Dekker, 1994.
    00007  * See "Kohonen neural networks for optimal colour quantization"
    00008  * in "Network: Computation in Neural Systems" Vol. 5 (1994) pp 351-367.
    00009  * for a discussion of the algorithm.
    00010  * See also  http://www.acm.org/~dekker/NEUQUANT.HTML
    00011  *
    00012  * Any party obtaining a copy of these files from the author, directly or
    00013  * indirectly, is granted, free of charge, a full and unrestricted irrevocable,
    00014  * world-wide, paid up, royalty-free, nonexclusive right and license to deal
    00015  * in this software and documentation files (the "Software"), including without
    00016  * limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
    00017  * and/or sell copies of the Software, and to permit persons who receive
    00018  * copies from any such party to do so, with the only requirement being
    00019  * that this copyright notice remain intact.
    00020  */
    00021
    00022 //-----------------------------------------------------------------------------
    00023 //
    00024 // ImageLib Sources
    00025 // by Denton Woods
    00026 // Last modified: 01/04/2009
    00027 //
    00028 // Filename: src-IL/src/il_neuquant.c
    00029 //
    00030 // Description: Heavily modified by Denton Woods.
    00031 //
    00032 //-----------------------------------------------------------------------------
    00033
    00034 #include "il_internal.h"
    00035
    00036
    00037 // Function definitions
    00038 void    initnet(ILubyte *thepic, ILint len, ILint sample);
    00039 void    unbiasnet();
    00040 void    inxbuild();
    00041 ILubyte inxsearch(ILint b, ILint g, ILint r);
    00042 void    learn();
    00043
    00044 // four primes near 500 - assume no image has a length so large
    00045 // that it is divisible by all four primes
    00046 #define prime1                  499
    00047 #define prime2                  491
    00048 #define prime3                  487
    00049 #define prime4                  503
    00050
    00051 #define minpicturebytes (3*prime4)                      // minimum size for input image
    00052
    00053
    00054 // Network Definitions
    00055 // -------------------
    00056
    00057 #define netsize                 256                                     // number of colours used
    00058 #define maxnetpos               (netsizethink-1)
    00059 #define netbiasshift    4                                       // bias for colour values
    00060 #define ncycles                 100                                     // no. of learning cycles
    00061
    00062 // defs for freq and bias
    00063 #define intbiasshift    16                                      // bias for fractions
    00064 #define intbias                 (((ILint) 1)<<intbiasshift)
    00065 #define gammashift              10                                      // gamma = 1024
    00066 #define gamma                   (((ILint) 1)<<gammashift)
    00067 #define betashift               10
    00068 #define beta                    (intbias>>betashift)// beta = 1/1024
    00069 #define betagamma               (intbias<<(gammashift-betashift))
    00070
    00071 // defs for decreasing radius factor
    00072 #define initrad                 (netsize>>3)            // for 256 cols, radius starts
    00073 #define radiusbiasshift 6                                       // at 32.0 biased by 6 bits
    00074 #define radiusbias              (((ILint) 1)<<radiusbiasshift)
    00075 #define initradius              (initrad*radiusbias)    // and decreases by a
    00076 #define radiusdec               30                                              // factor of 1/30 each cycle
    00077
    00078 // defs for decreasing alpha factor
    00079 #define alphabiasshift  10                                              // alpha starts at 1.0
    00080 #define initalpha               (((ILint) 1)<<alphabiasshift)
    00081 ILint   alphadec;                                                               // biased by 10 bits
    00082
    00083 // radbias and alpharadbias used for radpower calculation
    00084 #define radbiasshift    8
    00085 #define radbias                 (((ILint) 1)<<radbiasshift)
    00086 #define alpharadbshift  (alphabiasshift+radbiasshift)
    00087 #define alpharadbias    (((ILint) 1)<<alpharadbshift)
    00088
    00089
    00090 // Types and Global Variables
    00091 // --------------------------
    00092
    00093 unsigned char   *thepicture;                    // the input image itself
    00094 int                             lengthcount;                    // lengthcount = H*W*3
    00095 int                             samplefac;                              // sampling factor 1..30
    00096 typedef int             pixel[4];                               // BGRc
    00097 static pixel    network[netsize];               // the network itself
    00098 int                             netindex[256];                  // for network lookup - really 256
    00099 int                             bias [netsize];                 // bias and freq arrays for learning
    00100 int                             freq [netsize];
    00101 int                             radpower[initrad];              // radpower for precomputation
    00102
    00103 int netsizethink; // number of colors we want to reduce to, 2-256
    00104
    00105 // Initialise network in range (0,0,0) to (255,255,255) and set parameters
    00106 // -----------------------------------------------------------------------
    00107
    00108 void initnet(ILubyte *thepic, ILint len, ILint sample)
    00109 {
    00110         ILint i;
    00111         ILint *p;
    00112
    00113         thepicture = thepic;
    00114         lengthcount = len;
    00115         samplefac = sample;
    00116
    00117         for (i=0; i<netsizethink; i++) {
    00118                 p = network[i];
    00119                 p[0] = p[1] = p[2] = (i << (netbiasshift+8))/netsize;
    00120                 freq[i] = intbias/netsizethink; // 1/netsize
    00121                 bias[i] = 0;
    00122         }
    00123         return;
    00124 }
    00125
    00126
    00127 // Unbias network to give byte values 0..255 and record position i to prepare for sort
    00128 // -----------------------------------------------------------------------------------
    00129
    00130 void unbiasnet()
    00131 {
    00132         ILint i,j;
    00133
    00134         for (i=0; i<netsizethink; i++) {
    00135                 for (j=0; j<3; j++)
    00136                         network[i][j] >>= netbiasshift;
    00137                 network[i][3] = i;                      // record colour no
    00138         }
    00139         return;
    00140 }
    00141
    00142
    00143 // Insertion sort of network and building of netindex[0..255] (to do after unbias)
    00144 // -------------------------------------------------------------------------------
    00145
    00146 void inxbuild()
    00147 {
    00148         ILint i,j,smallpos,smallval;
    00149         ILint *p,*q;
    00150         ILint previouscol,startpos;
    00151
    00152         previouscol = 0;
    00153         startpos = 0;
    00154         for (i=0; i<netsizethink; i++) {
    00155                 p = network[i];
    00156                 smallpos = i;
    00157                 smallval = p[1];                        // index on g
    00158                 // find smallest in i..netsize-1
    00159                 for (j=i+1; j<netsizethink; j++) {
    00160                         q = network[j];
    00161                         if (q[1] < smallval) {  // index on g
    00162                                 smallpos = j;
    00163                                 smallval = q[1];        // index on g
    00164                         }
    00165                 }
    00166                 q = network[smallpos];
    00167                 // swap p (i) and q (smallpos) entries
    00168                 if (i != smallpos) {
    00169                         j = q[0];   q[0] = p[0];   p[0] = j;
    00170                         j = q[1];   q[1] = p[1];   p[1] = j;
    00171                         j = q[2];   q[2] = p[2];   p[2] = j;
    00172                         j = q[3];   q[3] = p[3];   p[3] = j;
    00173                 }
    00174                 // smallval entry is now in position i
    00175                 if (smallval != previouscol) {
    00176                         netindex[previouscol] = (startpos+i)>>1;
    00177                         for (j=previouscol+1; j<smallval; j++) netindex[j] = i;
    00178                         previouscol = smallval;
    00179                         startpos = i;
    00180                 }
    00181         }
    00182         netindex[previouscol] = (startpos+maxnetpos)>>1;
    00183         for (j=previouscol+1; j<256; j++) netindex[j] = maxnetpos; // really 256
    00184         return;
    00185 }
    00186
    00187
    00188 // Search for BGR values 0..255 (after net is unbiased) and return colour index
    00189 // ----------------------------------------------------------------------------
    00190
    00191 ILubyte inxsearch(ILint b, ILint g, ILint r)
    00192 {
    00193         ILint i,j,dist,a,bestd;
    00194         ILint *p;
    00195         ILint best;
    00196
    00197         bestd = 1000;           // biggest possible dist is 256*3
    00198         best = -1;
    00199         i = netindex[g];        // index on g
    00200         j = i-1;                        // start at netindex[g] and work outwards
    00201
    00202         while ((i<netsizethink) || (j>=0)) {
    00203                 if (i<netsizethink) {
    00204                         p = network[i];
    00205                         dist = p[1] - g;                // inx key
    00206                         if (dist >= bestd) i = netsizethink;    // stop iter
    00207                         else {
    00208                                 i++;
    00209                                 if (dist<0) dist = -dist;
    00210                                 a = p[0] - b;   if (a<0) a = -a;
    00211                                 dist += a;
    00212                                 if (dist<bestd) {
    00213                                         a = p[2] - r;   if (a<0) a = -a;
    00214                                         dist += a;
    00215                                         if (dist<bestd) {bestd=dist; best=p[3];}
    00216                                 }
    00217                         }
    00218                 }
    00219                 if (j>=0) {
    00220                         p = network[j];
    00221                         dist = g - p[1]; // inx key - reverse dif
    00222                         if (dist >= bestd) j = -1; // stop iter
    00223                         else {
    00224                                 j--;
    00225                                 if (dist<0) dist = -dist;
    00226                                 a = p[0] - b;   if (a<0) a = -a;
    00227                                 dist += a;
    00228                                 if (dist<bestd) {
    00229                                         a = p[2] - r;   if (a<0) a = -a;
    00230                                         dist += a;
    00231                                         if (dist<bestd) {bestd=dist; best=p[3];}
    00232                                 }
    00233                         }
    00234                 }
    00235         }
    00236         return (ILubyte)best;
    00237 }
    00238
    00239
    00240 // Search for biased BGR values
    00241 // ----------------------------
    00242
    00243 ILint contest(ILint b, ILint g, ILint r)
    00244 {
    00245         // finds closest neuron (min dist) and updates freq
    00246         // finds best neuron (min dist-bias) and returns position
    00247         // for frequently chosen neurons, freq[i] is high and bias[i] is negative
    00248         // bias[i] = gamma*((1/netsize)-freq[i])
    00249
    00250         ILint i,dist,a,biasdist,betafreq;
    00251         ILint bestpos,bestbiaspos,bestd,bestbiasd;
    00252         ILint *p,*f, *n;
    00253
    00254         bestd = ~(((ILint) 1)<<31);
    00255         bestbiasd = bestd;
    00256         bestpos = -1;
    00257         bestbiaspos = bestpos;
    00258         p = bias;
    00259         f = freq;
    00260
    00261         for (i=0; i<netsizethink; i++) {
    00262                 n = network[i];
    00263                 dist = n[0] - b;   if (dist<0) dist = -dist;
    00264                 a = n[1] - g;   if (a<0) a = -a;
    00265                 dist += a;
    00266                 a = n[2] - r;   if (a<0) a = -a;
    00267                 dist += a;
    00268                 if (dist<bestd) {bestd=dist; bestpos=i;}
    00269                 biasdist = dist - ((*p)>>(intbiasshift-netbiasshift));
    00270                 if (biasdist<bestbiasd) {bestbiasd=biasdist; bestbiaspos=i;}
    00271                 betafreq = (*f >> betashift);
    00272                 *f++ -= betafreq;
    00273                 *p++ += (betafreq<<gammashift);
    00274         }
    00275         freq[bestpos] += beta;
    00276         bias[bestpos] -= betagamma;
    00277         return(bestbiaspos);
    00278 }
    00279
    00280
    00281 // Move neuron i towards biased (b,g,r) by factor alpha
    00282 // ----------------------------------------------------
    00283
    00284 void altersingle(ILint alpha, ILint i, ILint b, ILint g, ILint r)
    00285 {
    00286         ILint *n;
    00287
    00288         n = network[i];                         // alter hit neuron
    00289         *n -= (alpha*(*n - b)) / initalpha;
    00290         n++;
    00291         *n -= (alpha*(*n - g)) / initalpha;
    00292         n++;
    00293         *n -= (alpha*(*n - r)) / initalpha;
    00294         return;
    00295 }
    00296
    00297
    00298 // Move adjacent neurons by precomputed alpha*(1-((i-j)^2/[r]^2)) in radpower[|i-j|]
    00299 // ---------------------------------------------------------------------------------
    00300
    00301 void alterneigh(ILint rad, ILint i, ILint b, ILint g, ILint r)
    00302 {
    00303         ILint j,k,lo,hi,a;
    00304         ILint *p, *q;
    00305
    00306         lo = i-rad;   if (lo<-1) lo=-1;
    00307         hi = i+rad;   if (hi>netsizethink) hi=netsizethink;
    00308
    00309         j = i+1;
    00310         k = i-1;
    00311         q = radpower;
    00312         while ((j<hi) || (k>lo)) {
    00313                 a = (*(++q));
    00314                 if (j<hi) {
    00315                         p = network[j];
    00316                         *p -= (a*(*p - b)) / alpharadbias;
    00317                         p++;
    00318                         *p -= (a*(*p - g)) / alpharadbias;
    00319                         p++;
    00320                         *p -= (a*(*p - r)) / alpharadbias;
    00321                         j++;
    00322                 }
    00323                 if (k>lo) {
    00324                         p = network[k];
    00325                         *p -= (a*(*p - b)) / alpharadbias;
    00326                         p++;
    00327                         *p -= (a*(*p - g)) / alpharadbias;
    00328                         p++;
    00329                         *p -= (a*(*p - r)) / alpharadbias;
    00330                         k--;
    00331                 }
    00332         }
    00333         return;
    00334 }
    00335
    00336
    00337 // Main Learning Loop
    00338 // ------------------
    00339
    00340 void learn()
    00341 {
    00342         ILint i,j,b,g,r;
    00343         ILint radius,rad,alpha,step,delta,samplepixels;
    00344         ILubyte *p;
    00345         ILubyte *lim;
    00346
    00347         alphadec = 30 + ((samplefac-1)/3);
    00348         p = thepicture;
    00349         lim = thepicture + lengthcount;
    00350         samplepixels = lengthcount/(3*samplefac);
    00351         delta = samplepixels/ncycles;
    00352         alpha = initalpha;
    00353         radius = initradius;
    00354
    00355         rad = radius >> radiusbiasshift;
    00356         if (rad <= 1) rad = 0;
    00357         for (i=0; i<rad; i++)
    00358                 radpower[i] = alpha*(((rad*rad - i*i)*radbias)/(rad*rad));
    00359
    00360         // beginning 1D learning: initial radius=rad
    00361
    00362         if ((lengthcount%prime1) != 0) step = 3*prime1;
    00363         else {
    00364                 if ((lengthcount%prime2) !=0) step = 3*prime2;
    00365                 else {
    00366                         if ((lengthcount%prime3) !=0) step = 3*prime3;
    00367                         else step = 3*prime4;
    00368                 }
    00369         }
    00370
    00371         i = 0;
    00372         while (i < samplepixels) {
    00373                 b = p[0] << netbiasshift;
    00374                 g = p[1] << netbiasshift;
    00375                 r = p[2] << netbiasshift;
    00376                 j = contest(b,g,r);
    00377
    00378                 altersingle(alpha,j,b,g,r);
    00379                 if (rad) alterneigh(rad,j,b,g,r);   // alter neighbours
    00380
    00381                 p += step;
    00382                 if (p >= lim) p -= lengthcount;
    00383
    00384                 i++;
    00385                 if (i%delta == 0) {
    00386                         alpha -= alpha / alphadec;
    00387                         radius -= radius / radiusdec;
    00388                         rad = radius >> radiusbiasshift;
    00389                         if (rad <= 1) rad = 0;
    00390                         for (j=0; j<rad; j++)
    00391                                 radpower[j] = alpha*(((rad*rad - j*j)*radbias)/(rad*rad));
    00392                 }
    00393         }
    00394         // finished 1D learning: final alpha=alpha/initalpha;
    00395         return;
    00396 }
    00397
    00398
    00399 ILimage *iNeuQuant(ILimage *Image, ILuint NumCols)
    00400 {
    00401         ILimage *TempImage, *NewImage;
    00402         ILuint  sample, i, j;
    00403
    00404         netsizethink=NumCols;
    00405
    00406         NewImage = iCurImage;
    00407         iCurImage = Image;
    00408         TempImage = iConvertImage(iCurImage, IL_BGR, IL_UNSIGNED_BYTE);
    00409         iCurImage = NewImage;
    00410         sample = ilGetInteger(IL_NEU_QUANT_SAMPLE);
    00411
    00412         if (TempImage == NULL)
    00413                 return NULL;
    00414
    00415         initnet(TempImage->Data, TempImage->SizeOfData, sample);
    00416         learn();
    00417         unbiasnet();
    00418
    00419         NewImage = (ILimage*)icalloc(sizeof(ILimage), 1);
    00420         if (NewImage == NULL) {
    00421                 ilCloseImage(TempImage);
    00422                 return NULL;
    00423         }
    00424         NewImage->Data = (ILubyte*)ialloc(TempImage->SizeOfData / 3);
    00425         if (NewImage->Data == NULL) {
    00426                 ilCloseImage(TempImage);
    00427                 ifree(NewImage);
    00428                 return NULL;
    00429         }
    00430         ilCopyImageAttr(NewImage, Image);
    00431         NewImage->Bpp = 1;
    00432         NewImage->Bps = Image->Width;
    00433         NewImage->SizeOfPlane = NewImage->Bps * Image->Height;
    00434         NewImage->SizeOfData = NewImage->SizeOfPlane;
    00435         NewImage->Format = IL_COLOUR_INDEX;
    00436         NewImage->Type = IL_UNSIGNED_BYTE;
    00437
    00438         NewImage->Pal.PalSize = netsizethink * 3;
    00439         NewImage->Pal.PalType = IL_PAL_BGR24;
    00440         NewImage->Pal.Palette = (ILubyte*)ialloc(256*3);
    00441         if (NewImage->Pal.Palette == NULL) {
    00442                 ilCloseImage(TempImage);
    00443                 ilCloseImage(NewImage);
    00444                 return NULL;
    00445         }
    00446
    00447         for (i = 0, j = 0; i < (unsigned)netsizethink; i++, j += 3) {
    00448                 NewImage->Pal.Palette[j  ] = network[i][0];
    00449                 NewImage->Pal.Palette[j+1] = network[i][1];
    00450                 NewImage->Pal.Palette[j+2] = network[i][2];
    00451         }
    00452
    00453         inxbuild();
    00454         for (i = 0, j = 0; j < TempImage->SizeOfData; i++, j += 3) {
    00455                 NewImage->Data[i] = inxsearch(
    00456                         TempImage->Data[j], TempImage->Data[j+1], TempImage->Data[j+2]);
    00457         }
    00458
    00459         ilCloseImage(TempImage);
    00460
    00461         return NewImage;
    00462 }