PyBox / Blog / How to

OpenCV in Python on Android: use the phone camera

Desktop OpenCV code can read the real phone camera. This is the minimum you need.

OpenCV in Python on Android: use the phone camera: the PyBox screen this guide uses
PyBox is the Python IDE I build. Everything below works with it, and the steps are the same ideas you would use anywhere. Get it on Google Play.

Permissions

During setup PyBox asks for storage, notifications, camera and microphone access. Camera permission is needed for OpenCV to read frames. You can change it later in Android settings.

Install

opencv-python
numpy

Face detection

import cv2

cascade = cv2.CascadeClassifier(
    cv2.data.haarcascades + "haarcascade_frontalface_default.xml"
)
cam = cv2.VideoCapture(0)

while True:
    ok, frame = cam.read()
    if not ok:
        break
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    faces = cascade.detectMultiScale(gray, scaleFactor=1.2, minNeighbors=5)
    for x, y, w, h in faces:
        cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2)
    cv2.imshow("PyBox - face detection", frame)
    if cv2.waitKey(1) & 0xFF == ord("q"):
        break

cam.release()
cv2.destroyAllWindows()

The window opens on the X11 desktop. This is the same code you would run on a laptop, which is the point.

Performance

  • Resize frames before heavy work: cv2.resize(frame, (640, 360)).
  • Detect every other frame, and draw every frame.
  • For neural networks use ONNX Runtime, TensorFlow Lite or NCNN, which can use GPU acceleration.

More about the hardware side on the home page.

Questions

Can OpenCV use the Android camera from Python?

Yes. In PyBox, cv2.VideoCapture(0) reads the camera after you grant permission.

Do I need to install OpenCV separately?

Install it with pip (opencv-python). PyBox provides a prebuilt Android wheel.

Anshuman MishraBuilds PyBox at Vytros, a Python IDE for Android. About the developer.

Code Python on your phone.