'Insert Python script in Kivy

i want to insert this python script in kivy so i can use it in Android. Itried with chaquoy but there no much solutions. So can anyone let me know what should i add to this python script to run it in kivy also what i put in kivy file so i can click on the button to start the function and another button to stop it and shows the final result

from keras.models import load_model
from time import sleep
from keras.preprocessing.image import img_to_array
from keras.preprocessing import image
import cv2
import numpy as np

face_classifier = cv2.CascadeClassifier('./haarcascade_frontalface_default.xml')
classifier =load_model('./Emotion_Detection.h5')

class_labels = ['Angry','Happy','Neutral','Sad','Surprise']




while True:
    # Grab a single frame of video
    ret, frame = cap.read()
    labels = []
    gray = cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY)
    faces = face_classifier.detectMultiScale(gray,1.3,5)

    for (x,y,w,h) in faces:
        cv2.rectangle(frame,(x,y),(x+w,y+h),(255,0,0),2)
        roi_gray = gray[y:y+h,x:x+w]
        roi_gray = cv2.resize(roi_gray,(48,48),interpolation=cv2.INTER_AREA)


        if np.sum([roi_gray])!=0:
            roi = roi_gray.astype('float')/255.0
            roi = img_to_array(roi)
            roi = np.expand_dims(roi,axis=0)

        # make a prediction on the ROI, then lookup the class

            preds = classifier.predict(roi)[0]
            print("\nprediction = ",preds)
            label=class_labels[preds.argmax()]
            print("\nprediction max = ",preds.argmax())
            print("\nlabel = ",label)
            label_position = (x,y)
            cv2.putText(frame,label,label_position,cv2.FONT_HERSHEY_SIMPLEX,2,(0,255,0),3)
        else:
            cv2.putText(frame,'No Face Found',(20,60),cv2.FONT_HERSHEY_SIMPLEX,2,(0,255,0),3)
        print("\n\n")
    cv2.imshow('Emotion Detector',frame)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break
cap.release()
cv2.destroyAllWindows()


Solution 1:[1]

U have to put in mind that kivy gui is loop so if u try to loop something than output it inside kivy it will get stuck(bugged). so the solution is to run both kivy and and the function u want in threading like this

import ##....
import threading

output =  ### 
somecond = False

def my_function():
   global somecond, some_output
   while True:
       time.sleep(1) ### THREADS ARE CALLED ONLY ONE TIME.
                 ### U KILL THIS FUNCTION U CANT START IT AGAIN.

           while some_cond == True:
               output = ####

thread_my_fucnction = threading.Thread(target = my_function)

class my_screen(Widget):
    global some_output, somecond
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.kivy_output = ####
        
       
    def my_button(self):
        global some_output, somecond 
        somecond = True
        Clock.shecdule(self.update_kivy_output, #seconds)
        ########## use Clock.unschedual(self.update_kivy_out)  if u want to stop end updating ur output and clock.schedual to update again
    def update_kivy_output(self, *args):
        global some_output
        self.kivy_output = some_output

class theapp(App):
    def build(self):
        self.screenm = ScreenManager(transition=FadeTransition())

        self.my_screen = my_screen()
        screen = Screen(name = "my_screen")
        screen.add_widget(self.my_screen)
        self.screenm.add_widget(screen)

if __name__ == "__main__":
    theapp = theapp()
    thread_my_function.start()                              
    threading.Thread(target = theapp.run())

at last if u want to display a cv2 into kivy u need to convert it into texture

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Oussama