I have an operation that will be performed MANY times and so I need it to be as fast as possible, thus I think keeping validations to a minimum is important here.
I’m given an image, an offset and a size; and the idea is to take the color that appears the most within the area determined by the size and offset, so far I have this:
Private Shared Function someFunction(image As Bitmap, offset As Point, sampleSize As Size) As Color
Dim pixelsColors As New List(Of Color)
For i As Integer = offset.X To offset.X + sampleSize.Width
For j As Integer = offset.Y To offset.Y + sampleSize.Height
pixelsColors.Add(image.GetPixel(i, j))
Next
Next
End Function
What I now need is to know what is the most repeating item within the list and choose a in the case more than one have the top count, choose a random item of those that won.
I don’t even mind getting rid of the List(Of Color) and using some other (more appropriate) object.
UPDATE AFTER ACCEPTING ANSWER
The idea of the answer seems good but since there are a few minor error I’ll post this code for future reference for other.
Private Shared Function someFunction(image As Bitmap, offset As Point, sampleSize As Size) As Color
Dim pixelsColors As New Collections.Generic.Dictionary(Of Color, Integer)
For i As Integer = offset.X To offset.X + sampleSize.Width
For j As Integer = offset.Y To offset.Y + sampleSize.Height
Dim color As Color = image.GetPixel(i, j)
Dim count As Integer
If Not pixelsColors.TryGetValue(color, count) Then count = 0
pixelsColors(color) = count + 1
Next
Next
Return pixelsColors.OrderByDescending(Function(colorCount) colorCount.Value).First.Key
End Function
Instead of storing a linear
List(Of Color)you should be using a hash table which allows you to associate aColorwith a count. Then you con do a simple traversal at the end to discover what the highest count is