Click here to Skip to main content
14,641,113 members
Articles » Mobile Development » Android » General
Posted 27 Feb 2013

Tagged as


84 bookmarked

Real-Time Computer Vision on Android using BoofCV

Rate this:
4.90 (30 votes)
Please Sign up or sign in to vote.
4.90 (30 votes)
21 Jan 2014CPOL
A simple tutorial on how to create an application on Android which processes video in real-time.

Image 1

Colorized image gradient displayed on an Android cell phone.


In this article, a step by step tutorial will be given for writing a simple computer vision application on Android devices using BoofCV. At the end of the tutorial, you will know how to process a video feed, compute the image gradient, visualize the gradient, and display the results. For those of you who don't know, BoofCV is an open source computer vision library written in Java, making it a natural fit for Android devices.

Most of this article is actually going to deal with the Android API, which is a bit convoluted when it comes to video streams. Using BoofCV on Android is very easy and requires no modification or native code. It has become even easier to use since BoofCV v0.13 was released, with its improved Android integration package.

Before we start, here are some quick links to help familiarize you with BoofCV and its capabilities. I'm assuming that you are already familiar with Android and the basics of Android development.

The source code for this tutorial can be downloaded from the link at the top. This project is entirely self contained and has all the libraries you will need.


Since this article was first posted (February 2013), it has been modified (January 2014) to address the issues raised by "Member 4367060", see discussion below. While the effects of these changes are not readily apparent due to how the project is configured, it is more correct and can be applied to other configurations with fewer problems.

  • Application can now be loaded onto Nexus 7 devices
  • Front facing images are flipped for correct viewing
  • Fixed bug where camera capture doesn't start again if surfaceCreated isn't called

BoofCV on Android

As previously mentioned, BoofCV is a Java library, which means the library does not need to be recompiled for Android. Jars found on its download page can be used without modification. For Android specific functions, make sure you include the BoofCVAndroid.jar, which is part of the standard jar download or can be compiled by yourself. See project website for additional instructions.

The key to writing fast computer vision code on Android is efficient conversion between image formats. Using RGB accessor functions in Bitmap is painfully slow and there is no good build in way to convert NV21 (video image format). This is where the Android integration package comes in. It contains two classes which will make your life much easier.

  • ConvertBitmap
  • ConvertNV21

Use those classes to convert from Android image types into BoofCV image types. Here are some usage examples:

// Easiest way to convert a Bitmap into a BoofCV type
ImageUInt8 image = ConvertBitmap.bitmapToGray(bitmap, (ImageUInt8)null, null); 
// From NV21 to gray scale

Capturing Video on Android

On Android, you capture a video stream by listening in on the camera preview. To make matters more interesting, they try to force you to display a preview at all times. Far from the best API that I've seen for capturing video streams, but it's what we have to work with. If you haven't downloaded the example code, now would be a good time to do so.

Video on Android Steps:

  1. Open and configure camera
  2. Create SurfaceHolder to display camera preview
  3. Add view on top of the camera preview view for display purposes
  4. Provide a listener for the camera's preview
  5. Start camera preview
  6. Perform expensive calculations in a separate thread
  7. Render results

Before you can access the camera, you must first add the following to AndroidManifest.xml.

<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="" android:required="false" />
<uses-feature android:name="" android:required="false" /> 

If this is a computer vision application, which must use a camera to work, why is it told not to require a camera? Turns out that if you tell it to require a camera, then you will exclude devices (such as a tablet) from the Play store with only one forward-facing camera! In newer version of Android OS, there is apparently some way to get around this issue.

Take a look at Several important activities take place in onCreate() and onResume().

  1. View for displaying the camera preview is created and configured.
  2. View for rendering the output is added.
  3. The camera is opened and configured.
