如何在kivy中的类中插入Python脚本?

时间:2017-06-16 21:21:31

标签: python kivy

我有一个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")

2 个答案:

答案 0 :(得分:0)

如果您想创建一个将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,它是小部件的一部分 我喜欢的任何更新属性的方式。肯定有其他方法。

答案 1 :(得分:0)

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