Python Forum
Kivy App - Python3 script to Android app (opencv)
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Kivy App - Python3 script to Android app (opencv)
#1
Hello all, i am Jayson...
I have really gotten into flask because of this forum and am also starting to make android apps with my scripts
in P4a w buildozer.
right now i have made a dual or Two Cam solution for cell phones.......
when i run it in termux it cannot get permissions to access /dev/0 or anything
so i made it an app.

here is the script for having two webcams or a cell phone....
however i have a probem.... remember...it doesnt exit good a lot with the movie compiled in time.
from flask import Flask, Response, request, render_template, redirect, url_for
import cv2
import numpy as np

app = Flask(__name__)
@app.route('/')
def fishmap():
    def output():
        yield """<html>Android TWO CAM...</html>"""
        cap = cv2.VideoCapture(0)
        cap1 = cv2.VideoCapture(1)
        out = cv2.VideoWriter('output.avi',cv2.VideoWriter_fourcc(*'XVID'), cap.get(cv2.CAP_PROP_FPS), (1440,720))
        while(cap.isOpened()):
            ret, frame = cap.read()
            ret1, frame1 = cap1.read()
            if ret == True:
                print (frame)
                reframe = cv2.resize(frame,(720, 720), interpolation = cv2.INTER_AREA)
                reframe1 = cv2.resize(frame1,(720, 720), interpolation = cv2.INTER_AREA)
                both = np.column_stack((reframe, reframe1))
                out.write(both)
                cv2.imshow('Frame', both)
                if cv2.waitKey(1) & 0xFF == ord('q'):
                    break
            else: 
                break
        cap.release()
        cap1.release()
        out.release()
        cv2.waitKey(0)
        cv2.destroyAllWindows()
    return Response(output())
if __name__ == "__main__":  
    app.run(host='0.0.0.0', debug=True, port=80)
Reply
#2
OMG everyone....i made it a kivy app.

here it is ....working!!!! out here in Oc Ca.
   
main.py
import kivy
from kivy.app import App
from kivy.uix.label import Label
import cv2
import numpy as np
from multiprocessing import Process

class MyLabelApp(App):
    def build(self):
        lbl = Label(text ="Android Two Cam Is running, Close window and save ouput.avi locally!!!")
        return lbl
