,

OpenCV for Android: Show the Camera and Switch Between Front and Back Cameras

OpenCV for Android: Show the Camera and Switch Between Front and Back Cameras
Part 2 of 5 OpenCV for Android
  1. OpenCV for Android in 2026: Set Up OpenCV 4 in Android Studio the Easy Way
  2. OpenCV for Android: Show the Camera and Switch Between Front and Back Cameras
  3. OpenCV for Android: Apply Live Color Filters to the Camera (Grayscale, Sepia, Invert, Edges)
  4. OpenCV for Android: Capture and Save Photos from the Camera
  5. OpenCV for Android: Draw a Box and Text on the Live Camera

In this part we build the screen the rest of the series uses: a full-screen live camera preview powered by OpenCV, plus a menu button that switches between the back and front cameras. Every frame passes through our code, which is what lets us add filters and drawings in the next parts.

You need the project from the previous part, with OpenCV added through Gradle and the camera permission in the manifest.

Step 1: Add the camera view to the layout

Replace res/layout/activity_main.xml with an OpenCV JavaCameraView that fills the screen:

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:opencv="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <org.opencv.android.JavaCameraView
        android:id="@+id/camera_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        opencv:show_fps="true"
        opencv:camera_id="back" />

</FrameLayout>

Step 2: Create the menu

Create res/menu/main_menu.xml (right-click res → New → Android Resource File, type Menu):

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:id="@+id/action_switch_camera"
        android:title="Switch camera"
        android:showAsAction="ifRoom" />
</menu>

Step 3: Give the activity an action bar and a landscape screen

Our activity will extend OpenCV’s CameraActivity, which is a plain Android Activity. New projects use a theme without an action bar, so the menu would have nowhere to appear. In AndroidManifest.xml, give the activity a framework theme with an action bar, and lock it to landscape so the preview is the right way up:

<activity
    android:name=".MainActivity"
    android:exported="true"
    android:screenOrientation="landscape"
    android:theme="@android:style/Theme.Material">
    <!-- keep the existing intent-filter here -->
</activity>

Step 4: Write the activity

Replace MainActivity.java with the code below. CameraActivity asks for the camera permission for us, and CvCameraViewListener2 gives us every frame as an OpenCV Mat.

import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.SurfaceView;
import android.view.WindowManager;

import org.opencv.android.CameraActivity;
import org.opencv.android.CameraBridgeViewBase;
import org.opencv.android.OpenCVLoader;
import org.opencv.core.Core;
import org.opencv.core.Mat;

import java.util.Collections;
import java.util.List;

public class MainActivity extends CameraActivity
        implements CameraBridgeViewBase.CvCameraViewListener2 {

    private static final String TAG = "OpenCVCamera";
    private CameraBridgeViewBase cameraView;
    private int cameraIndex = CameraBridgeViewBase.CAMERA_ID_BACK;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (!OpenCVLoader.initLocal()) {
            Log.e(TAG, "OpenCV failed to load");
            finish();
            return;
        }
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        setContentView(R.layout.activity_main);

        cameraView = findViewById(R.id.camera_view);
        cameraView.setVisibility(SurfaceView.VISIBLE);
        cameraView.setCvCameraViewListener(this);
    }

    @Override
    protected List<? extends CameraBridgeViewBase> getCameraViewList() {
        return Collections.singletonList(cameraView);
    }

    @Override
    public void onResume() {
        super.onResume();
        if (cameraView != null) cameraView.enableView();
    }

    @Override
    public void onPause() {
        super.onPause();
        if (cameraView != null) cameraView.disableView();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (cameraView != null) cameraView.disableView();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main_menu, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == R.id.action_switch_camera) {
            cameraIndex = (cameraIndex == CameraBridgeViewBase.CAMERA_ID_BACK)
                    ? CameraBridgeViewBase.CAMERA_ID_FRONT
                    : CameraBridgeViewBase.CAMERA_ID_BACK;
            cameraView.disableView();
            cameraView.setCameraIndex(cameraIndex);
            cameraView.enableView();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onCameraViewStarted(int width, int height) { }

    @Override
    public void onCameraViewStopped() { }

    @Override
    public Mat onCameraFrame(CameraBridgeViewBase.CvCameraViewFrame inputFrame) {
        Mat rgba = inputFrame.rgba();
        if (cameraIndex == CameraBridgeViewBase.CAMERA_ID_FRONT) {
            Core.flip(rgba, rgba, 1); // mirror the front camera like a selfie
        }
        return rgba;
    }
}

How it works

  • getCameraViewList() tells CameraActivity which views need the camera, so it can request the permission and switch them on once you allow it.
  • enableView() / disableView() open and release the camera. We release it in onPause() so other apps can use it.
  • Switching cameras means stopping the view, changing the camera index and starting it again.
  • onCameraFrame() runs for every frame. Whatever Mat you return is what appears on screen. Here we only mirror the front camera with Core.flip().

Run it

Run the app, allow the camera permission, and tap Switch camera in the action bar. The preview jumps between the back and front cameras, and the FPS counter in the corner shows how fast frames are processed.

Next, we will use onCameraFrame() to apply live colour filters such as grayscale, sepia, invert and edge detection.

Written by

GitHub · About Codeonion · Contact

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

>> Related articles

all articles →