質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.50%
Kivy

Kivyは、Pythonを用いたNUI開発のためのオープンソースフレームワーク。マルチタッチなど多くの入力に対応したNUIアプリなどを開発することができます。多くの環境で動作するクロスプラットフォームです。

Python 3.x

Python 3はPythonプログラミング言語の最新バージョンであり、2008年12月3日にリリースされました。

button

HTMLで用いる<button>タグです。

関数型プログラミング

関数型プログラミングとは、関数を用いて演算子を構築し、算出し、コンピュータプログラムを構成する枠組みです。

Python

Pythonは、コードの読みやすさが特徴的なプログラミング言語の1つです。 強い型付け、動的型付けに対応しており、後方互換性がないバージョン2系とバージョン3系が使用されています。 商用製品の開発にも無料で使用でき、OSだけでなく仮想環境にも対応。Unicodeによる文字列操作をサポートしているため、日本語処理も標準で可能です。

Q&A

解決済

1回答

4785閲覧

[Kivy-python] Buttonを用いた画像表示方法

Kenza

総合スコア21

Kivy

Kivyは、Pythonを用いたNUI開発のためのオープンソースフレームワーク。マルチタッチなど多くの入力に対応したNUIアプリなどを開発することができます。多くの環境で動作するクロスプラットフォームです。

Python 3.x

Python 3はPythonプログラミング言語の最新バージョンであり、2008年12月3日にリリースされました。

button

HTMLで用いる<button>タグです。

関数型プログラミング

関数型プログラミングとは、関数を用いて演算子を構築し、算出し、コンピュータプログラムを構成する枠組みです。

Python

Pythonは、コードの読みやすさが特徴的なプログラミング言語の1つです。 強い型付け、動的型付けに対応しており、後方互換性がないバージョン2系とバージョン3系が使用されています。 商用製品の開発にも無料で使用でき、OSだけでなく仮想環境にも対応。Unicodeによる文字列操作をサポートしているため、日本語処理も標準で可能です。

0グッド

0クリップ

投稿2020/05/19 14:35

編集2020/05/21 07:31

下記のように’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()

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

teamikl

2020/05/20 06:16

上記コードからは、変数 img2 の定義が確認できませんが、エラーはでてませんか?
Kenza

2020/05/21 06:58

返信ありがとうございます。そこの個所に関してimg2からimgに変更しましたが、相変わらず、ボタンを押しても初期画面から変化はなかったです。 個人的にはkvfileの source: paint_area.image_texture のコードが反映されていないのではと思っていますが、具体的な原因はわからないです。。。 よろしくお願いいたします。
teamikl

2020/05/21 10:34

コードは実行できてないのですが、原因はそこかな Imageにファイル名を指定する時のsource ではなく、 テクスチャ利用時は texture: paint_area.image_texture ですね。
guest

回答1

0

ベストアンサー

修正点:

  • Widget -> Image 等 or Widgetにしたい場合は canvas 内の要素にする。
  • source: -> texture:
  • tostring() -> tobytes() ※ 影響なし
  • Textureのオプション colorfmt ※ 試しただけで影響なし

※確認出来てないだけで影響があるかどうかわかりません。
元コードは動かせてませんが、画像が出ない症状の確認 → 修正を確認出来ました。


動作確認用

python

1from kivy.app import App 2from kivy.properties import ObjectProperty 3from kivy.uix.boxlayout import BoxLayout 4from kivy.graphics.texture import Texture 5import cv2 6 7class TestImageShow(BoxLayout): 8 image_texture = ObjectProperty(None) 9 10 def img_show(self): 11 filename = './sample.png' 12 img = cv2.imread(filename,cv2.IMREAD_UNCHANGED) 13 img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) # openCVの色の並びはBGRなのでRGBに直す 14 img = cv2.flip(img, 0) 15 texture = Texture.create(size=(img.shape[1], img.shape[0])) 16 texture.blit_buffer(img.tobytes()) 17 self.image_texture = texture 18 19 20class TestImageShowApp(App): 21 pass 22 23 24if __name__ == '__main__': 25 app = TestImageShowApp() 26 app.run()
TestImageShow: Button: id: show_button text: "Show" on_release: root.img_show() Image: id: paint texture: root.image_texture

投稿2020/05/21 10:58

teamikl

総合スコア8664

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

Kenza

2020/05/25 06:31 編集

ありがとうございました! 解決しました!
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.50%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問