1

I have been trying to make an android apk in kivy to access mobile camera through opencv, but my application crashes in my phone. It is probably not able to access my phone's camera!

import imp
from kivymd.app import MDApp
from kivymd.uix.boxlayout import MDBoxLayout
from kivymd.uix.button import MDRaisedButton
from kivy.uix.image import Image
from kivy.clock import Clock
import cv2
from kivy.graphics.texture import Texture

class MainApp(MDApp):
    def build(self):
        layout = MDBoxLayout(orientation='vertical')
        self.image = Image()
        layout.add_widget(self.image)
        layout.add_widget(MDRaisedButton(
            text='Click Here',
            pos_hint={'center_x':.5,'center_y':.5},
            size_hint=(None,None))
        )
        self.capture=cv2.VideoCapture(0)
        Clock.schedule_interval(self.load_video, 1.0/30.0)
        return layout
    def load_video(self, *args):
        ret, frame= self.capture.read()
        self.frame=frame
        buffer=cv2.flip(frame, 0).tostring()
        texture=Texture.create(size=(frame.shape[1],frame.shape[0]),colorfmt='bgr')
        texture.blit_buffer(buffer, colorfmt='bgr',bufferfmt='ubyte')
        self.image.texture=texture


if __name__ == '__main__':
    MainApp().run()

Also the changes I have made in my buildozer.spec folder are as follows:

changes made in buildozer.spec

James Z
  • 12,209
  • 10
  • 24
  • 44
Arfa Nisar
  • 11
  • 2
  • 1
    you need to use kivy methods to access the camera. OpenCV with python doesn't know what android is. – Christoph Rackwitz Feb 19 '22 at 15:20
  • first you should try standard Kivy widget for camera: [Camera Example](https://kivy.org/doc/stable/examples/gen__camera__main__py.html) – furas Feb 19 '22 at 15:42
  • I have used this code that you mentioned, but now when I open the application it shows a blank screen! What would be the solution to this issue? @furas – Arfa Nisar Feb 21 '22 at 04:39

1 Answers1

1

You need to change opencv version to at least 4.5.2 in p4a's recipe. OpenCV <= 4.5.1 does not support camera on Android. For more info see answer https://stackoverflow.com/a/69445715 here Cannot open camera using cv2.VideoCapture(0) in android phones

Using OpenCV < 4.5.2, your ret, frame= self.capture.read() returns (False, None) and then you get an Exception accessing some methods of None.