Sub DetectFaces
' Save the image from Canvas to disk
Dim Out As OutputStream = File.OpenOutput(File.DirApp, "1.jpg", False)
canvas.Snapshot.WriteToStream(Out)
Out.Close
' Load the image
Dim imgs As JavaObject
imgs.InitializeNewInstance("org.opencv.core.Mat", Null)
Dim imgcodecs As JavaObject
imgcodecs.InitializeStatic("org.opencv.imgcodecs.Imgcodecs")
imgs = imgcodecs.RunMethod("imread", Array(File.Combine(File.DirApp, "1.jpg")))
' Check if the image was loaded correctly
If imgs.RunMethod("empty", Null) Then
Log("Image not loaded.")
Return
End If
' Load face classifier
Dim faceCascade As JavaObject
Dim xmlPath As String = File.Combine(File.DirApp, "haarcascade_frontalface_default.xml")
faceCascade.InitializeNewInstance("org.opencv.objdetect.CascadeClassifier", Null)
faceCascade.RunMethod("load", Array(xmlPath))
' Detect faces
Dim faceDetections As JavaObject
faceDetections.InitializeNewInstance("org.opencv.core.MatOfRect", Null)
faceCascade.RunMethod("detectMultiScale", Array(imgs, faceDetections))
' Process detections and draw rectangles
Private facesDetected As Map : facesDetected.Initialize
Dim facesArray() As Object = faceDetections.RunMethod("toArray", Null)
Dim count As Int = 0
For Each face As JavaObject In facesArray
count = count + 1
Log("Face detected at: x=" & face.GetField("x") & " y=" & face.GetField("y") & " width=" & face.GetField("width") & " height=" & face.GetField("height"))
canvas.DrawRect(face.GetField("x"), face.GetField("y"), face.GetField("width"), face.GetField("height"), fx.Colors.Green, False, 2)
Private faceId As String = $"people${canvas.Tag}Face${count}"$
facesDetected.Put(faceId, CreateMap("x": face.GetField("x"), "y": face.GetField("y"), "width": face.GetField("width"), "height": face.GetField("height")))
Log(faceId)
' Crop and save face
Dim x As Int = face.GetField("x")
Dim y As Int = face.GetField("y")
Dim width As Int = face.GetField("width")
Dim height As Int = face.GetField("height")
Dim faceMat As JavaObject = imgs.RunMethod("submat", Array(y, y + height, x, x + width))
Dim faceImgCodecs As JavaObject
faceImgCodecs.InitializeStatic("org.opencv.imgcodecs.Imgcodecs")
Dim faceFileName As String = File.Combine(File.DirApp, faceId & ".jpg")
faceImgCodecs.RunMethod("imwrite", Array(faceFileName, faceMat))
Next
Log("Total faces detected: " & facesArray.Length)
'Log(facesDetected)
End Sub