Kivy Python FileChooser()

Я хочу сделать кнопку выбора файла, которая выберет файл изображения и отобразит его в окне для классификации изображения.
Я только что сделал распознавание изображения в kivy python, но хочу добавить кнопку, где пользователь может выбрать файл изображения из собственной системы. Пожалуйста, помогите мне добавить кнопку выбора файла в этот код ниже:

файл main.py:

import kivy.app
import Fruits
from kivy.uix.popup import Popup
from kivy.uix.tabbedpanel import TabbedPanel
from kivy.properties import ObjectProperty, StringProperty
from kivy.lang import Builder

class FirstApp(kivy.app.App):
    def classify_image(self):
        img_path = self.root.ids["img"].source

        img_features = Fruits.extract_features(img_path)

        predicted_class = Fruits.predict_output("c:\\Users\\aakip\\Documents\\Python\\face_recognition school project\\weights.npy", img_features, activation="sigmoid")

        self.root.ids["label"].text = "Predicted Class : " + predicted_class

if __name__ == "__main__":

    firstApp = FirstApp(title="Fruits 360 Recognition.")
    firstApp.run()

Fruits.py:

import numpy
import PIL.Image


def sigmoid(inpt):
    return 1.0/(1.0+numpy.exp(-1*inpt))
    
def relu(inpt):
    result = inpt
    result[inpt<0] = 0
    return result

def predict_output(weights_mat_path, data_inputs, activation="relu"):
    weights_mat = numpy.load(weights_mat_path,allow_pickle=True) #allow_pickle=True
    r1 = data_inputs
    for curr_weights in weights_mat:
        r1 = numpy.matmul(r1, curr_weights)
        if activation == "relu":
            r1 = relu(r1)
        elif activation == "sigmoid":
            r1 = sigmoid(r1)
    r1 = r1[0, :]
    predicted_label = numpy.where(r1 == numpy.max(r1))[0][0]
    class_labels = ["Apple", "Raspberry", "Mango", "Lemon"]
    predicted_class = class_labels[predicted_label]
    return predicted_class

def extract_features(img_path):
    im = PIL.Image.open(img_path).convert("HSV")
    fruit_data_hsv = numpy.asarray(im, dtype=numpy.uint8)

    indices = numpy.load(file="c:\\Users\\aakip\\Documents\\Python\\face_recognition school project\\indices.npy")
    #indices  = numpy.load(file="indices.npy")
    
    
    hist = numpy.histogram(a=fruit_data_hsv[:, :, 0], bins=360)
    im_features = hist[0][indices]
    img_features = numpy.zeros(shape=(1, im_features.size))
    img_features[0, :] = im_features[:im_features.size]
    return img_features

Файл .kv:

#:kivy 1.10.0
BoxLayout:
    orientation: "vertical"
    Label:
        text: "Predicted Class Appears Here."
        font_size: 30
        id: label
    BoxLayout:
        orientation: "horizontal"
        Image:
            source: "apple.jpeg"
            id: img
    Button:
        text: "Classify Image."
        font_size: 30
        on_press: app.classify_image()

<FileChoosePopup>:
    title: "Choose a .jpeg File"
    size_hint: .9, .9
    auto_dismiss: False

    BoxLayout:
        orientation: "vertical"
        FileChooser:
            id: filechooser
            FileChooserIconLayout

        BoxLayout:
            size_hint: (1, 0.1)
            pos_hint: {'center_x': .5, 'center_y': .5}
            spacing: 20
            Button:
                text: "Cancel"
                on_release: root.dismiss()
            Button:
                text: "Load"
                on_release: root.load(filechooser.selection)
                id: ldbtn
                disabled: True if filechooser.selection==[] else False

СПАСИБО!


person Akash Panda    schedule 17.10.2020    source источник


Ответы (1)


вы пытались проверить документацию Kivi? https://kivy.org/doc/stable/api-kivy.uix.filechooser.html

Я считаю, что это часть, которую вы ищете.

class Root(FloatLayout):
    loadfile = ObjectProperty(None)
    def show_load(self):
        content = LoadDialog(load=self.load, cancel=self.dismiss_popup)
        self._popup = Popup(title="Load file", content=content,
                            size_hint=(0.9, 0.9))
        self._popup.open()
    def load(self, path, filename):
            with open(os.path.join(path, filename[0])) as stream:
                self.text_input.text = stream.read()
    
            self.dismiss_popup()
person nahakubuilder    schedule 01.11.2020