1、效果图

2、思路
主要是利用QComboBox 这个结构体,具体可以看代码
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 | import sys from PyQt5.QtWidgets import QWidget, QComboBox, QApplication class ComboxDemo(QWidget): def __init__(self): super().__init__() # 设置标题 self.setWindowTitle('ComBox例子') # 设置初始界面大小 self.resize(300, 200) # 实例化QComBox对象 self.cb = QComboBox(self) self.cb.move(100, 20) # 单个添加条目 self.cb.addItem('C') self.cb.addItem('C++') self.cb.addItem('Python') # 多个添加条目 self.cb.addItems(['Java', 'C#', 'PHP']) # 信号 self.cb.currentIndexChanged[str].connect(self.print_value) # 条目发生改变,发射信号,传递条目内容 self.cb.currentIndexChanged[int].connect(self.print_value) # 条目发生改变,发射信号,传递条目索引 self.cb.highlighted[str].connect(self.print_value) # 在下拉列表中,鼠标移动到某个条目时发出信号,传递条目内容 self.cb.highlighted[int].connect(self.print_value) # 在下拉列表中,鼠标移动到某个条目时发出信号,传递条目索引 def print_value(self, i): print(i) if __name__ == '__main__': app = QApplication(sys.argv) comboxDemo = ComboxDemo() comboxDemo.show() sys.exit(app.exec_()) |
3、将下拉框嵌入到其他窗口
如果想把下拉框嵌入到其他窗口中,可以用下面语句

效果图

