ディープラーニングを使用して、ドラゴンボールZの「スカウター(っぽいもの)」を作ってみた記事のコード類です。
作成したディープラーニング・スカウターについては、以下の記事をごらんください。
コード類はかなり汚くて自分でも公開するのが嫌なくらいですが、きれいに書き直すパワーがないので、参考程度に使用してください。
①顔画像検出器を生成するファイル
training_object_detector.py
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | import os import sys import dlib img_dir = "." options = dlib.simple_object_detector_training_options() options.add_left_right_image_flips = True options.C = 5 options.num_threads = 4 options.be_verbose = True training_xml_path = os.path.join(img_dir, "training.xml") testing_xml_path = os.path.join(img_dir, "test.xml") dlib.train_simple_object_detector(training_xml_path, "detector.svm", options) print("") print("Training accuracy: {}".format( dlib.test_simple_object_detector(training_xml_path, "detector.svm"))) print("Testing accuracy: {}".format( dlib.test_simple_object_detector(testing_xml_path, "detector.svm"))) |
face_detector.py
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 | import os import sys import glob import cv2 import dlib from skimage import io if len(sys.argv) != 2: exit() faces_folder = sys.argv[1] #detector = dlib.get_frontal_face_detector() detector = dlib.simple_object_detector("detector.svm") win_det = dlib.image_window() win_det.set_image(detector) print("Showing detections on the images in the faces folder...") win = dlib.image_window() for f in glob.glob(os.path.join(faces_folder, "*.jpg")): print("Processing file: {}".format(f)) img = io.imread(f) dets = detector(img) print("Number of faces detected: {}".format(len(dets))) for k, d in enumerate(dets): print("Detection {}: Left: {} Top: {} Right: {} Bottom: {}".format( k, d.left(), d.top(), d.right(), d.bottom())) color =(0,255,0) cv2.rectangle(img, (d.right(),d.bottom()), (d.left(), d.top()), color,3) win.clear_overlay() win.set_image(img) win.add_overlay(dets) dlib.hit_enter_to_continue() |
②顔を切り出すファイル
CroppingFace_anime.py
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 | # -*- coding: utf-8 -*- import os import sys import glob import argparse import cv2 from PIL import Image import dlib def main(): parser = argparse.ArgumentParser(description='画像ファイルのクリッピングとデータ拡張処理') parser.add_argument('--outdir', '-o', default='.', help='拡張した画像データの保存場所') parser.add_argument('--indir', '-i', default='.', help='元画像のあるディレクトリ') parser.add_argument('--size', '-s', type=int, default=100, #100 help='クロップサイズ') args = parser.parse_args() size = args.size #detector = dlib.get_frontal_face_detector() detector = dlib.simple_object_detector("detector.svm") dir_list = os.listdir(args.indir) for dir_name in dir_list: ix = 0 outdir = os.path.join(args.outdir, dir_name) if not os.path.exists(outdir): os.mkdir(outdir) print('mkdir {}'.format(outdir)) image_files = glob.glob(os.path.join(args.indir, dir_name, "*.jpg")) #image_files = glob.glob(os.path.join(args.indir, dir_name, "*.png")) for image_file in image_files: img = cv2.imread(image_file) dets = detector(img, 1) # cropping faces open_img = Image.open(image_file) for d in dets: if d.right()-d.left() < size/2 or d.bottom()-d.top() < size/2: print('{}: detected face is too small.'.format(image_file)) continue cropped_img = open_img.crop((d.left(), d.top(), d.right(), d.bottom())) cropped_img = cropped_img.resize((size, size)) output_file = outdir + "/" + str(ix).zfill(4) + ".jpg" cropped_img.save(output_file, 'JPEG', quality=100, optimize=True) #output_file = outdir + "/" + str(ix).zfill(4) + ".png" #cropped_img.save(output_file, 'png', quality=100, optimize=True) ix += 1 if __name__ == '__main__': main() |
[参考 Interface 2017.8号]
③ディープラーニング学習
python train_face.py
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 | # -*- coding: utf-8 -*- #!/usr/bin/env python """ このプログラムは, Chainer examples/mnist をCNNに改良したものです. """ #from __future__ import print_function import argparse import os import sys import chainer import chainer.functions as F import chainer.links as L import chainer.initializers as I # 西崎追加(モデルパラメータの初期化のため) from chainer import training from chainer.training import extensions # 畳み込みニューラルネットワークの定義 class CNN(chainer.Chain): def __init__(self, n_out): w = I.Normal(scale=0.05) # モデルパラメータの初期化 super(CNN, self).__init__( # Chainerの場合,「層」を記述するのではなく,層と層をつなぐリンク構造を記述する # "Linear"は,全結合層(full-connected layer)を表す conv1=L.Convolution2D(3, 16, 5, 1, 0), # 1層目の畳み込み層(フィルタ数は16) conv2=L.Convolution2D(16, 32, 5, 1, 0), # 2層目の畳み込み層(フィルタ数は32) conv3=L.Convolution2D(32, 64, 5, 1, 0), # 3層目の畳み込み層(フィルタ数は64) l4=L.Linear(None, n_out, initialW=w), #クラス分類用 ) # DNNのフォワード処理を行う(フォワードという言葉の意味も必要) def __call__(self, x): h1 = F.max_pooling_2d(F.relu(self.conv1(x)), ksize=2, stride=2) # 最大値プーリングは2×2,活性化関数はReLU h2 = F.max_pooling_2d(F.relu(self.conv2(h1)), ksize=2, stride=2) h3 = F.max_pooling_2d(F.relu(self.conv3(h2)), ksize=2, stride=2) # 9x9,64ch return self.l4(h3) def main(): # オプション処理 parser = argparse.ArgumentParser(description='Chainer example: MNIST') parser.add_argument('--batchsize', '-b', type=int, default=50, help='Number of images in each mini-batch') parser.add_argument('--epoch', '-e', type=int, default=50, help='Number of sweeps over the dataset to train') parser.add_argument('--gpu', '-g', type=int, default=-1, help='GPU ID (negative value indicates CPU)') parser.add_argument('--out', '-o', default='result', help='Directory to output the result') parser.add_argument('--datadir', '-d', default='face_data', help='学習データのディレクトリ') args = parser.parse_args() print('GPU: {}'.format(args.gpu)) print('# Minibatch-size: {}'.format(args.batchsize)) print('# epoch: {}'.format(args.epoch)) print('') train = [] label = 0 print('loading dataset') for c in os.listdir(args.datadir): print('class: {}, class id: {}'.format(c, label)) d = os.path.join(args.datadir, c) imgs = os.listdir(d) for i in [f for f in imgs if ('jpg' in f)]: train.append([os.path.join(d, i), label]) label += 1 print('') train = chainer.datasets.LabeledImageDataset(train, '.') model = L.Classifier(CNN(3)) # CNNにする if args.gpu >= 0: chainer.cuda.get_device(args.gpu).use() # Make a specified GPU current model.to_gpu() # Copy the model to the GPU # Setup an optimizer optimizer = chainer.optimizers.Adam() optimizer.setup(model) train_iter = chainer.iterators.SerialIterator(train, args.batchsize) updater = training.StandardUpdater(train_iter, optimizer, device=args.gpu) trainer = training.Trainer(updater, (args.epoch, 'epoch'), out=args.out) trainer.extend(extensions.dump_graph('main/loss')) trainer.extend(extensions.snapshot(), trigger=(args.epoch, 'epoch')) trainer.extend(extensions.LogReport()) trainer.extend( extensions.PlotReport('main/loss', 'epoch', file_name='loss.png')) trainer.extend( extensions.PlotReport('main/accuracy', 'epoch', file_name='accuracy.png')) trainer.extend(extensions.PrintReport( ['epoch', 'main/loss', 'main/accuracy', 'elapsed_time'])) trainer.extend(extensions.ProgressBar()) trainer.run() # モデルをCPU対応へ model.to_cpu() # 保存 modelname = args.out + "/FaceEmotion.model" print('save the trained model: {}'.format(modelname)) chainer.serializers.save_npz(modelname, model) if __name__ == '__main__': main() |
[参考 Interface 2017.8号]
④ディープラーニング識別
python train_face.py
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 | # -*- coding: utf-8 -*- #from __future__ import print_function import argparse import os import sys import numpy as np import cv2 import dlib from PIL import Image import chainer import chainer.functions as F import chainer.links as L cat = ['クリリン', '悟空', 'ラディッツ'] # カテゴリによって変える(順番も) # 畳み込みニューラルネットワークの定義 class CNN(chainer.Chain): def __init__(self, n_out): super(CNN, self).__init__( conv1=L.Convolution2D(3, 16, 5, 1, 0), # 1層目の畳み込み層(フィルタ数は16) conv2=L.Convolution2D(16, 32, 5, 1, 0), # 2層目の畳み込み層(フィルタ数は32) conv3=L.Convolution2D(32, 64, 5, 1, 0), # 3層目の畳み込み層(フィルタ数は64) l4=L.Linear(None, n_out), #クラス分類用 ) def __call__(self, x): h1 = F.max_pooling_2d(F.relu(self.conv1(x)), ksize=2, stride=2) # 最大値プーリングは2×2,活性化関数はReLU h2 = F.max_pooling_2d(F.relu(self.conv2(h1)), ksize=2, stride=2) h3 = F.max_pooling_2d(F.relu(self.conv3(h2)), ksize=2, stride=2) return self.l4(h3) def main(): # オプション処理 parser = argparse.ArgumentParser(description='顔認識プログラム') parser.add_argument('--image', '-i', default='sample.jpg', help='画像ファイル(JPG)') parser.add_argument('--size', '-s', type=int, default=100, help='クロップサイズ') parser.add_argument('--model', '-m', default='FaceEmotion.model', help='学習したモデル') args = parser.parse_args() size = args.size model = L.Classifier(CNN(3)) # モデルの定義 chainer.serializers.load_npz(args.model, model) #モデルの読み込み #ここを変える必要がある #detector = dlib.get_frontal_face_detector() detector = dlib.simple_object_detector("detector.svm") img = cv2.imread(args.image) dets = detector(img, 1) open_img = Image.open(args.image) flag = 0 for i, d in enumerate(dets): flag = 1 if d.right()-d.left() < size/2 or d.bottom()-d.top() < size/2: print('{}: 顔画像が小さすぎます。'.format(args.image)) continue cropped_img = open_img.crop((d.left(), d.top(), d.right(), d.bottom())) resized_img = cropped_img.resize((size, size)) resized_img.save('eval.jpg', 'JPEG', quality=100, optimize=True) evaldata = np.array(resized_img, dtype=np.float32) evaldata = evaldata.transpose(2, 0, 1) evaldata = evaldata.reshape(1, 3, size, size) x = chainer.Variable(np.asarray(evaldata)) y = model.predictor(x) # フォワード c = F.softmax(y).data.argmax() print('{}個目の顔の判定結果は『{}』です。'.format(flag, cat[c])) print(str(F.softmax(y))) flag += 1 if flag == 0: print('顔画像の検出に失敗しました') if __name__ == '__main__': main() |
[参考 Interface 2017.8号]
⑤スカウターGUIのプログラム
このファイルはQtDesignerから生成したファイルになります。
pyqt_Opencv.py
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 | # -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'pyqt_Opencv.ui' # # Created by: PyQt4 UI code generator 4.11.4 # # WARNING! All changes made in this file will be lost! from PyQt4 import QtCore, QtGui try: _fromUtf8 = QtCore.QString.fromUtf8 except AttributeError: def _fromUtf8(s): return s try: _encoding = QtGui.QApplication.UnicodeUTF8 def _translate(context, text, disambig): return QtGui.QApplication.translate(context, text, disambig, _encoding) except AttributeError: def _translate(context, text, disambig): return QtGui.QApplication.translate(context, text, disambig) class Ui_Qt_CV_MainWindow(object): def setupUi(self, Qt_CV_MainWindow): Qt_CV_MainWindow.setObjectName(_fromUtf8("Qt_CV_MainWindow")) Qt_CV_MainWindow.resize(800, 600) self.centralwidget = QtGui.QWidget(Qt_CV_MainWindow) self.centralwidget.setObjectName(_fromUtf8("centralwidget")) self.file_button = QtGui.QPushButton(self.centralwidget) self.file_button.setGeometry(QtCore.QRect(360, 30, 101, 41)) self.file_button.setObjectName(_fromUtf8("file_button")) self.file_edit = QtGui.QLineEdit(self.centralwidget) self.file_edit.setGeometry(QtCore.QRect(30, 30, 321, 41)) self.file_edit.setObjectName(_fromUtf8("file_edit")) self.scouter_button = QtGui.QPushButton(self.centralwidget) self.scouter_button.setGeometry(QtCore.QRect(570, 30, 171, 121)) self.scouter_button.setText(_fromUtf8("")) icon = QtGui.QIcon() icon.addPixmap(QtGui.QPixmap(_fromUtf8("Scouter-icon.png")), QtGui.QIcon.Normal, QtGui.QIcon.Off) self.scouter_button.setIcon(icon) self.scouter_button.setIconSize(QtCore.QSize(150, 150)) self.scouter_button.setObjectName(_fromUtf8("scouter_button")) self.pic_View = QtGui.QGraphicsView(self.centralwidget) self.pic_View.setGeometry(QtCore.QRect(20, 170, 721, 371)) self.pic_View.setObjectName(_fromUtf8("pic_View")) Qt_CV_MainWindow.setCentralWidget(self.centralwidget) self.menubar = QtGui.QMenuBar(Qt_CV_MainWindow) self.menubar.setGeometry(QtCore.QRect(0, 0, 800, 25)) self.menubar.setObjectName(_fromUtf8("menubar")) self.menuFiel = QtGui.QMenu(self.menubar) self.menuFiel.setObjectName(_fromUtf8("menuFiel")) Qt_CV_MainWindow.setMenuBar(self.menubar) self.statusbar = QtGui.QStatusBar(Qt_CV_MainWindow) self.statusbar.setObjectName(_fromUtf8("statusbar")) Qt_CV_MainWindow.setStatusBar(self.statusbar) self.actionFile_select = QtGui.QAction(Qt_CV_MainWindow) self.actionFile_select.setObjectName(_fromUtf8("actionFile_select")) self.actionQuite = QtGui.QAction(Qt_CV_MainWindow) self.actionQuite.setObjectName(_fromUtf8("actionQuite")) self.menuFiel.addAction(self.actionFile_select) self.menuFiel.addAction(self.actionQuite) self.menubar.addAction(self.menuFiel.menuAction()) self.retranslateUi(Qt_CV_MainWindow) QtCore.QObject.connect(self.actionQuite, QtCore.SIGNAL(_fromUtf8("triggered()")), Qt_CV_MainWindow.close) QtCore.QMetaObject.connectSlotsByName(Qt_CV_MainWindow) def retranslateUi(self, Qt_CV_MainWindow): Qt_CV_MainWindow.setWindowTitle(_translate("Qt_CV_MainWindow", "MainWindow", None)) self.file_button.setText(_translate("Qt_CV_MainWindow", "File", None)) self.menuFiel.setTitle(_translate("Qt_CV_MainWindow", "File", None)) self.actionFile_select.setText(_translate("Qt_CV_MainWindow", "file select", None)) self.actionQuite.setText(_translate("Qt_CV_MainWindow", "Quite", None)) if __name__ == "__main__": import sys app = QtGui.QApplication(sys.argv) Qt_CV_MainWindow = QtGui.QMainWindow() ui = Ui_Qt_CV_MainWindow() ui.setupUi(Qt_CV_MainWindow) Qt_CV_MainWindow.show() sys.exit(app.exec_()) |
[参考:PyQt(PySide)で画像処理その1(GUIの作成)]
⑥スカウターを実行するディープラーニングファイル
scouter.py
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 | # -*- coding: utf-8 -*- #from __future__ import print_function import argparse import os import sys import numpy as np import cv2 import dlib from PIL import Image import chainer import chainer.functions as F import chainer.links as L cat = ['クリリン', '悟空', 'ラディッツ'] # カテゴリによって変える(順番も) # 畳み込みニューラルネットワークの定義 class CNN(chainer.Chain): def __init__(self,parent = None): super(CNN, self).__init__( conv1=L.Convolution2D(3, 16, 5, 1, 0), # 1層目の畳み込み層(フィルタ数は16) conv2=L.Convolution2D(16, 32, 5, 1, 0), # 2層目の畳み込み層(フィルタ数は32) conv3=L.Convolution2D(32, 64, 5, 1, 0), # 3層目の畳み込み層(フィルタ数は64) l4=L.Linear(None, 3), #クラス分類用 ) def __call__(self, x): h1 = F.max_pooling_2d(F.relu(self.conv1(x)), ksize=2, stride=2) # 最大値プーリングは2×2,活性化関数はReLU h2 = F.max_pooling_2d(F.relu(self.conv2(h1)), ksize=2, stride=2) h3 = F.max_pooling_2d(F.relu(self.conv3(h2)), ksize=2, stride=2) return self.l4(h3) def scouter_on(self,file): # オプション処理 parser = argparse.ArgumentParser(description='顔認識プログラム') parser.add_argument('--image', '-i', default='sample.jpg', help='画像ファイル(JPG)') parser.add_argument('--size', '-s', type=int, default=100, help='クロップサイズ') parser.add_argument('--model', '-m', default='result/FaceEmotion.model', help='学習したモデル') args = parser.parse_args() size = args.size model = L.Classifier(CNN(3)) # モデルの定義 chainer.serializers.load_npz(args.model, model) #モデルの読み込み #ここを変える必要がある #detector = dlib.get_frontal_face_detector() detector = dlib.simple_object_detector("detector.svm") # args.image=unicode(file) print(str(args.image)) img = cv2.imread(args.image) dets = detector(img, 1) open_img = Image.open(args.image) flag = 0 for i, d in enumerate(dets): flag = 1 if d.right()-d.left() < size/2 or d.bottom()-d.top() < size/2: print('{}: 顔画像が小さすぎます。'.format(args.image)) continue cropped_img = open_img.crop((d.left(), d.top(), d.right(), d.bottom())) resized_img = cropped_img.resize((size, size)) #resized_img.save('eval.jpg', 'JPEG', quality=100, optimize=True) evaldata = np.array(resized_img, dtype=np.float32) evaldata = evaldata.transpose(2, 0, 1) evaldata = evaldata.reshape(1, 3, size, size) x = chainer.Variable(np.asarray(evaldata)) y = model.predictor(x) # フォワード c = F.softmax(y).data.argmax() print('{}個目の顔の判定結果は『{}』です。'.format(flag, cat[c])) #print(str(F.softmax(y))) #スカウターオン greenimg = cv2.imread('son_img.jpg',-1) #透過させる img = cv2.addWeighted(img, 0.6, greenimg , 0.4, 0.0) #byouga color =(0,255,0) cv2.rectangle(img, (d.right(),d.bottom()), (d.left(), d.top()), color,3) #名前を表示 #フォントの大きさ fontscale = 1.7 #フォントカラー(B, G, R) color=(255, 30, 255) #フォント fontface = cv2.FONT_HERSHEY_SIMPLEX #cv2.putText(描画先, 描画文字列, 描画座標[左下が基準], フォント, フォントカラー) if c == 0: cv2.putText(img,"Klilyn (Power Level:206)",(d.left(),d.bottom()+50),fontface,fontscale, color,5) elif c == 1: cv2.putText(img,"Gokuh (Power Level:416)",(d.left(),d.bottom()+50),fontface,fontscale, color,5) elif c == 2: cv2.putText(img,"Raditz (Power Level:1500)",(d.left(),d.bottom()+50),fontface,fontscale, color,5) #スカウターの画面を作成 #h, w, channels = img.shape #cv2.rectangle(img, (0,0),(w,h), (0,255,0),-1) #cv2.imwrite('son_img.jpg', img) flag += 1 if flag == 0: print('顔画像の検出に失敗しました') #スカウターオン greenimg = cv2.imread('son_img.jpg',-1) #透過させる img = cv2.addWeighted(img, 0.6, greenimg , 0.4, 0.0) #名前を表示 #フォントの大きさ fontscale = 2 #フォントカラー(B, G, R) color=(0, 0, 255) #フォント fontface = cv2.FONT_HERSHEY_SIMPLEX #cv2.putText(描画先, 描画文字列, 描画座標[左下が基準], フォント, フォントカラー) cv2.putText(img,"No faces are detected",(400,400),fontface,fontscale, color,4) return str(3), img return c, img if __name__ == '__main__': main() |
⑦GUIのメインファイル
main.py
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 | # coding:utf-8 from __future__ import with_statement import numpy as np import sys from PyQt4 import QtCore,QtGui import os import cv2 #生成されたフォームのファイルからフォームをインポート from pyqt_Opencv import Ui_Qt_CV_MainWindow #スカウターの外部プログラムを読み込む from scouter import CNN import chainer #おまじない その1""" class DesignerMainWindow(QtGui.QMainWindow,Ui_Qt_CV_MainWindow): def __init__(self, parent = None): super(DesignerMainWindow, self).__init__(parent) self.ui = Ui_Qt_CV_MainWindow() self.setupUi(self) #おまじない その1終わり #シグナル&スロット:file_buttonをクリックすると、open_file関数を実行 QtCore.QObject.connect(self.file_button, QtCore.SIGNAL("clicked()"), self.open_file) #scouterボタンクリック時にexe_canny関数を実行 QtCore.QObject.connect(self.scouter_button, QtCore.SIGNAL("pressed()"), self.open_scouter) QtCore.QObject.connect(self.scouter_button, QtCore.SIGNAL("released()"), self.exe_scouter) #open_file関数""" def open_file(self): #「ファイルを開く」ダイアログにて画像読み込み""" self.file = QtGui.QFileDialog.getOpenFileName() if file: self.scene = QtGui.QGraphicsScene() #file_edit(Line editオブジェクト)にファイルアドレスをセット""" self.file_edit.setText(self.file) #ファイルを読み込んでRとBを交換 pic = cv2.imread(unicode(self.file)) pic2 = cv2.cvtColor(pic,cv2.COLOR_BGR2RGB) #エッジ検出 #self.cv_img = cv_test.canny(pic2) #画像縮小 h, w, channels = pic2.shape pic2 = cv2.resize(pic2,(w/2,h/2)) # self.cv_img = pic2 #画像の高さ、幅を読み込み height, width, dim = self.cv_img.shape #全ピクセル数 bytesPerLine = dim * width #Opencv(numpy)画像をQtのQImageに変換 self.image = QtGui.QImage(self.cv_img.data, width, height, bytesPerLine, QtGui.QImage.Format_RGB888) #QImageをQPixmapに変換し、アイテムとして読み込む pic_Item = QtGui.QGraphicsPixmapItem(QtGui.QPixmap.fromImage(self.image)) #画像配置用ウィジット生成""" scene = QtGui.QGraphicsScene() #"""PixmapItem形式で画像を取り込み""" #pic_Item = QtGui.QGraphicsPixmapItem(QtGui.QPixmap(file)) #"""画像の幅と高さ情報を採取""" __width = pic_Item.boundingRect().width() __height = pic_Item.boundingRect().height() #"""画像配置用ウィジットのデフォルトサイズ値を採取""" __x = self.pic_View.x() __y = self.pic_View.y() #"""画像に合わせてウィジットのサイズを変更""" self.pic_View.setGeometry(QtCore.QRect(__x, __y, __width+3, __height+3)) __main_x = int(__x + __width + 30) __main_y = int(__y + __height + 50) #"""画像に合わせてメインウィンドウのサイズ変更""" self.resize(__main_x,__main_y) #"""ウィジットに画像を配置""" scene.addItem(pic_Item) #"""前回作成したフォームとの関連付け""" self.pic_View.setScene(scene) #scouter関数 def open_scouter(self): #スカウターを描画 img = cv2.imread(unicode(self.file)) greenimg = cv2.imread('son_img.jpg',-1) #透過させる img = cv2.addWeighted(img, 0.6, greenimg , 0.4, 0.0) #色の並び修正 img = cv2.cvtColor(img,cv2.COLOR_BGR2RGB) #画像縮小 h, w, channels = img.shape img = cv2.resize(img,(w/2,h/2)) self.cv_img = img #Opencv(numpy)画像をQtのQImageに変換 height, width, dim = self.cv_img.shape #全ピクセル数 bytesPerLine = dim * width self.image = QtGui.QImage(self.cv_img.data, width, height, bytesPerLine, QtGui.QImage.Format_RGB888) #QImageをQPixmapに変換し、アイテムとして読み込む pic_Item = QtGui.QGraphicsPixmapItem(QtGui.QPixmap.fromImage(self.image)) #画像配置用ウィジット生成""" scene = QtGui.QGraphicsScene() #"""ウィジットに画像を配置""" scene.addItem(pic_Item) #"""前回作成したフォームとの関連付け""" self.pic_View.setScene(scene) #scouter実行関数 def exe_scouter(self): #opencv_testファイルからクラスの読み込み sc= CNN(chainer.Chain) #ファイルを読み込んでRとBを交換 ret,img = sc.scouter_on(self.file) #描画 #色の並び修正 img = cv2.cvtColor(img,cv2.COLOR_BGR2RGB) #画像縮小 h, w, channels = img.shape img = cv2.resize(img,(w/2,h/2)) self.cv_img = img #Opencv(numpy)画像をQtのQImageに変換 height, width, dim = self.cv_img.shape #全ピクセル数 bytesPerLine = dim * width self.image = QtGui.QImage(self.cv_img.data, width, height, bytesPerLine, QtGui.QImage.Format_RGB888) #QImageをQPixmapに変換し、アイテムとして読み込む pic_Item = QtGui.QGraphicsPixmapItem(QtGui.QPixmap.fromImage(self.image)) #画像配置用ウィジット生成""" scene = QtGui.QGraphicsScene() #"""ウィジットに画像を配置""" scene.addItem(pic_Item) #"""前回作成したフォームとの関連付け""" self.pic_View.setScene(scene) if __name__ == '__main__': #"""おまじない その2""" app = QtGui.QApplication(sys.argv) dmw = DesignerMainWindow() dmw.show() sys.exit(app.exec_()) #"""おまじない その2終わり""" |
[参考:PyQt(PySide)で画像処理その1(GUIの作成)]
以上となります。