Generally, an image has three RGB channels. Each channel is represented by a byte and the value ranges from 0 to 255. For each channel, we can calculate the histogram of the image, which is actually to calculate the occurrence frequency of each pixel value, as shown in:
The effect of histogram equalization is to convert the three-channel histogram of the source image into a uniform distribution, and the number of occurrences of each pixel value is similar. The following is the effect of histogram equalization (the histogram is viewed by light and shade, generatedCodeSee later ):
We can see that the histogram of the image is very even.
Code for histogram equalization:
Bool gfimage: histogramequalization () {vector <uchar> pixmaps; calculatemapfunbyhiseq (pixmaps); For (int ch = 0; ch <getchannel (); ch ++) {uchar * pdata = getdata (); For (INT r = 0; r <getheight (); R ++) {uchar * pline = pdata + R * getwidthstep (); for (int c = 0; C <getwidth (); C ++) {uchar val = pline [getchannel () * C + CH]; pline [getchannel () * C + CH] = pixmaps [CH] [Val] ;}} return true ;}
Bool gfimage: calculatemapfunbyhiseq (vector <uchar> & vmappings) const {vmappings. resize (getchannel (); For (INT I = 0; I <vmappings. size (); I ++) {vmappings [I]. resize (256);} vector <gfhistogram> vhistograms; vhistograms. resize (getchannel (); For (INT I = 0; I <getchannel (); I ++) {vhistograms [I]. calculate (* This, 256, I);} double TMP; For (INT CH = 0; ch <getchannel (); ch ++) {TMP = vhistograms [CH]. getfrequencyat (0) * 255; vmappings [CH] [0] = (uchar) TMP; For (Int J = 1; j <256; j ++) {TMP = TMP + vhistograms [CH]. getfrequencyat (j) * 255; vmappings [CH] [J] = (uchar) TMP ;}} return true ;}
Call time
String strimagepath = "lena.jpg"; gfimage image1 (strimagepath); image1.showimage ("Ori"); image1.histogramequalization (); image1.showimage ("res"); CV: waitkey ();
Gfimage encapsulates the image class of opencv, and gfhistogram is a custom histogram class. For detailed code, refer to here