【问题标题】:How to insert a Python script in a class in kivy?如何在kivy的类中插入Python脚本?
【发布时间】:2018-11-16 12:11:22
【问题描述】:

我有一个 python 文本,我想把它放在 kivy 的一个类中。然后我想将这个类用作一个函数并从另一个类中调用它。我应该如何定义类?括号class FaceGenerator()应该写什么?

class FaceGenerator():
    # open the camera and capture video
    cam = cv2.VideoCapture(0)
    face_detector = 
    cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
    # Asking the user for an ID and Name
    ID = raw_input('Please insert your ID number  ')
    Name= raw_input('Please insert your Name  ')
    sample_number = 0 # a counter that counts the number of pictures for 
    each person in the database

    # detecting the face and draw rectangle on it
    while (True):
        retval,image = cam.read() # reading image from cam
        print np.shape(image)
        gray_image = cv2.cvtColor(image,cv2.COLOR_BGR2GRAY) # converting 
        image to gray image
        faces = face_detector.detectMultiScale(gray_image,1.3,5)
        ''' detectMultiScale, detects objects of different sizes in the 
        input image.
        the detected objects are returned as a list of rectangles
        '''
        for (x,y,w,h) in faces:
            cv2.rectangle(image, (x,y), (x+w, y+h), (255,0,0), 2)
            sample_number=sample_number+1
        # saving the captured face in the facebase folder
            cv2.imwrite('Trainer/User.'+ID+'.'+str(sample_number)+'.jpg', 
         gray_image[y:y+h,x:x+w])
    # this loop drawing a rectabgle on the face while the cam is open 
        cv2.imshow('frame',image)
        if cv2.waitKey(100) & 0xFF == ord('q'):
            break
        elif sample_number==20:
            break

    cam.release()
    cv2.destroyAllWindows()
    return Label(text = "Succesfully created trainning set")

【问题讨论】:

  • 写入括号对象,--> 类 FaceGenerator(object)。但是你定义的并不是一个真正的类。我认为只需定义一个可以从程序 def FaceGenerator () 中的任何位置调用的函数来为您提供更好的服务:
  • 我只需定义一个返回字符串的函数,然后通过遍历您的小部件树并更新标签的文本属性而不返回新标签来更新它。
  • 我认为关注these trivial rules 可以让你的帖子变得更好,只需一点点工作。

标签: python kivy


【解决方案1】:

如果您想创建一个类,请将 object 放在括号中 --> class FaceGenerator(object): 但是在您的情况下,根本不需要类,您正在寻找的是一个函数。如果我理解正确,您只想在该类上调用一个函数,因此您只能首先定义一个函数

这是我认为您想做的一种方式:

from kivy.app import App
from kivy.base import Builder
from kivy.properties import ObjectProperty
from kivy.uix.boxlayout import BoxLayout


def FaceGenerator():
    #do your stuff
    face = 'PalimPalim'
    return face

Builder.load_string("""
<rootwi>:
    label_to_be_changed: label_to_be_changed
    orientation: 'vertical'
    Button:
        text:'klick me'
        on_press: root.change_Label_text()
    Label:
        id: label_to_be_changed

""")
class rootwi(BoxLayout):
    label_to_be_changed = ObjectProperty()

    def change_Label_text(self):
        temp_str = FaceGenerator()
        self.label_to_be_changed.text = temp_str

class MyApp(App):
    def build(self):
        return rootwi()

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

更多信息

  • kv 中的 root 在这种情况下指的是最左边的小部件rootwi
  • 为作为小部件一部分的小部件定义 ObjectProperty 是 我最喜欢的更新属性的方式。当然还有其他方法。

【讨论】:

  • 实际上我想要做的是将 FaceRecognition 代码插入到我的 kivy 应用程序的一个屏幕上,当我按下一个按钮时,我想开始使用这个 coed 来生成一个训练数据库所以当我调用识别器时,它会使用这个训练数据库来获取人脸特征并识别人脸。我想把这段代码放在一个矩形中,这样当它完成捕获图片时,我可以按下右下角的按钮移动到下一页。
  • 所以我应该定义一个函数,然后在特定屏幕上的 kv 代码中我必须放置 BoxLayout 并且在这个 BoxLayout 中我应该调用该函数,是我写的吗?
  • 您可以定义独立于屏幕的函数,然后在屏幕上调用或引用它。在示例中,我提供的 FaceGenerator 函数与 kv 或类无关。我只是在课堂上调用它。
  • 我正在调用该函数并使用结果来更改小部件的属性。您的屏幕也可以这样做。调用该函数并使用结果更新屏幕上的某些内容,例如您的屏幕标签之一的文本属性。
  • 好吧,我会试试这个,让你知道我发生了什么事。谢谢