def cap():
    cap = cv2.VideoCapture(0)
    cap1 = cv2.VideoCapture(2)
    out = cv2.VideoWriter('/storage/emulated/0/dcim/output.avi',cv2.VideoWriter_fourcc(*'XVID'), cap.get(cv2.CAP_PROP_FPS), (1440,7>
    while(cap.isOpened()):
        ret, frame = cap.read()
        ret1, frame1 = cap1.read()
        if ret == True:
            reframe = cv2.resize(frame,(720, 720), interpolation = cv2.INTER_AREA)
            reframe1 = cv2.resize(frame1,(720, 720), interpolation = cv2.INTER_AREA)
            both = np.column_stack((reframe, reframe1))
            out.write(both)
        else: 
            break
    cap.release()
    cap1.release()
    out.release()
    cv2.waitKey(0)

if __name__ == "__main__":
    p1 = Process(target=cap)
    p1.start()
    label = MyLabelApp()
    label.run()
    label.on_stop(p1.terminate())
###################################
How to build Python for Android (buildozer) to make and android app from a python kivy script with opencv
sudo apt update && sudo apt install zip unzip && sudo apt install software-properties-common && \
    sudo add-apt-repository ppa:deadsnakes/ppa && \
    sudo apt install python3.9 && \
    alias python3=python3.9


sudo apt-get install -y \
    python3-pip \
    build-essential \
    git \
    python3-dev \
    ffmpeg \
    libsdl2-dev \
    libsdl2-image-dev \
    libsdl2-mixer-dev \
    libsdl2-ttf-dev \
    libportmidi-dev \
    libswscale-dev \
    libavformat-dev \
    libavcodec-dev \
    zlib1g-dev
   
sudo dpkg --add-architecture i386 && \
sudo apt-get update && \
sudo apt-get install -y build-essential ccache git zlib1g-dev libncurses5:i386 libstdc++6:i386 zlib1g:i386 openjdk-8-jdk unzip ant ccache autoconf libtool libssl-dev

sudo update-alternatives --config java
#select 2 jdk-8

sudo pip install buildozer cython==0.29.19 cefpython3 && \
sudo pip install git+https://github.com/kivy/python-for-android.git    

sudo apt-get install -y \
    libgstreamer1.0 \
    gstreamer1.0-plugins-base \
    gstreamer1.0-plugins-good
   
sudo apt-get install build-essential libsqlite3-dev sqlite3 bzip2 libbz2-dev zlib1g-dev libssl-dev openssl libgdbm-dev libgdbm-compat-dev liblzma-dev libreadline-dev libncursesw5-dev libffi-dev uuid-dev


sudo apt update

buildozer init

sudo nano buildozer.spec
buildozer.spec
[[app]
title = Android Two Cam
package.name = TwoCam
package.domain = TwoCam.lftr.biz
source.dir = .
source.include_exts = py,png,jpg,kv,atlas
version = 0.1
requirements = python3,kivy,opencv==4.7.0,numpy
orientation = portrait
fullscreen = 0
android.presplash_color = aqua
android.permissions=INTERNET,READ_EXTERNAL_STORAGE,WRITE_EXTERNAL_STORAGE,MANAGE_EXTERNAL_STORAGE,CAMERA
android.archs = arm64-v8a
p4a.requirements = python3,kivy,opencv==4.7.0,numpy
p4a.setup_py = true
[buildozer]
log_level = 2
warn_on_root = 1
Run python for android and make main.py become a kivy app for android
sudo buildozer -v android debug
Reply
#3
Hello all....its jayson:

well, i have been working on compiling a lot and this is what i have

Another issue down the line, opencv videocapture will not work, it is working for droid above 4.5.1 so i get 4.7 ....
               
here is the code that needs some help i will add the apk too...
APK FILE HERE
main.py
import kivy
from kivy.app import App
from kivy.uix.label import Label
import cv2
import numpy as np
from multiprocessing import Process
 
class MyLabelApp(App):
    def build(self):
        caption = cv2.VideoCapture(0,cv2.CAP_V4L2)
        if not caption.isOpened():
            lbl2 = Label(text ="cannot open camera 0")
            return lbl2
            caption.release()
        else:
            caption.release()
        caption1 = cv2.VideoCapture(1,cv2.CAP_V4L2)
        if not caption1.isOpened():
            lbl3 = Label(text ="cannot open camera 1")
            return lbl3
            caption1.release()
        else:
            caption1.release()
        lbl = Label(text ="Android Two Cam Is running, Close window and save ouput.avi locally!!! ")
        return lbl
def cap():
    cap = cv2.VideoCapture(0,cv2.CAP_V4L2)
    cap1 = cv2.VideoCapture(1,cv2.CAP_V4L2)
    out = cv2.VideoWriter('/storage/emulated/0/dcim/output.avi',cv2.VideoWriter_fourcc(*'XVID'), cap.get(cv2.CAP_PROP_FPS), (1440,720))
    while(cap.isOpened()):
        ret, frame = cap.read()
        ret1, frame1 = cap1.read()
        if ret == True:
            reframe = cv2.resize(frame,(720, 720), interpolation = cv2.INTER_AREA)
            reframe1 = cv2.resize(frame1,(720, 720), interpolation = cv2.INTER_AREA)
            both = np.column_stack((reframe, reframe1))
            out.write(both) 
if __name__ == "__main__":
    p1 = Process(target=cap)
    p1.start()
    label = MyLabelApp()
    label.run()
    label.on_stop(p1.terminate())
Reply
#4
Any help diagnosing the error would send me lightyears into the future....(cannot open camera 0)

I am going to continue diagnosing here aswell....opencv is definately the error....not the import, however,
the use of cv2.VideoCapture(camera index number)

also i should find out what index number they are for real also. -1 appears to be automatic?

I am also worried about the caption property....

i had set it properly to android however it may be v4l2....
Reply
#5
Well i have put together a degug plan:
a program that prints out what camera (opencv index) actually works...

test.py
import kivy
from kivy.app import App
from kivy.uix.label import Label
import cv2

class MyLabelApp(App):
    def build(self):
        def list_ports():
            non_working_ports = []
            dev_port = 0
            #caption=cv2.CAP_V4L2
            caption = cv2.CAP_ANDROID
            working_ports = []
            available_ports = []
            while len(non_working_ports) < 6: # if there are more than 5 non working ports stop the testing. 
                camera = cv2.VideoCapture(dev_port, caption)
                if not camera.isOpened():
                    non_working_ports.append(str("Port %s is not working." %dev_port))
                else:
                    is_reading, img = camera.read()
                    w = camera.get(3)
                    h = camera.get(4)
                    if is_reading:
                        working_ports.append(str("Port %s is working and reads images (%s x %s)" %(dev_port,h,w)))
                    else:
                        available_ports.append(str("Port %s for camera ( %s x %s) is present but does not reads." %(dev_port,h,w)))
                dev_port +=1
            return available_ports,working_ports,non_working_ports
        ports  = str(list_ports())
        lblcams = Label(text =ports)
        return lblcams

if __name__ == "__main__":
    label = MyLabelApp()
    label.run()
OpenCv Camera TEST - APK


the apk works after adding permissions in app....however i must not know the "io caption" yet, all devices say not working, in linux the program is cherry.

I am going to try more 'IO caption"s and other options programatically by altering the test script and running it.....
Reply
#6
So, I have run the program with :
caption=cv2.CAP_V4L2
caption=cv2.CAP_ANDROID
and with no caption

   

I know believe my Python Code is correct with V4L2 however,
i will need to get better Android privileges
to allow open cv to work.....
this will be done in the buildozer.spec....i will update if working...
Reply
#7
Hi, were u able to save opencv video on android?
Reply
#8
(Oct-16-2023, 06:34 AM)lukmik Wrote: Hi, were u able to save opencv video on android?

I'm also interested in finding out. However, it seems the OP has been offline for several months. His dual camera solution for cell phones sounds like a fascinating project. I'm curious to know more about its progress and if OP made any significant progress. Also, I wanted to mention that it never hurts to have a solid theoretical foundation to support your practical endeavors. For example, when I was working on a mobile app project, I found this article to be incredibly insightful. Incorporating both practical experience and well-grounded knowledge from professionals can be a game-changer. I hope OP shows up here and tells us how it turned out.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
Sad Migrating of python2 script to python3 zuri 7 992 Oct-05-2023, 02:40 PM
Last Post: snippsat
  Buildozer fails building Kivy app for android Kolterdyx 0 3,134 Apr-30-2020, 06:31 PM
Last Post: Kolterdyx
  Secure App Data Storage for Kivy Android App JonPC 1 2,449 Nov-08-2019, 03:42 PM
Last Post: luke
  Gnuradio python3 is not compatible python3 xmlrpc library How Can I Fix İt ? muratoznnnn 3 4,930 Nov-07-2019, 05:47 PM
Last Post: DeaD_EyE
  Developing Python with OpenCV into an Android App AviationFreak 1 6,836 Sep-29-2019, 08:55 AM
Last Post: wavic
  error running script in python3.7.2 interpreter srm 4 4,869 May-23-2019, 01:09 PM
Last Post: snippsat
  Made a simple script for android (really simple) but it is not running anddontyoucomebacknomore 2 2,384 Mar-06-2019, 12:19 AM
Last Post: anddontyoucomebacknomore
  Integrating Python Script for Android App everythingisenergy 0 6,287 Jan-15-2019, 07:39 PM
Last Post: everythingisenergy
  cant execute a script without prefixing with python3 hunnimonstr 1 3,086 Jul-05-2017, 04:42 PM
Last Post: wavic

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020