统计一副彩色图像实际使用的颜色数

     

      源代码下载:https://files.cnblogs.com/laviewpbt/CountColor.rar

     一副24位彩色图像最多可以使用256*256*256=16777216种颜色,但是在实际的彩色图像中,不可能全使用了这么多种颜色,那么如何快速统计出他实际使用的颜色数呢,这里贴出我的实现方案,供大家参考,大家如果有更好的方案,也感谢提出哦。

      如果是一副32位的PNG图像,那么最多可能有256*256*256*256=4294967296,那又该如何统计实际用的颜色,期待大侠的出现。

 

      程序的关键代码:

       BitmapData bmData = m_Bitmap.LockBits(new Rectangle(00, m_Bitmap.Width, m_Bitmap.Height), ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb);

            
int stride = bmData.Stride;
            System.IntPtr Scan0 
= bmData.Scan0;
            Stopwatch sw 
= new Stopwatch();
            sw.Start();
         
            
            
int [] BlueGreen=new int [65536];     //Blue-Red 数组
            byte [] Red=new byte[16777215];
            
int Index, M, N;
            
int Count;
            
int Width;
            
int Height;
            
int Stride;
            Count 
= 0;
            N 
= 0;
            M 
= 0;
            Width 
= bmData.Width;                   //直接访问变量比访问结构体的成员速度要快
            Height = bmData.Height;
            Stride 
= bmData.Stride;
            
unsafe
            {
               
                
for (int y = 0; y < Height; ++y)
                {
                    
byte* p = (byte*)(void*)Scan0 +Stride*y;
                    
for (int x = 0; x < Width; ++x)
                    {
                        Index
=p[0]*256+p[1];
                        N
=BlueGreen[Index];
                        
if (N==0)                   //未出现过的Blue和Green组合
                        {
                            M
++;
                            BlueGreen[Index]
=M;
                            Red[p[
2]*65536+M]=1;
                            Count
++;
                        }
                        
else
                        {
                            Index
=p[2]*65536+N;
                            
if (Red[Index]==0)
                            {
                                Red[Index]
=1;
                                Count
++;
                            }
                        }
                        p 
+= 3;
                    }
                }
            }
            sw.Stop();
            MessageBox.Show( (sw.ElapsedMilliseconds).ToString());   
//耗时
            this.Text = Count.ToString();       //图像中使用的颜色数
            m_Bitmap.UnlockBits(bmData);

 

 

posted on 2011-06-14 20:43  彭佳乐  阅读(2331)  评论(7编辑  收藏  举报

导航