在 Kivy 中插入 Python 脚本

发布于 2025-01-12 23:30:26 字数 1831 浏览 0 评论 0原文

我想在 kivy 中插入这个 python 脚本,这样我就可以在 Android 中使用它。我尝试了 chaquoy 但没有太多解决方案。那么任何人都可以让我知道我应该在这个 python 脚本中添加什么才能在 kivy 中运行它以及我在 kivy 文件中放入的内容,这样我就可以单击按钮来启动该功能,然后单击另一个按钮来停止它并显示最终结果

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()

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()

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

不甘平庸 2025-01-19 23:30:26

你必须记住 kivy gui 是循环的,所以如果你尝试循环某些东西而不是在 kivy 中输出它,它会被卡住(被窃听)。所以解决方案是同时运行 kivy 和你想要的线程函数,

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())

如果你想将 cv2 显示到 kivy 中,你需要将其转换为纹理

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文