Number of colors in an image

Will McGugan news at NOwillmcguganSPAM.com
Fri Nov 26 13:48:08 EST 2004


Laszlo Zsolt Nagy wrote:
>   Hello,
> 
> How can I determine the number of colors used in an image? I tried to
> search on Google but I could figure out. I read the PIL handbook but I
> do not see how to do it. Can anyone help?

You may get a better response on how to do it in Python, but the 
following C++ code should be easy to translate if necessary. All it 
requires is a get pixel function.

int CImage::CountUsedColours() const
{
	if ( !IsValid() ) { Error( errImageInvalid ); return 0; }	
	
	const int TableSize= ( 256 * 256 * 256 ) / 8;

	byte CountTable[ TableSize ];
	memset( &CountTable[0], 0, TableSize );	
	
	for( int Y= 0; Y < GetHeight(); Y++ )
	{
		byte* pColour= (byte*)GetLinePointer( Y );
		int WidthCount= GetWidth();		

		while( WidthCount-- )
		{
			const CColour colPix= GetPixel( pColour );
			const int Offset= (int)colPix.R << 16 | (int)colPix.G << 8 | 
(int)colPix.B;
			CountTable[ Offset >> 3 ] |= 1 << ( Offset & 7 );
			pColour+= GetBPP();
		}

	}

	int ColourCount= 0;

	for( int n= 0; n < TableSize; n++ )
	{
		const int CountBits= CountTable[n];

		ColourCount+= ( CountBits & 1 );
		ColourCount+= ( CountBits >> 1 ) & 1;
		ColourCount+= ( CountBits >> 2 ) & 1;
		ColourCount+= ( CountBits >> 3 ) & 1;
		ColourCount+= ( CountBits >> 4 ) & 1;
		ColourCount+= ( CountBits >> 5 ) & 1;
		ColourCount+= ( CountBits >> 6 ) & 1;
		ColourCount+= ( CountBits >> 7 );						
	}

	OK();
	return ColourCount;
}


Regards,

Will McGugan



More information about the Python-list mailing list