【问题标题】:Strolling Image - VB.net to get the latest colour漫步图像 - VB.net 获取最新颜色
【发布时间】:2021-03-16 13:52:54
【问题描述】:

需要一些指导,下图是在一个网站上滚动的,从右到左,颜色会在红色或绿色之间变化,每个是 255 个值。我不确定如何在滚动时查看最新的颜色,下面的示例显示红色是最新的,但几秒钟前是绿色。有没有办法说最新的颜色是什么。

我每 2 秒从窗口中取出 BMP 图像,就在显示红色或绿色的文本框之后。我在这里看不到任何类似的示例代码,也看不到谷歌。

任何帮助将不胜感激。 皮特

【问题讨论】:

  • 这里有点猜测,因为您已经在某个时间点对图像进行快照,这只是找到目标像素并检查其颜色的情况。您如何找到目标像素可能是困难的部分,但要考虑非白色像素之类的问题?

标签: vb.net


【解决方案1】:

您可以在位图中搜索目标颜色并将它们添加到Dictionary(Of Color, Point),每当您在更大的X 位置找到关键颜色时,添加或更新字典(点)中每种颜色的值。使用LockBits 方法遍历位图的字节以获得更快和更好的性能。

当字典中填满所需数据后,按其X 属性对值进行降序排序,并返回第一个的键(颜色)。

Imports System.Linq
Imports System.Drawing
Imports System.Drawing.Imaging
Imports System.Runtime.InteropServices

' TODO: Find a better name...
Private Function GetLastColor(bmp As Bitmap, ParamArray colors() As Color) As Color
    If bmp Is Nothing Then Return Color.Empty

    ' To work with 24-bit and 32-bit images...
    Dim bpp = Image.GetPixelFormatSize(bmp.PixelFormat) \ 8
    Dim bmpData = bmp.LockBits(New Rectangle(0, 0, bmp.Width, bmp.Height),
                                ImageLockMode.ReadOnly, bmp.PixelFormat)
    Dim bmpBuff((Math.Abs(bmpData.Stride) * bmpData.Height) - 1) As Byte

    Marshal.Copy(bmpData.Scan0, bmpBuff, 0, bmpBuff.Length)

    bmp.UnlockBits(bmpData)

    Dim c As Color
    Dim i As Integer
    Dim dict As New Dictionary(Of Color, Point)

    For y = 0 To bmp.Height - 1
        For x = 0 To bmp.Width - 1
            i = y * bmpData.Stride + x * bpp
            c = Color.FromArgb(bmpBuff(i + 2), bmpBuff(i + 1), bmpBuff(i))

            ' Or color.ToArgb() = c.ToArgb() ...
            If colors.Any(Function(color) Color.op_Equality(color, c)) Then
                Dim p = New Point(x, y)

                If Not dict.ContainsKey(c) Then
                    dict.Add(c, p)
                ElseIf x > dict(c).X Then
                    dict(c) = p
                End If
            End If
        Next
    Next

    If dict.Count > 0 Then
        Return dict.OrderByDescending(Function(x) x.Value.X).First().Key
    Else
        Return Color.Empty
    End If
End Function

用法:

Sub Caller()
    Dim c As Color = GetLastColor(
        SomeBmp,
        Color.FromArgb(255, 0, 0),
        Color.FromArgb(0, 255, 0),
        Color.FromArgb(0, 0, 255))

    ' TODO: ...
End Sub

这是一个演示,每两秒创建一个图像,并在随机位置用随机颜色填充小矩形。最后一个矩形是带圆圈的。

【讨论】:

    猜你喜欢
    • 2011-05-24
    • 2010-12-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-16
    • 2013-07-21
    • 1970-01-01
    • 2019-07-27
    相关资源
    最近更新 更多