【发布时间】:2020-10-17 06:46:44
【问题描述】:
我想制作一个文件选择器按钮,它将选择一个图像文件并将其显示在窗口上以对图像进行分类。
我刚刚在 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
谢谢!
【问题讨论】:
标签: python kivy kivy-language filechooser