Private Sub ButtonUpload_Click(sender As Object, e As EventArgs) Handles ButtonUpload.Click
If OpenFileDialog1.ShowDialog() = DialogResult.OK Then
PictureBox1.Image = Image.FromFile(OpenFileDialog1.FileName)
End If
Dim grayscale As New Imaging.ColorMatrix(New Single()() _
{
New Single() {0.299, 0.299, 0.299, 0, 0},
New Single() {0.587, 0.587, 0.587, 0, 0},
New Single() {0.114, 0.114, 0.114, 0, 0},
New Single() {0, 0, 0, 1, 0},
New Single() {0, 0, 0, 0, 1}
})
Dim bmp As New Bitmap(PictureBox1.Image)
Dim imgattr As New Imaging.ImageAttributes()
imgattr.SetColorMatrix(grayscale)
Using g As Graphics = Graphics.FromImage(bmp)
g.DrawImage(bmp, New Rectangle(0, 0, bmp.Width, bmp.Height),
0, 0, bmp.Width, bmp.Height,
GraphicsUnit.Pixel, imgattr)
End Using
PictureBox1.Image = bmp
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim bmp As New Bitmap(PictureBox1.Image)
Dim visited As New HashSet(Of Point)
Dim blackAreasCount As Integer = 0
For x As Integer = 0 To bmp.Width - 1
For y As Integer = 0 To bmp.Height - 1
If bmp.GetPixel(x, y).ToArgb() = Color.Black.ToArgb() AndAlso Not visited.Contains(New Point(x, y)) Then
blackAreasCount += 1
Fill(bmp, x, y, visited)
End If
Next
Next
Label1.Text = blackAreasCount.ToString()
End Sub
Private Sub Fill(bmp As Bitmap, x As Integer, y As Integer, visited As HashSet(Of Point))
If x < 0 OrElse x >= bmp.Width OrElse y < 0 OrElse y >= bmp.Height Then Return
If visited.Contains(New Point(x, y)) OrElse bmp.GetPixel(x, y).ToArgb() <> Color.Black.ToArgb() Then Return
' Mark the current pixel as visited
visited.Add(New Point(x, y))
' Recursively fill the neighboring pixels
Fill(bmp, x - 1, y, visited)
Fill(bmp, x + 1, y, visited)
Fill(bmp, x, y - 1, visited)
Fill(bmp, x, y + 1, visited)
End Sub