Visual Basic进程嵌套循环像这样很慢,还是我的代码有其他问题?

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Visual Basic进程嵌套循环像这样很慢,还是我的代码有其他问题?相关的知识,希望对你有一定的参考价值。

[基本上,我试图遍历图片的每个像素,并对照另一张图片的每个像素进行检查。问题在于它似乎执行起来非常缓慢(我无法再与打开的窗口进行交互,并且Debug.WriteLine起作用)。我想确定这是问题所在,而不是我的代码有问题。

[monPiccrop在我的代码顶部被暗化为位图。

Private Sub BtnCheck_Click(sender As Object, e As EventArgs) Handles btnCheck.Click
        monPic = New Bitmap("../../../../" & picNum & ".png")
        crop = New Bitmap("../../../../mm.png")
        For x As Integer = 0 To monPic.Width - 1
            Debug.WriteLine("level 1")
            For y As Integer = 0 To monPic.Height - 1
                Debug.WriteLine("level 2")
                If CInt(monPic.GetPixel(x, y).A) <> 0 Then
                    For x2 As Integer = 0 To crop.Width - 1
                        Debug.WriteLine("level 3")
                        For y2 As Integer = 0 To crop.Height - 1
                            Debug.WriteLine("level 4")
                            If monPic.GetPixel(x, y).R = crop.GetPixel(x2, y2).R And monPic.GetPixel(x, y).G = crop.GetPixel(x2, y2).G And monPic.GetPixel(x, y).B = crop.GetPixel(x2, y2).B Then matches += 1
                        Next y2
                    Next x2
                End If
            Next y
        Next x
        lblMatches.Text = CStr(matches)
    End Sub
答案

这很快。需要

Imports System.Security.Cryptography

将两个位图转换为字节数组,然后使用Sha256进行哈希处理。比较哈希。

改编自https://www.codeproject.com/Articles/9299/Comparing-Images-using-GDI

Private Function Compare(bmp1 As Bitmap, bmp2 As Bitmap) As String
    Dim result = "It's a match!"
    If Not (bmp1.Size = bmp2.Size) Then
        result = "It's not even the same size"
    Else
        Dim ic As New ImageConverter
        Dim btImage1(0) As Byte
        btImage1 = CType(ic.ConvertTo(bmp1, btImage1.GetType), Byte())
        Dim btImage2(0) As Byte
        btImage2 = CType(ic.ConvertTo(bmp2, btImage2.GetType), Byte())
        Dim shaM As New SHA256Managed
        Dim hash1 = shaM.ComputeHash(btImage1)
        Dim hash2 = shaM.ComputeHash(btImage2)
        Dim i As Integer = 0
        Do While i < hash1.Length AndAlso i < hash2.Length AndAlso result = "It's a match!"
            If hash1(i) <> hash2(i) Then
                result = "The pixels don't match"
            End If
            i = (i + 1)
        Loop
    End If
    Return result
End Function

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Dim png1 As New Bitmap(path1)
    Dim png2 As New Bitmap(path2)
    Dim message = Compare(png1, png2)
    MessageBox.Show(message)
End Sub

以上是关于Visual Basic进程嵌套循环像这样很慢,还是我的代码有其他问题?的主要内容,如果未能解决你的问题,请参考以下文章

在 Visual Basic 中使用循环打印平方数

Visual Basic while 循环语法

visual C++ 创建一个窗口却无法显示窗口的原因是啥?

Visual Basic 中的 For-Next 循环

连接到 AD 的奇怪错误 - visual basic

如何使用Visual Studio 2017在Windows窗体应用程序中查看和编辑Visual Basic Power Pack形状?