FAST color counting of a pixmap.

BlitzMax Forums/BlitzMax Beginners Area/FAST color counting of a pixmap.

The forum is locked. These are the original blitzbasic.com forums, kept so they can still be read. No new topics, replies or edits can be made here. To join in, head over to the Blitz3D+ forums.

I made this in afew minutes.

Type color_counter
	Field colors:Tmap
	
	Method New()
		colors=CreateMap()
	EndMethod
	
	Method Add(r,g,b)
		Local i
		
		If MapContains(colors,tos(r,g,b))
			i=Int(String(MapValueForKey(colors,tos(r,g,b))))
		EndIf
		i:+1
		MapInsert(colors,tos(r,g,b),String(i))
			
	EndMethod
	
	Method Count:Int()
		Local i
		For Local o:Object=EachIn MapKeys(colors)
			i:+1
		Next
		Return i
	EndMethod 
	
	Function Tos:String(r,g,b)	' rgb to a string
		Return String(r)+"-"+String(g)+"-"+String(b)
	EndFunction
EndType

Function count_colors(source:TImage) 
	Local sourcePixmap:TPixmap = LockImage(source) 
	Local sourcePixmapPtr:Byte Ptr = PixmapPixelPtr(sourcePixmap, 0, 0) 
	Local tmpPixmap:TPixmap = CopyPixmap(sourcePixmap)
	Local tmpPixmapPtr:Byte Ptr = PixmapPixelPtr(tmpPixmap,0,0)
	'Local x:Int,y:Int
	Local w:Int = tmpPixmap.width
	Local h:Int = tmpPixmap.height
	
	Local colors:color_counter=New color_counter
	
	For Local x:Int = 0 To w - 1
		For Local y:Int = 0 To h - 1
			Local red = sourcePixmapPtr[x * 4 + y * 4 * w] 
			Local green = sourcePixmapPtr[x * 4 + y * 4 * w + 1] 
			Local blue = sourcePixmapPtr[x * 4 + y * 4 * w + 2] 
			
			colors.Add(red,green,blue)
					
		Next
	Next
	Notify("There are " + colors.Count() + " colors in this image.") 
	Return Null
EndFunction