Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Tetragramm
GitHub Repository: Tetragramm/opencv
Path: blob/master/samples/java/sbt/src/main/scala/ScalaDetectFaceDemo.scala
16354 views
1
import org.opencv.core.Core
2
import org.opencv.core.MatOfRect
3
import org.opencv.core.Point
4
import org.opencv.core.Scalar
5
import org.opencv.imgcodecs.Imgcodecs
6
import org.opencv.imgproc.Imgproc
7
import org.opencv.objdetect.CascadeClassifier
8
import reflect._
9
10
/*
11
* Detects faces in an image, draws boxes around them, and writes the results
12
* to "scalaFaceDetection.png".
13
*/
14
object ScalaDetectFaceDemo {
15
def run() {
16
println(s"\nRunning ${classTag[this.type].toString.replace("$", "")}")
17
18
// Create a face detector from the cascade file in the resources directory.
19
val faceDetector = new CascadeClassifier(getClass.getResource("/lbpcascade_frontalface.xml").getPath)
20
val image = Imgcodecs.imread(getClass.getResource("/AverageMaleFace.jpg").getPath)
21
22
// Detect faces in the image.
23
// MatOfRect is a special container class for Rect.
24
val faceDetections = new MatOfRect
25
faceDetector.detectMultiScale(image, faceDetections)
26
27
println(s"Detected ${faceDetections.toArray.size} faces")
28
29
// Draw a bounding box around each face.
30
for (rect <- faceDetections.toArray) {
31
Imgproc.rectangle(
32
image,
33
new Point(rect.x, rect.y),
34
new Point(rect.x + rect.width,
35
rect.y + rect.height),
36
new Scalar(0, 255, 0))
37
}
38
39
// Save the visualized detection.
40
val filename = "scalaFaceDetection.png"
41
println(s"Writing ${filename}")
42
assert(Imgcodecs.imwrite(filename, image))
43
}
44
}
45
46