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.objdetect.CascadeClassifier 7 import reflect._ 8 9 /* 10 * Detects faces in an image, draws boxes around them, and writes the results 11 * to "scalaFaceDetection.png". 12 */ 13 object ScalaDetectFaceDemo { 14 def run() { 15 println(s"\nRunning ${classTag[this.type].toString.replace("$", "")}") 16 17 // Create a face detector from the cascade file in the resources directory. 18 val faceDetector = new CascadeClassifier(getClass.getResource("/lbpcascade_frontalface.xml").getPath) 19 val image = Imgcodecs.imread(getClass.getResource("/AverageMaleFace.jpg").getPath) 20 21 // Detect faces in the image. 22 // MatOfRect is a special container class for Rect. 23 val faceDetections = new MatOfRect 24 faceDetector.detectMultiScale(image, faceDetections) 25 26 println(s"Detected ${faceDetections.toArray.size} faces") 27 28 // Draw a bounding box around each face. 29 for (rect <- faceDetections.toArray) { 30 Imgproc.rectangle( 31 image, 32 new Point(rect.x, rect.y), 33 new Point(rect.x + rect.width, 34 rect.y + rect.height), 35 new Scalar(0, 255, 0)) 36 } 37 38 // Save the visualized detection. 39 val filename = "scalaFaceDetection.png" 40 println(s"Writing ${filename}") 41 assert(Imgcodecs.imwrite(filename, image)) 42 } 43 } 44