列表中相同对象的快速计数

时间:2012-03-28 23:29:27

标签: .net vb.net

我的操作会执行很多次,所以我需要它尽可能快,因此我认为将验证保持在最低限度非常重要。

我给了一个图像,偏移量和大小;并且想法是采取由大小和偏移确定的区域内最多出现的颜色,到目前为止我有这个:

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

我现在需要的是知道列表中最重复的项目是什么,并选择一个多个具有最高计数的情况,选择一个赢得的随机项目。

我甚至不介意摆脱List(Of Color)并使用其他(更合适的)对象。

接受答复后的更新

答案的想法似乎很好,但由于存在一些小错误,我会发布此代码以供将来参考。

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

1 个答案:

答案 0 :(得分:1)

您应该使用哈希表,而不是存储线性List(Of Color),这样就可以将Color与计数相关联。然后你最后做一个简单的遍历来发现什么是最高计数

Dim map As New 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 = image.GetPixel(i, j)
    Dim count As Integer
    If Not map.TryGetValue(color, count) Then
      count = 0
    End If
    map(color) = count + 1
  Next
Next

Dim mostColor = map.Max(Function(x) x.Count).Key