Display WebCam Image Using OpenCV in Scala Language
July 14, 2017
In this short example, we will use Scala language to retrieve webcam image with OpenCV SBT library.
Prerequisites
- Please make sure both Scala and SBT are installed on your system. Please follow my tutorial post here to install. This is applicable for both Raspberry Pi or any Linux system.
Reference
- Library from bytedeco
Complete project
- You can also download/clone the complete project from github.
SBT Plugin
I am using scala version 2.12.2
. I added the plugin in project/plugins.sbt
as addSbtPlugin("org.bytedeco" % "sbt-javacv" % "1.15")
. And sbt version is 1.0.2
. You can check the latest version in their release from here.
Test Environment
I tested on Ubuntu 16.04.2 using a simple USB webcam. No driver installation.
Example
Before we begin, I must say thank you
to those who write OpenCV plugin for Scala language. We all know that writing code in Scala language is a joy. Let’s begin.
This is just a short program just to prove that the library is easy to setup and get the OpenCV working in a short period of time. Once you run the following code, the JFrame will be prompted with an image from your webcam.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
package example
import org.bytedeco.javacpp.opencv_core._
import org.bytedeco.javacv.FrameGrabber.ImageMode
import org.bytedeco.javacv.{CanvasFrame, Frame, OpenCVFrameGrabber}
object JavaCvExample extends App {
val canvas = new CanvasFrame("Webcam")
canvas.setDefaultCloseOperation(javax.swing.JFrame.EXIT_ON_CLOSE)
val grabber = new OpenCVFrameGrabber(0)
grabber.setBitsPerPixel(CV_8U)
grabber.setImageMode(ImageMode.COLOR)
grabber.start()
val img: Frame = grabber.grab()
canvas.showImage(img)
}
How to run
Assume that you have downloaded/cloned the project, then
If you are using IntelliJ IDE, right click on JavaCvExample
file and then click Run
or Ctrl+Shift+F10
.
If you want to use command line, go to JavaCvScala
folder and type sbt run
.