整体代码
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 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 | # -*- coding: utf-8 -*- ''' ''' import sys import cv2 as cv import argparse from PIL import Image import numpy as np import tensorflow as tf import pickle as p import matplotlib.pyplot as plt import os, random from sklearn.preprocessing import MinMaxScaler from skimage.io import imsave # 保存影像 import warnings from PyQt5 import QtCore, QtGui, QtWidgets from PyQt5.QtWidgets import * from PyQt5.QtCore import * from PyQt5.QtGui import * ###========全局变量 定义开始=======### type_seting=0 select_rethon_flag =0 #鼠标点击事件结束flag #鼠标点击事件坐标变量 global_x0 = 0 global_y0 = 0 global_x1 = 0 global_y1 = 0 final_picture = ... ###========全局变量 定义结束========### ###===============================鼠标点击事件类及成员函数================================### class MouseLabel(QLabel): x0 = 0 y0 = 0 x1 = 0 y1 = 0 flag = False #鼠标点击事件 def mousePressEvent(self,event): global select_rethon_flag # 全局变量 if select_rethon_flag==1: self.flag = True self.x0 = event.x() self.y0 = event.y() #鼠标释放事件 def mouseReleaseEvent(self,event): self.flag = False #鼠标移动事件 def mouseMoveEvent(self,event): if self.flag: self.x1 = event.x() self.y1 = event.y() self.update() #绘制事件 def paintEvent(self, event): super().paintEvent(event) rect =QRect(self.x0, self.y0, abs(self.x1-self.x0), abs(self.y1-self.y0)) global global_x0 # 全局变量 global global_y0 # 全局变量 global global_x1 global global_y1 global_x0 = self.x0 global_y0 = self.y0 global_x1 = self.x1 global_y1 = self.y1 # print("绘制事件") # print("x0=", global_x0) # print("y0=", global_y0) # print("x1=", global_x1) # print("y1=", global_y1) # print("\n") painter = QPainter(self) painter.setPen(QPen(Qt.red,2,Qt.SolidLine)) painter.drawRect(rect) class Ui_MainWindow(object): def setupUi(self, MainWindow): MainWindow.setObjectName("MainWindow") # 1、总界面框大小 MainWindow MainWindow.resize(1600, 820) # 总界面框 #左侧界面区域:verticalLayoutWidget QWidget类 self.verticalLayoutWidget = QtWidgets.QWidget(MainWindow) self.verticalLayoutWidget.setGeometry(QtCore.QRect(30, 25, 1280, 720))#左边图片框 self.verticalLayoutWidget.setStyleSheet('background-color:rgb(55,55,55)') # 设置做左边框的颜色 self.verticalLayoutWidget.setObjectName("verticalLayoutWidget") self.verticalLayout = QtWidgets.QVBoxLayout(self.verticalLayoutWidget) #QVBoxLayout类 垂直地摆放小部件 self.verticalLayout.setContentsMargins(0, 0, 0, 0)#设置左侧、顶部、右侧和底部边距,以便在布局周围使用。 self.verticalLayout.setObjectName("verticalLayout") #画红色框 self.label_ShowPicture = MouseLabel(self.verticalLayoutWidget) # 重定义的label self.label_ShowPicture.setObjectName("Draw_ShowPicture") # self.label_ShowPicture.setGeometry(QRect(30, 30, 511, 541)) # 鼠标可以点击的范围 self.verticalLayout.addWidget(self.label_ShowPicture,0, Qt.AlignLeft | Qt.AlignTop) # 水平居左 垂直居上 # 右边按钮及显示结果字符的一块区域:verticalLayoutWidget_2 QWidget类 self.verticalLayoutWidget_2 = QtWidgets.QWidget(MainWindow) self.verticalLayoutWidget_2.setGeometry(QtCore.QRect(1350, 50, 220, 800)) #右边按钮及显示结果字符的大小 #self.verticalLayoutWidget_2.setStyleSheet('background-color:rgb(155,155,155)') # 设置做左边框的颜色 self.verticalLayoutWidget_2.setObjectName("verticalLayoutWidget_2") self.verticalLayout_2 = QtWidgets.QVBoxLayout(self.verticalLayoutWidget_2) #QVBoxLayout类 垂直地摆放小部件 self.verticalLayout_2.setContentsMargins(0, 0, 0, 0) self.verticalLayout_2.setObjectName("verticalLayout_2") #1:按钮1 选择图片按钮:pushButton_select_pcture self.pushButton_select_pcture = QtWidgets.QPushButton(self.verticalLayoutWidget_2) self.pushButton_select_pcture.setObjectName("pushButton_select_pcture") self.verticalLayout_2.addWidget(self.pushButton_select_pcture)#将按钮1增加到 # 设置控件间的间距 self.verticalLayout_2.setSpacing(50) #2:下拉菜单:薄烟、浓烟 self.comboBox = QtWidgets.QComboBox(self.verticalLayoutWidget_2) self.comboBox.setObjectName("comboBox") self.verticalLayout_2.addWidget(self.comboBox) self.comboBox.addItems([' 等级',' 浓烟',' 薄烟']) #3:选择区域按钮 self.pushButton_selct_region = QtWidgets.QPushButton(self.verticalLayoutWidget_2) self.pushButton_selct_region.setObjectName("pushButton_selct_region") self.verticalLayout_2.addWidget(self.pushButton_selct_region) #4;通过训练生成烟花按钮 self.pushButton_genetate = QtWidgets.QPushButton(self.verticalLayoutWidget_2) self.pushButton_genetate.setObjectName("pushButton_genetate") self.verticalLayout_2.addWidget(self.pushButton_genetate) #按钮4 yolov3方法识别按钮 self.pushButton_save_picture = QtWidgets.QPushButton(self.verticalLayoutWidget_2) self.pushButton_save_picture.setObjectName("pushButton_save_picture") self.verticalLayout_2.addWidget(self.pushButton_save_picture) self.label = QtWidgets.QLabel(self.verticalLayoutWidget_2) font = QtGui.QFont() font.setPointSize(15) self.label.setFont(font) self.label.setObjectName("label") self.verticalLayout_2.addWidget(self.label) #lable_2放显示结果1 self.label_2 = QtWidgets.QLabel(self.verticalLayoutWidget_2) font = QtGui.QFont() font.setPointSize(15) self.label_2.setFont(font) self.label_2.setText("") self.label_2.setObjectName("label_2") self.verticalLayout_2.addWidget(self.label_2) #lable_3放显示结果2 self.lable_3 = QtWidgets.QLabel(self.verticalLayoutWidget_2) font = QtGui.QFont() font.setPointSize(15) self.lable_3.setFont(font) self.lable_3.setObjectName("label_3") self.verticalLayout_2.addWidget(self.lable_3) #lable_4放显示结果3 self.label_4 = QtWidgets.QLabel(self.verticalLayoutWidget_2) font = QtGui.QFont() font.setPointSize(15) self.label_4.setFont(font) self.label_4.setObjectName("label_4") self.verticalLayout_2.addWidget(self.label_4) #=======================事件===================================================================# # button点击事件 self.pushButton_select_pcture.clicked.connect(self.pushButton_select_pcture_click)#读入图片按钮 # 选择区域button点击事件 self.pushButton_selct_region.clicked.connect(self.select_region) # 生成烟花button点击事件 self.pushButton_genetate.clicked.connect(self.generate) #利用模型生成图片 # button点击事件 self.pushButton_save_picture.clicked.connect(self.save_composed_picture) # 保存合成图片 # 下拉菜单信号事件 self.comboBox.currentIndexChanged[str].connect(self.print_value) # 条目发生改变,发射信号,传递条目内容 self.comboBox.currentIndexChanged[int].connect(self.print_value) # 条目发生改变,发射信号,传递条目索引 self.retranslateUi(MainWindow) QtCore.QMetaObject.connectSlotsByName(MainWindow) name_picture = 0 def retranslateUi(self, MainWindow): _translate = QtCore.QCoreApplication.translate MainWindow.setWindowTitle(_translate("MainWindow", "基于生成式对抗网络的烟火图片生成系统")) #self.label_ShowPicture.setText(_translate("MainWindow", "图片展示区")) self.pushButton_select_pcture.setText(_translate("MainWindow", "导入图片")) #self.comboBox.setText(_translate("MainWindow", "等级")) self.pushButton_selct_region.setText(_translate("MainWindow", "选择区域")) self.pushButton_genetate.setText(_translate("MainWindow", "生成烟火")) self.pushButton_save_picture.setText(_translate("MainWindow", "保存合成图片")) #self.label.setText(_translate("MainWindow", "")) image=None #事件函数 def pushButton_select_pcture_click(self): filename = QFileDialog.getOpenFileName(None, 'Open file', 'C:/Users/Desktop/testpicture/')#后面这个路径其实没什么用,路径主要还是看选择的具体路径 # 设置标签的图片 src0 = cv.imread(filename[0]) [height_src0, width_src0,hhh]= src0.shape print('height_src0: %d \twidth_src0: %d \t' % (height_src0, width_src0)) if (width_src0 > 1280): print("1") rate1 = 1280 / width_src0 print(1280) print(rate1) new_width = 1280 new_height = int(height_src0 * rate1) print(new_width, new_height) if (height_src0 > 720):#图片宽高都大于1280*720 print("2") rate2 = 720 /height_src0 if(rate2<rate1):#选择更宽或者更高的一个缩放到标准1280或者720, rate2=rate2 new_height = 720 new_width = int(width_src0 * rate2) else: rate2=rate1 new_height = int(height_src0 * rate2) new_width = 1280 #image = src0.scaled(new_width, new_height) resized0 = cv.resize(src0, (new_width, new_height), interpolation=cv.INTER_AREA) elif (height_src0 > 720): print("3") rate3 = 720 /height_src0 print("rate3=",rate3) new_height = 720 new_width = int(width_src0 * rate3) print("new_height=", new_height) print("new_width=", new_width) #image = src0.scaled(new_width, new_height) resized0 = cv.resize(src0, (new_width, new_height), interpolation=cv.INTER_AREA) else: print("4") resized0 =src0 new_width=width_src0 new_height=height_src0 #resized0 = cv.resize(src0, (1280, 720), interpolation=cv.INTER_AREA) cv.imwrite("temp0.jpg", resized0) self.label_ShowPicture.move(0, 0) print("new_height=", new_height) print("new_width=", new_width) #self.label_ShowPicture.setScaledContents (True) # 让图片自适应label大小 #self.label_ShowPicture.setContentsMargins(0, 0, new_width, new_height) #self.label_ShowPicture.setMargin(30); #表示控件与窗体的左右边距 #self.label_ShowPicture.setSpacing(40); #表示各个控件之间的上下间距 self.label_ShowPicture.setPixmap(QPixmap("temp0.jpg")) #self.label_ShowPicture.setContentsMargins(0, 0, new_width, new_height) print("filename[0]=",filename[0]) self.image = Image.open(filename[0]) #下拉框 def print_value(self, i): global type_seting if i==0: print("请选择等级") type_seting = -1 if i == 1: print("等级为浓烟") type_seting=0 if i == 2: print("等级为薄烟") #global type_seting type_seting = 1 def shibie_svm(self): print("识别中") self.label_2.setText("") if self.image == None: self.label_2.setText("没有选中待检测的图片") # print("没有选择图片") ###==========================选择区域=========================================================### def select_region(self): print("请选择区域") self.label_2.setText("") global select_rethon_flag select_rethon_flag=1 ###==========================通过训练进行生成=========================================================### def generate(self): global global_x0 # 全局变量 global global_y0 # 全局变量 global global_x1 global global_y1 print("开始生成") # self.label_2.setText("开始生成") ###===============================加载数据==================================================## n = 0 m = 0 # 加载数据 image_width = 64 image_height = 64 image_depth = 3 image_pix = image_height * image_width in_label = np.array( [0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1, # 0-29 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, # 30-59 0, 1, 0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1, 0, 0, # 60-89 0, 0, 0,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, 0, 1, 0, 1, 0, 0, 0, 0, 1, # 720-749 0, 1, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 1, 0, 1, 1, 1, 1, 0, 0, 1, # 750-779 0, 1, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0, # 780-809 0, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 0, # 810-839 0, 1, 1, 1, 0, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 1, # 840-869 0, 1, 0, 0, 0, 0 # 870-875 ]) def load_batch(filename): with open(filename, 'rb')as f: data_dict = p.load(f, encoding='bytes') images = data_dict['data'] images = images.reshape(876, image_depth, image_width, image_width) images = images.transpose(0, 2, 3, 1) return images def load_data(): image_batch = load_batch('./data64') # x_train=np.concatenate(image_batch) x_train = image_batch minmax = MinMaxScaler() # 重塑 x_train_rows = x_train.reshape(x_train.shape[0], image_width * image_width * image_depth) # 归一化,0-255归一化为0-1 x_train = minmax.fit_transform(x_train_rows) # 重新变为64 x 64 x 3 x_train = x_train.reshape(x_train.shape[0], image_width, image_width, image_depth) return x_train def get_inputs(noise_dim, image_height, image_width, image_depth): inputs_real = tf.placeholder(tf.float32, [None, image_width, image_width, image_depth], name='inputs_real') inputs_noise = tf.placeholder(tf.float32, [None, noise_dim], name='inputs_noise') label = tf.placeholder(tf.float32, [None, 2], name='label') return inputs_real, inputs_noise, label def leaky_relu(X, leak=0.2): f1 = 0.5 * (1 + leak) f2 = 0.5 * (1 - leak) return f1 * X + f2 * tf.abs(X) def get_generator(inputs_noise, label, output_dim, is_train=True, alpha=0.01): with tf.variable_scope("generator", reuse=(not is_train)): # 100 x 1 to 8 x 8 x 512 # 全连接层 layer1 = tf.concat([inputs_noise, label], axis=1) layer1 = tf.layers.dense(layer1, 8 * 8 * 512) layer1 = tf.reshape(layer1, [-1, 8, 8, 512]) # batch normalization layer1 = tf.layers.batch_normalization(layer1, training=is_train) # Leaky ReLU layer1 = tf.maximum(alpha * layer1, layer1) # dropout layer1 = tf.nn.dropout(layer1, keep_prob=0.8) # 8 x 8 x 512 to 16 x 16 x 256 layer2 = tf.layers.conv2d_transpose(layer1, 256, 3, strides=2, padding='same') layer2 = tf.layers.batch_normalization(layer2, training=is_train) layer2 = tf.maximum(alpha * layer2, layer2) layer2 = tf.nn.dropout(layer2, keep_prob=0.8) # 16 x 16 x 256 to 32 x 32 x 128 layer3 = tf.layers.conv2d_transpose(layer2, 128, 3, strides=2, padding='same') layer3 = tf.layers.batch_normalization(layer3, training=is_train) layer3 = tf.maximum(alpha * layer3, layer3) layer3 = tf.nn.dropout(layer3, keep_prob=0.8) # 32 x 32 x 128 to 64 x 64 x 3 logits = tf.layers.conv2d_transpose(layer3, output_dim, 3, strides=2, padding='same') # MNIST原始数据集的像素范围在0-1,这里的生成图片范围为(-1,1) # 因此在训练时,记住要把MNIST像素范围进行resize outputs = tf.tanh(logits) print(outputs.get_shape()) print("G") return outputs def conv_cond_concat(x, y): x_shapes = x.get_shape() y_shapes = y.get_shape() ret = tf.concat([ x, y * tf.ones( [x_shapes.as_list()[0], x_shapes.as_list()[1], x_shapes.as_list()[2], y_shapes.as_list()[3]])], 3) return ret def get_discriminator(inputs_img, label, reuse=False, alpha=0.01): inputs_img = tf.reshape(inputs_img, shape=(batch_size, image_width, image_width, image_depth)) label = tf.reshape(label, shape=(batch_size, 1, 1, 2)) with tf.variable_scope("discriminator", reuse=reuse): # 200 x 200 x 3 to 100 x 100 x 128 layer1 = conv_cond_concat(inputs_img, label) layer1 = tf.layers.conv2d(layer1, 128, 3, strides=2, padding='same') layer1 = tf.maximum(alpha * layer1, layer1) layer1 = tf.nn.dropout(layer1, keep_prob=0.8) # 100 x 100 x 128 to 50 x 50 x 256 layer2 = tf.layers.conv2d(layer1, 256, 3, strides=2, padding='same') layer2 = tf.layers.batch_normalization(layer2, training=True) layer2 = tf.maximum(alpha * layer2, layer2) layer2 = tf.nn.dropout(layer2, keep_prob=0.8) # 50 x 50 x 256 to 25 x 25 x 512 layer3 = tf.layers.conv2d(layer2, 512, 3, strides=2, padding='same') layer3 = tf.layers.batch_normalization(layer3, training=True) layer3 = tf.maximum(alpha * layer3, layer3) layer3 = tf.nn.dropout(layer3, keep_prob=0.8) # 25 x 25 x 512 to 25*25*512 x 1 flatten = tf.reshape(layer3, (-1, 8 * 8 * 512)) logits = tf.layers.dense(flatten, 1) outputs = tf.sigmoid(logits) print("D") return logits, outputs def get_loss(inputs_img, inputs_noise, label, image_depth, smooth=0.1): g_outputs = get_generator(inputs_noise, label, image_depth, is_train=True) d_logits_real, d_outputs_real = get_discriminator(inputs_img, label) d_logits_fake, d_outputs_fake = get_discriminator(g_outputs, label, reuse=True) # 计算Loss g_loss = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(logits=d_logits_fake, labels=tf.ones_like(d_logits_fake) * ( 1 - smooth))) d_loss_real = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(logits=d_logits_real, labels=tf.ones_like(d_logits_real) * ( 1 - smooth))) d_loss_fake = tf.reduce_mean( tf.nn.sigmoid_cross_entropy_with_logits(logits=d_logits_fake, labels=tf.zeros_like(d_logits_fake))) d_loss = tf.add(d_loss_real, d_loss_fake) return g_loss, d_loss, d_loss_real, d_loss_fake def get_optimizer(g_loss, d_loss, beta1=0.4, learning_rate=0.001): train_vars = tf.trainable_variables() g_vars = [var for var in train_vars if var.name.startswith("generator")] d_vars = [var for var in train_vars if var.name.startswith("discriminator")] # 保存生成器变量 saver = tf.train.Saver(var_list=g_vars) # Optimizer with tf.control_dependencies(tf.get_collection(tf.GraphKeys.UPDATE_OPS)): g_opt = tf.train.AdamOptimizer(learning_rate, beta1=beta1).minimize(g_loss, var_list=g_vars) d_opt = tf.train.AdamOptimizer(learning_rate, beta1=beta1).minimize(d_loss, var_list=d_vars) return g_opt, d_opt, saver def show_result(epoch, batch_res, fname): print("save img %s" % epoch) # 将batch_res进行值[0, 1]归一化,同时将其reshape成(batch_size, image_height, image_width) batch_res = 0.5 * batch_res.reshape((batch_res.shape[0], image_height, image_width, image_depth)) + 0.5 print(batch_res.shape[0]) for i, res in enumerate(batch_res): img = (res) * 255. img = img.astype(np.uint8) # print(img.shape[0],img.shape[1],img.shape[2]) # fname=fname+'epoch%s' % epoch+'img%s' % i imsave(os.path.join('output_cf', f'epoch{str(epoch)}-img{str(i)}.png'), img) # 定义参数 batch_size = 80 noise_size = 100 epochs = 1001 n_samples = 1 learning_rate = 0.001 beta1 = 0.4 output_path = "./output_1/" output_label_path = "./label_1/" def train(x_label, noise_size, data_shape, batch_size, n_samples, flag, type): # 添加了flag和type # 存储loss losses = [] # 加载所有图片 images = load_data() # 记录训练轮数 steps = 0 # y用于保存模型和读取模型 # saver = tf.train.Saver() # 设置占位符 inputs_img, inputs_noise, inputs_label = get_inputs(noise_size, data_shape[1], data_shape[2], data_shape[3]) g_loss, d_loss, d_loss_real, d_loss_fake = get_loss(inputs_img, inputs_noise, inputs_label, image_depth) g_train_opt, d_train_opt, saver = get_optimizer(g_loss, d_loss, beta1, learning_rate) with tf.Session() as sess: saver = tf.train.Saver() if (flag == 0): sess.run(tf.global_variables_initializer()) # 迭代epoch for e in range(epochs): print(e) # 用于打乱顺序,每一次迭代都要打乱顺序 index = random.sample(range(0, images.shape[0]), images.shape[0]) real_images = images[index] real_label = x_label[index] # 每一批次进行训练 for batch_i in range(images.shape[0] // batch_size): steps += 1 # 截取batch_size的大小 batch_images = real_images[batch_i * batch_size: (batch_i + 1) * batch_size] batch_label = real_label[batch_i * batch_size: (batch_i + 1) * batch_size] # batch_images重塑成[100,64,64,3],label变成独热编码的形式 batch_images = batch_images.reshape([batch_size, image_width, image_width, image_depth]) batch_label = tf.one_hot(indices=batch_label, depth=2, axis=1) batch_label = batch_label.eval() # batch_label = batch_label.reshape([batch_size, image_width, image_width, 2]) # 为了使用tanh激活函数,需要将数范围控制在[ -1, 1]之间 batch_images = batch_images * 2 - 1 # noise噪声输入 batch_noise = np.random.uniform(-1, 1, size=(batch_size, noise_size)) # run optimizer _ = sess.run(g_train_opt, feed_dict={inputs_label: batch_label, inputs_img: batch_images, inputs_noise: batch_noise}) _ = sess.run(d_train_opt, feed_dict={inputs_label: batch_label, inputs_img: batch_images, inputs_noise: batch_noise}) if steps % 20 == 0: train_loss_d = sess.run(d_loss, feed_dict={inputs_label: batch_label, inputs_img: batch_images, inputs_noise: batch_noise}) train_loss_d_real = sess.run(d_loss_real, feed_dict={inputs_label: batch_label, inputs_img: batch_images, inputs_noise: batch_noise}) train_loss_d_fake = sess.run(d_loss_fake, feed_dict={inputs_label: batch_label, inputs_img: batch_images, inputs_noise: batch_noise}) train_loss_g = sess.run(g_loss, feed_dict={inputs_label: batch_label, inputs_img: batch_images, inputs_noise: batch_noise}) # 输出损失值 print("Epoch {}({})/{}....".format(e + 1, steps / 20, epochs), "Discriminator Loss: {:.4f}(Real: {:.4f} + Fake: {:.4f})...".format(train_loss_d, train_loss_d_real, train_loss_d_fake), "Generator Loss: {:.4f}....".format(train_loss_g)) losses.append((train_loss_d, train_loss_d_real, train_loss_d_fake, train_loss_g)) ''' if(e >= 80): print("sample%s" % e) # 生成噪声图片 noise_shape = inputs_noise.get_shape().as_list()[-1] examples_noise = np.random.uniform(-1, 1, size=[n_samples, noise_shape]) # 设置自动随机标签,也可以人工设置 digits = np.zeros((n_samples, 2),dtype=np.int) for i in range(0, n_samples): #j = np.random.randint(0, 2, 1) j = 0 digits[i][j] = 1 D=[] #保存标签 f = open(os.path.join(output_label_path,'label%s.txt'%e), 'w+') for i in range(n_samples): jointsFrame = digits[i] # 每行 D.append(jointsFrame) for Ji in range(2): strNum = str(jointsFrame[Ji]) f.write(strNum) f.write(' ') f.write('\n') f.close() print("save label %s" % e) #生成样本 samples = sess.run(get_generator(inputs_noise, inputs_label, image_depth, False), feed_dict={inputs_noise: examples_noise, inputs_label: digits}) #保存样本图片 show_result(e, samples, output_path) ''' if (e == 250): saver.save(sess, "./model_250.ckpt") print("MODEL SAVED!") elif (flag == 1): saver.restore(sess, "./model_1000.ckpt") # 生成噪声图片 noise_shape = inputs_noise.get_shape().as_list()[-1] examples_noise = np.random.uniform(-1, 1, size=[n_samples, noise_shape]) # 设置自动随机标签,也可以人工设置 digits = np.zeros((n_samples, 2), dtype=np.int) for i in range(0, n_samples): j = type digits[i][j] = 1 # 生成样本 samples = sess.run(get_generator(inputs_noise, inputs_label, image_depth, False), feed_dict={inputs_noise: examples_noise, inputs_label: digits}) samples = 0.5 * samples.reshape((samples.shape[0], image_height, image_width, image_depth)) + 0.5 for i, res in enumerate(samples): img = (res) * 255. img = img.astype(np.uint8) # print(img.shape[0],img.shape[1],img.shape[2]) # fname=fname+'epoch%s' % epoch+'img%s' % i imsave(os.path.join('output_1', f'app-img{str(i)}.png'), img) cv.imwrite('output.jpg', img)#保存生成的烟雾图 '''########################################################################## 接着就要写这个生成的样本sample怎么调用到应用程序中,以上是恢复模型的参考代码 ##########################################################################''' global type_seting type_now = type_seting with tf.Graph().as_default(): os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' train(in_label, noise_size, [-1, image_width, image_width, image_depth], batch_size, n_samples, flag=1, type=type_now) # 添加了flag和type,flag=0表示是训练并存储模型 flag=1表示是读取模型,type表示标签种类 print("生成烟雾图片成功") # print("x0=", global_x0) # print("y0=", global_y0) # print("x1=", global_x1) # print("y1=", global_y1) # print("\n") weight=global_x1-global_x0 height=global_y1-global_y0 resized1 = cv.imread('temp0.jpg')#读取最开始读入的图片 #cv.imshow('resized1-0.jpg', resized1) #cv.waitKey(10) img = cv.imread('output.jpg')#读取生成的烟雾图 resized0 = cv.resize(img, (weight, height), interpolation=cv.INTER_AREA) #cv.imshow('resized0.jpg', resized0) #cv.waitKey(10) #嵌入图片,resized1是原图,resized0是烟雾图片,中括号内为嵌入的坐标 resized1[global_y0:height+global_y0, global_x0:weight+global_x0] = resized0 #cv.imshow('resized1.jpg', resized1) cv.imwrite('temp1.jpg', resized1) resized2 = resized1 # 将最终生成的图片复制到全局变量中,在保存按钮中进行保存 #cv.imwrite('resized2.jpg', resized2) global final_picture # 此处声明该图片为全局变量 final_picture=resized2 #将最终生成的图片复制到全局变量中,在保存按钮中进行保存 #cv.imwrite('final_picture0.jpg', final_picture) #cv.waitKey(10) height, width, bytesPerComponent = resized1.shape #取彩色图片的长、宽、通道 bytesPerLine = 3 * width cv.cvtColor(resized1, cv.COLOR_BGR2RGB, resized1) QImg = QImage(resized1.data, width, height, bytesPerLine,QImage.Format_RGB888) pixmap = QPixmap.fromImage(QImg) self.label_ShowPicture.setPixmap(pixmap) #self.label_ShowPicture.setPixmap(QPixmap("resized1.jpg")) self.label_ShowPicture.setCursor(Qt.CrossCursor) print("已经嵌入") def save_composed_picture(self): global final_picture # 此处声明该图片为全局变量 cv.cvtColor(final_picture, cv.COLOR_BGR2RGB, final_picture) cv.imwrite('final_picture.jpg', final_picture) print("保存最终结果图片成功") if __name__ == "__main__": app = QtWidgets.QApplication(sys.argv) MainWindow = QtWidgets.QMainWindow() ui = Ui_MainWindow() ui.setupUi(MainWindow) MainWindow.show() sys.exit(app.exec_()) |