【解决方案2】:

@PalimPalim 我在上面担任过您的结构。我的代码现在是这样的 Python代码

import kivy
import cv2, os
import numpy as np
from PIL import Image

from kivy.app import App
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.uix.button import Button
from kivy.uix.widget import Widget
from kivy.uix.label import Label
from kivy.lang import Builder
from kivy.config import Config
Config.set('graphics', 'fullscreen', '0')
Config.set('graphics','show_cursor','1')

def FaceGenerator():
# open the camera and capture video
    cam = cv2.VideoCapture(0)
    face_detector = 
    cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
    ID = 0
    sample_number = 0 # a counter that counts the number of pictures for 
    each person in the database

    # detecting the face and draw rectangle on it
    while (True):
        retval,image = cam.read() # reading image from cam
        print np.shape(image)
        gray_image = cv2.cvtColor(image,cv2.COLOR_BGR2GRAY) # converting 
        image to gray image
        faces = face_detector.detectMultiScale(gray_image,1.3,5)
        ''' detectMultiScale, detects objects of different sizes in the 
        input image.
        the detected objects are returned as a list of rectangles
        '''
        for (x,y,w,h) in faces:
            cv2.rectangle(image, (x,y), (x+w, y+h), (255,0,0), 2)
            sample_number=sample_number+1
        # saving the captured face in the facebase folder

            cv2.imwrite('Trainer/User.'+str(ID)+'.'+str(sample_number)+'.jpg',
            gray_image[y:y+h,x:x+w])
    # this loop drawing a rectabgle on the face while the cam is open 
        cv2.imshow('frame',image)
        if cv2.waitKey(100) & 0xFF == ord('q'):
            break
        elif sample_number==20:
            break

    cam.release()
    cv2.destroyAllWindows()
    output = "Succesfully created trainning set"
    return output

class ScreenOne(Screen):
    pass

class ScreenTwo(Screen):
    pass

class ScreenThree(Screen):
        pass


class ScreenManagement(ScreenManager):
    pass


sm = Builder.load_file("facerecognition.kv")

class FaceRecognitionApp(App):
    def build(self):
        return sm

if __name__=="__main__":
    FaceRecognitionApp().run()

.KV 文件是:

ScreenManagement:
    id: screen_management
    ScreenOne:
    ScreenTwo:
    ScreenThree:



<ScreenOne>:
    name: "screen1"
    id: screen_one

    FloatLayout:
        canvas.before:
            Rectangle:
                source: "image1.jpg"
                pos:self.pos
                size:self.size

        Label:
            text:"Hello\n Welcome to my App\n"
            font_size:40 
            color: 0,0,0,1
        Button:
            text: 'Next'
            font_size: 32 # font size
            size_hint: .2,.1
            pos_hint:{'right':1, 'y':0}
            on_release: app.root.current="screen2"

<ScreenTwo>:
    name: "screen2"
    id: screen_two

    FloatLayout:
        canvas:

            Rectangle:
                source: "image1.jpg"
                pos:self.pos
                size:self.size

        Label:
            text:"Please insert your Name\n Please insert your Password\n"
            font_size:40 
            color: 0,0,0,1
        Button:
            text: 'Next'
            font_size: 32 # font size
            size_hint: .2,.1
            pos_hint:{'right':1, 'y':0}
            on_release: app.root.current="screen3"

<ScreenThree>:
    name: "screen3"
    id: screen_three


    FloatLayout:
        canvas:

            Rectangle:
                source: "image1.jpg"
                pos:self.pos
                size:self.size


        Button:
            text: 'Next'
            font_size: 32 # font size
            size_hint: .2,.1
            pos_hint:{'right':1, 'y':0}
            on_release: app.root.current="screen1"

        BoxLayout:
            orientation: 'horizontal'
            FaceGenerator()

【讨论】:

  • BoxLayout:orientation: 'horizo​​ntal' FaceGenerator() 不起作用,因为你需要一些按钮来调用你的函数。
  • 此外,kivy 在另一个函数运行时停止更新,因此您可能需要查看线程stackoverflow.com/a/44605996/6646710
  • 如果我在 BoxLayout 中添加了一个按钮,当我按下它时,它会打开该功能并开始拍摄一些照片。我可以做 on_release: app.root.current="FaceGenerator"
  • 这仍然不是对函数的调用。像 on_release: app.root.fg() 一样做某事并向您的应用程序类添加方法 def fg(self): FaceGenerator()
  • 你的意思是这样做,类 FaceRecognitionApp(App): def fg(self): FaceGenerator() def build(self): return sm
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-09-13
  • 2016-04-12
相关资源
最近更新 更多