下記のように’img_show’ボタンを押すと、Piantクラス内の関数img_show()が呼び出され、画像(./sample.jpg)が表示されてほしいのですが、ボタンを押しても初期画面から変化がありません。
クラスNet()はこの問題には絡んでいないとは思いますので、飛ばしてもらって結構です。
どうすればよいでしょうか?ご教授のほどよろしくお願いいたします。
カレントディレクトリにsample.jpgは置かれています。
python
1import random 2 3from kivy.config import Config 4# 起動時のウィンドウサイズ 5Config.set('graphics', 'width', '2048') 6Config.set('graphics', 'height', '1024') 7 8from kivy.app import App 9from kivy.clock import Clock 10from kivy.properties import StringProperty, ObjectProperty 11from kivy.uix.widget import Widget 12from kivy.uix.boxlayout import BoxLayout 13from kivy.uix.label import Label 14from kivy.graphics import Line, Color 15from kivy.core.window import Window 16from kivy.uix.image import Image 17from kivy.graphics.texture import Texture 18 19import os 20from collections import OrderedDict 21from torch.autograd import Variable 22from options.test_options import TestOptions 23from data.data_loader import CreateDataLoader 24from models.models import create_model 25import util.util as util 26from util.visualizer import Visualizer 27from util import html 28 29import numpy as np 30import torch 31import cv2 32 33class Net(): 34 # 認識モデルを読み込む 35 def __init__(self): 36 #self.model = torch.load(".\checkpoints\label2city_1024p/latest_net_G.pth", map_location=lambda storage, loc: storage) # 学習済みの重みファイルを読み込む 37 #self.model.eval() # 今回は学習は行わない 38 #self.sm = nn.Softmax(dim=1) # どの結果も信頼性が低い場合にスコアで足切りしたいのでsoftmaxで正規化する 39 40 self.opt = TestOptions().parse(save=False) 41 self.opt.nThreads = 1 # test code only supports nThreads = 1 42 self.opt.batchSize = 1 # test code only supports batchSize = 1 43 self.opt.serial_batches = True # no shuffle 44 self.opt.no_flip = True # no flip 45 self.data_loader = CreateDataLoader(self.opt) 46 self.dataset = self.data_loader.load_data() 47 self.visualizer = Visualizer(self.opt) 48 49 self.web_dir = os.path.join(self.opt.results_dir, self.opt.name, '%s_%s' % (self.opt.phase, self.opt.which_epoch)) 50 self.webpage = html.HTML(self.web_dir, 'Experiment = %s, Phase = %s, Epoch = %s' % (self.opt.name, self.opt.phase, self.opt.which_epoch)) 51 52 53 54 # 画像ファイル名を入力して認識結果を返す 55 def predict(self): 56 if not self.opt.engine and not self.opt.onnx: 57 model = create_model(self.opt) 58 if self.opt.data_type == 16: 59 model.half() 60 elif self.opt.data_type == 8: 61 model.type(torch.uint8) 62 63 if self.opt.verbose: 64 print(model) 65 else: 66 from run_engine import run_trt_engine, run_onnx 67 68 for i, data in enumerate(self.dataset): 69 if i >= self.opt.how_many: 70 break 71 if self.opt.data_type == 16: 72 data['label'] = data['label'].half() 73 data['inst'] = data['inst'].half() 74 elif self.opt.data_type == 8: 75 data['label'] = data['label'].uint8() 76 data['inst'] = data['inst'].uint8() 77 if self.opt.export_onnx: 78 print ("Exporting to ONNX: ", self.opt.export_onnx) 79 assert self.opt.export_onnx.endswith("onnx"), "Export model file should end with .onnx" 80 torch.onnx.export(model, [data['label'], data['inst']], 81 self.opt.export_onnx, verbose=True) 82 exit(0) 83 minibatch = 1 84 if self.opt.engine: 85 generated = run_trt_engine(self.opt.engine, minibatch, [data['label'], data['inst']]) 86 elif self.opt.onnx: 87 generated = run_onnx(self.opt.onnx, self.opt.data_type, minibatch, [data['label'], data['inst']]) 88 else: 89 generated = model.inference(data['label'], data['inst'], data['image']) 90 91 visuals = OrderedDict([('input_label', util.tensor2label(data['label'][0], self.opt.label_nc)), 92 ('synthesized_image', util.tensor2im(generated.data[0]))]) 93 img_path = data['path'] 94 print('process image... %s' % img_path) 95 self.visualizer.save_images(self.webpage, visuals, img_path) 96 #print(visuals,img_path) 97 98 99class Paint(Widget): 100 image_texture = ObjectProperty(None) 101 image_src = StringProperty('') 102 103 def __init__(self, **kwargs): 104 super().__init__(**kwargs) 105 self.line_width = 2 # 線の太さ 106 self.lines = [] # undo用に線を格納するリスト 107 self.in_drawing = False # 描画中か否かを判定 108 self.canvas.add(Color(0,0,0)) 109 self.model = Net() 110 #self.source = StringProperty('./sample.jpg') 111 112 113 def calc_pos(self, bbox): 114 xmin = min(bbox[0], bbox[2]) 115 ymin = min(bbox[1], bbox[3]) 116 xmax = max(bbox[0], bbox[2]) 117 ymax = max(bbox[1], bbox[3]) 118 return xmin,ymin,xmax,ymax 119 120 # クリック中(描画中)の動作 121 def on_touch_move(self, touch): 122 if self.in_drawing == False: 123 if self.pos[0]<touch.x<self.pos[0]+self.size[0] and self.pos[1]<touch.y<self.pos[1]+self.size[1]: 124 self.in_drawing = True 125 with self.canvas: 126 touch.ud['line'] = Line(points=(touch.x, touch.y), width=self.line_width) 127 elif touch.ud: 128 if self.pos[0]<touch.x<self.pos[0]+self.size[0] and self.pos[1]<touch.y<self.pos[1]+self.size[1]: 129 touch.ud['line'].points += [touch.x, touch.y] 130 131 # クリック終了時の動作 132 def on_touch_up(self, touch): 133 if self.in_drawing: 134 self.lines.append(touch.ud['line']) 135 self.in_drawing = False 136 137 # 直前の線を消去 138 def undo(self): 139 if len(self.lines)>0: 140 line = self.lines.pop(-1) 141 self.canvas.remove(line) 142 143 # キャンバスを全消しする 144 def clear_canvas(self): 145 for line in self.lines: 146 self.canvas.remove(line) 147 self.lines = [] 148 149 def save_canvas(self): 150 #Window.screenshot('./a.png') 151 self.export_to_png('./aaaa.png',scale=1.0) 152 153 def predict(self): 154 self.export_to_png('/aaaa.png') 155 self.model.predict() 156 print("done") 157 158 def img_show(self): 159 filename = './sample.jpg' 160 self.image_src = filename 161 img = cv2.imread(filename,cv2.IMREAD_UNCHANGED) 162 #img = cv2.resize(img, (128, 128)) 163 img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) # openCVの色の並びはBGRなのでRGBに直す 164 img = cv2.flip(img, 0) 165 #cv2.imwrite("./bbbb.png",img) 166 texture = Texture.create(size=(img2.shape[1], img2.shape[0])) 167 texture.blit_buffer(img2.tostring()) 168 self.image_texture = texture 169 170 171class PaintQuiz(BoxLayout): 172 def __init__(self, **kwargs): 173 super(PaintQuiz, self).__init__(**kwargs) 174 pass 175 176 177class PaintQuizApp(App): 178 def __init__(self, **kwargs): 179 super(PaintQuizApp, self).__init__(**kwargs) 180 self.title = 'PAINT TOOL' 181 182 183 def build(self): 184 return PaintQuiz() 185 186 187if __name__ == '__main__': 188 app = PaintQuizApp() 189 app.run()
kv
1<PaintQuiz>: 2 canvas: 3 Color: 4 rgb: 1,1,1 5 Rectangle: 6 pos: self.pos 7 size: self.size 8 BoxLayout: 9 size: root.size 10 orientation: 'vertical' 11 12 Paint: 13 size_hint_y: 0.6 14 id: paint_area 15 allow_stretch: True 16 source: paint_area.image_texture 17 18 BoxLayout: 19 size_hint_y: 0.1 20 Button: 21 id: button_undo 22 size_hint_x: 0.25 23 text: 'Undo' 24 on_release: paint_area.undo() 25 26 Button: 27 id: button_clear 28 size_hint_x: 0.25 29 text: 'Clear' 30 on_release: paint_area.clear_canvas() 31 32 Button: 33 id: button_run 34 size_hint_x: 0.25 35 text: 'img_show' 36 on_release: paint_area.img_show() 37 38 Button: 39 id: button_reset 40 size_hint_x: 0.25 41 text: 'Save' 42 on_release: paint_area.save_canvas()
回答1件
あなたの回答
tips
プレビュー