public void onCreate(Bundle savedInstanceState) {


    // Used to visualize the results
    mDraw = new Visualization(this);

    // Create our Preview view and set it as the content of our activity.
    mPreview = new CameraPreview(this,this,true);

    FrameLayout preview = (FrameLayout) findViewById(;


protected void onResume() {

The variable mPreview, which is an instance of CameraPreview (discussed below), is required to capture video images. mDraw draws our output on the screen. FrameLayout allows two views to be placed on top of each other, which is exactly what's being done above.

Configuring the Camera

In 'VideoActivity.onCreate()' it invokes the setUpAndConfigureCamera() function. This function opens a camera using <code>selectAndOpenCamera(), configures it to take a smaller preview image, starts a thread for processing the video, and passes the camera to mPreview.

private void setUpAndConfigureCamera() {
    // Open and configure the camera
    mCamera = selectAndOpenCamera();

    Camera.Parameters param = mCamera.getParameters();

    // Select the preview size closest to 320x240
    // Smaller images are recommended because some computer vision operations are very expensive
    List<Camera.Size> sizes = param.getSupportedPreviewSizes();
    Camera.Size s = sizes.get(closest(sizes,320,240));

    // declare image data

    // start image processing thread
    thread = new ThreadProcess();

    // Start the video feed by passing it to mPreview

A good practice when dealing with video images on Android is to minimize the amount of time spent in the preview call back. If your process takes too long, it will cause a backlog and cause a crash. Which is why we start a new thread in the above function. The very last line in the function passes the camera to mPreview so that the preview can be displayed and the video stream started.

Why not just call instead of <code>selectAndOpenCamera()? will only return the first back-facing camera on the device. In order to support tablets, with only a forward-facing camera, we examine all the cameras and return the first back-facing camera or any forward-facing one we find. Also note that flipHorizontal is set to true for forward-facing cameras. This is required for them to be viewed correctly.

private Camera selectAndOpenCamera() {
    Camera.CameraInfo info = new Camera.CameraInfo();
    int numberOfCameras = Camera.getNumberOfCameras();
    int selected = -1;

    for (int i = 0; i < numberOfCameras; i++) {
        Camera.getCameraInfo(i, info);

        if( info.facing == Camera.CameraInfo.CAMERA_FACING_BACK ) {
            selected = i;
            flipHorizontal = false;
        } else {
            // default to a front facing camera if a back facing one can't be found
            selected = i;
           flipHorizontal = true;

    if( selected == -1 ) {
        return null; // won't ever be called
    } else {

Camera Preview View's task is to placate Android and "display" the camera preview so that it will start streaming. Android requires that the camera preview be displayed no matter what.

CameraPreview can display the preview or hide it by making it really small. It's also smart enough to adjust the display size so that the original camera image's aspect ratio is maintained. For the sake of brevity, a skeleton of CameraPreview is shown below. See code for details.

public class CameraPreview extends ViewGroup implements SurfaceHolder.Callback {
    CameraPreview(Context context, Camera.PreviewCallback previewCallback, boolean hidden ) {
        // provide context, camera callback function and specify if the preview should be hidden
        // Create the surface for displaying the preview
        mSurfaceView = new SurfaceView(context);
        // Install a SurfaceHolder.Callback so we get notified when the
        // underlying surface is created and destroyed.
        mHolder = mSurfaceView.getHolder();
        // deprecated setting, but required on Android versions prior to 3.0
    public void setCamera(Camera camera) {
        if (mCamera != null) {
            // Without calling startPreview() here the video will not
            // wake up under certain conditions
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        // adjusts the setMeasuredDimension to hide the preview 
        // or ensure that has the correct aspect ratio
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        // adjust the size of the layout so that the aspect ratio is maintained

    public void surfaceCreated(SurfaceHolder holder) {

    protected void startPreview() {

Processing the Camera Preview

Each time a new frame has been captured by the camera, the function below will be called. The function is defined in VideoActivity, but a reference is passed to CameraPreview since it handles initialization of the preview. The amount of processing done in this function is kept to the bare minimum to avoid causing a backlog.

 * Called each time a new image arrives in the data stream.
public void onPreviewFrame(byte[] bytes, Camera camera) {
    // convert from NV21 format into gray scale
    synchronized (lockGray) {
    // Can only do trivial amounts of image processing inside this function or else bad stuff happens.
    // To work around this issue most of the processing has been pushed onto a thread and the call below
    // tells the thread to wake up and process another image

The last line in onPreviewFrame() invokes thread.interrupt(), which will wake up the image processing thread, see the next code block. Note the care that is taken to avoid having onPreviewFrame() and run() manipulate the same image data at the same time since they are run in different threads.

public void run() {
    while( !stopRequested ) {
        // Sleep until it has been told to wake up
        synchronized ( Thread.currentThread() ) {
            try {
            } catch (InterruptedException ignored) {}
        // process the most recently converted image by swapping image buffered
        synchronized (lockGray) {
            ImageUInt8 tmp = gray1;
            gray1 = gray2;
            gray2 = tmp;

       if( flipHorizontal )

        // process the image and compute its gradient
        // render the output in a synthetic color image
        synchronized ( lockOutput ) {
    running = false;

As mentioned above, all of the more expensive image processing operations are done in this thread. The computations in this example are actually minimal, but they are done in their own thread for the sake of demonstrating best practices. After the image is done being processed, it will inform the GUI that it should update the display by calling mDraw.postInvalidate(). The GUI thread will then wake up and draw our image on top of the camera preview.

This function is also where BoofCV does its work. Gradient computes the image gradient and was declared earlier, as is shown below. After the image gradient has been computed, it's visualized using BoofCV's VisualizeImageData class. That's it for BoofCV in this example.

ImageGradient<ImageUInt8,ImageSInt16> gradient =
     FactoryDerivative.three(ImageUInt8.class, ImageSInt16.class);

Visualization Display

After the preview has been processed, the results are displayed. The thread discussed above updates a Bitmap image 'output' which is displayed in the view below. Note how the threads are careful to avoid stepping on each others feet when reading/writing to 'output'.

 * Draws on top of the video stream for visualizing computer vision results
private class Visualization extends SurfaceView {
    Activity activity;
    public Visualization(Activity context ) {
        this.activity = context;
        // This call is necessary, or else the
        // draw method will not be called.
    protected void onDraw(Canvas canvas){
        synchronized ( lockOutput ) {
            int w = canvas.getWidth();
            int h = canvas.getHeight();
            // fill the window and center it
            double scaleX = w/(double)output.getWidth();
            double scaleY = h/(double)output.getHeight();
            double scale = Math.min(scaleX,scaleY);
            double tranX = (w-scale*output.getWidth())/2;
            double tranY = (h-scale*output.getHeight())/2;
            // draw the image


Now you know how to perform computer vision using a video stream on the Android platform with BoofCV! Let me know if you have questions or comments.


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

United States United States
Peter Abeles is a researcher in robotics and computer vision. In addition he is the author of several open source projects which include BoofCV, EJML, and JMatBench. His neglected blog can be found at

Comments and Discussions

QuestionGet Color Image Pin
Member 1200630324-Sep-15 3:38
MemberMember 1200630324-Sep-15 3:38 
AnswerRe: Get Color Image Pin
lessthanoptimal24-Sep-15 6:02
Memberlessthanoptimal24-Sep-15 6:02 
GeneralRe: Get Color Image Pin
Member 1200630327-Sep-15 22:47
MemberMember 1200630327-Sep-15 22:47 
GeneralRe: Get Color Image Pin
lessthanoptimal28-Sep-15 17:26
Memberlessthanoptimal28-Sep-15 17:26 
GeneralRe: Get Color Image Pin
Member 1200630329-Sep-15 2:36
MemberMember 1200630329-Sep-15 2:36 
QuestionBackground Processing Pin
Assem Marwan5-Dec-14 3:34
MemberAssem Marwan5-Dec-14 3:34 
QuestionWhy do you use thread.interrupt() in onPreviewFrame() instead of notifyAll() Pin
wenhuixiang28-Feb-14 2:21
Memberwenhuixiang28-Feb-14 2:21 
QuestionIM trying to do tracking using We are trying to do tracking using Multi spectral <ImageU8> type images using images stitching and tracking methods available in Boofcv but we are not able to achieve this. Pin
mehran_5815-Dec-13 7:50
Membermehran_5815-Dec-13 7:50 
QuestionRE: two suggestions to a great article Pin
Member 436706024-Apr-13 7:42
MemberMember 436706024-Apr-13 7:42 
AnswerRe: RE: two suggestions to a great article Pin
lessthanoptimal24-Apr-13 12:06
Memberlessthanoptimal24-Apr-13 12:06 
GeneralRe: RE: two suggestions to a great article Pin
Member 436706028-Apr-13 23:41
MemberMember 436706028-Apr-13 23:41 
GeneralRe: RE: two suggestions to a great article Pin
lessthanoptimal30-Apr-13 17:03
Memberlessthanoptimal30-Apr-13 17:03 
GeneralRe: RE: two suggestions to a great article Pin
Member 43670602-May-13 0:19
MemberMember 43670602-May-13 0:19 
GeneralRe: RE: two suggestions to a great article Pin
lessthanoptimal2-May-13 13:42
Memberlessthanoptimal2-May-13 13:42 
AnswerMessage Closed Pin
29-Aug-14 4:23
MemberMember 1098535829-Aug-14 4:23 
SuggestionTwo suggestions to a great article! Pin
Member 436706023-Apr-13 0:21
MemberMember 436706023-Apr-13 0:21 
GeneralRe: Two suggestions to a great article! Pin
lessthanoptimal24-Apr-13 6:22
Memberlessthanoptimal24-Apr-13 6:22 
Bugcompiling fine, but when running it crash... Pin
target3331-Mar-13 7:32
Membertarget3331-Mar-13 7:32 
GeneralRe: compiling fine, but when running it crash... Pin
lessthanoptimal31-Mar-13 9:25
Memberlessthanoptimal31-Mar-13 9:25 
GeneralRe: compiling fine, but when running it crash... Pin
target3331-Mar-13 11:15
Membertarget3331-Mar-13 11:15 
GeneralRe: compiling fine, but when running it crash... Pin
lessthanoptimal31-Mar-13 13:10
Memberlessthanoptimal31-Mar-13 13:10 
GeneralRe: compiling fine, but when running it crash... Pin
target331-Apr-13 3:35
Membertarget331-Apr-13 3:35 
GeneralRe: compiling fine, but when running it crash... Pin
lessthanoptimal1-Apr-13 7:29
Memberlessthanoptimal1-Apr-13 7:29 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.