-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMainwindow.py
303 lines (254 loc) · 10.2 KB
/
Mainwindow.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
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
from PyQt5.QtWidgets import QRadioButton,QPushButton,QFileDialog, QGridLayout,QApplication,QGroupBox,QVBoxLayout
from PyQt5.QtWidgets import QLineEdit,QDialog,QProgressBar,QScrollArea,QWidget,QLabel,QComboBox
from PyQt5.QtCore import Qt,pyqtSignal
from PyQt5.QtGui import QPixmap,QMouseEvent
from progressbar import progressbar
import qdarkstyle
import sys
import ft
from keras.applications.vgg16 import VGG16
from keras.applications.vgg19 import VGG19
import cv2 as cv
import os
import scipy.io as io
import math
import numpy as np
import sys
class MyQLabel(QLabel):
"""
自定义可点击的label
"""
button_clicked_signal = pyqtSignal()
def __init__(self,parent=None):
super(MyQLabel, self).__init__(parent)
def mouseReleaseEvent(self, QMouseEvent) -> None:
self.button_clicked_signal.emit()
def connect_customized_slot(self,func):
self.button_clicked_signal.connect(func)
class WidegtGallery(QDialog):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.setWindowTitle("图像检索系统")
self.resize(1500,900)
main_layout = QGridLayout()
self.setLayout(main_layout)
self.ini_group = QGroupBox("初始化")
self.create_ini()
main_layout.addWidget(self.ini_group,0,0)
self.frame1 = QGroupBox("检索模块")
self.create_search()
main_layout.addWidget(self.frame1,1,0)
self.picframe = QGroupBox("检索结果")
self.create_pic()
main_layout.addWidget(self.picframe,0,1,2,2)
def create_search(self):
"""
创建检索界面
"""
layout = QGridLayout()
self.frame1.setLayout(layout)
up_button = QPushButton("选择检索图像")
self.combobutton = QComboBox()
sear_button = QPushButton("搜索")
self.imgpath = QLineEdit("待检索图像")
self.sear_img = MyQLabel()
self.sear_img.setStyleSheet("border:1px solid gray")
self.combobutton.addItems(["基于语义(VGG16)","基于内容(SIFT)","基于语义(VGG19)"])
self.combobutton.setToolTip("选择使用的算法")
self.combobutton.setItemData(0,"一种基于语义的检索方法,\n以图像的含义为检测标准,\n速度较快且准确率较高",Qt.ToolTipRole)
self.combobutton.setItemData(1,"一种基于内容的检索方法,\n以物体形状为检测标准,\n速度最快但牺牲部分准确率",Qt.ToolTipRole)
self.combobutton.setItemData(2,"一种基于语义的检索方法,\n以图像的含义为检测标准,\n速度较快且准确率较高",Qt.ToolTipRole)
# 固定相框大小
self.sear_img.setMaximumSize(300,300)
self.sear_img.setMinimumSize(300,300)
layout.setContentsMargins(30,30,30,30)
layout.setSpacing(10)
layout.addWidget(up_button,0,0)
layout.addWidget(self.combobutton,1,0)
layout.addWidget(sear_button,2,0)
layout.addWidget(self.imgpath,3,0)
layout.addWidget(self.sear_img,4,0)
up_button.clicked.connect(self.search_)
sear_button.clicked.connect(self.sear_)
pass
def search_(self):
"""
检索事件中的选择图像
"""
path = QFileDialog.getOpenFileName(self,"选择图像..",filter="图像(*.jpg;*.png)")
self.imgpath.setText(path[0])
photo = QPixmap()
photo.load(path[0])
self.sear_img.setPixmap(photo)
pass
def sear_(self):
"""
检索事件
"""
if(self.combobutton.currentText()=="基于语义(VGG16)"):
mat = io.loadmat("./LIB/VGG16_LIB.mat")
conv_base = VGG16(weights="imagenet",include_top=False, input_shape=(150,150,3),pooling='avg')
feature1 = ft.extract_feature(conv_base,self.imgpath.text())
elif(self.combobutton.currentText()=="基于语义(VGG19)"):
mat = io.loadmat("./LIB/VGG19_LIB.mat")
conv_base = VGG19(weights="imagenet",include_top=False, input_shape=(150,150,3),pooling='avg')
feature1 = ft.extract_feature(conv_base,self.imgpath.text())
elif(self.combobutton.currentText()=="基于内容(SIFT)"):
mat = io.loadmat("./LIB/SIFT_LIB.mat")
voc = np.loadtxt("./LIB/siftBOW.npy",dtype='float32')
sift = cv.SIFT_create()
detector = cv.DescriptorMatcher_create("BruteForce")
img = cv.imread(self.imgpath.text())
bowde = cv.BOWImgDescriptorExtractor(sift, detector)
bowde.setVocabulary(voc)
des = sift.detect(img)
feature1 = bowde.compute(img,des)
dis_dict = dict()
for i in mat:
try:
dis = mat[i]-feature1
dis_dict[i] = np.linalg.norm(dis)
except:pass
# 待检测图像
# 排序
dis_dict = sorted(dis_dict.items(),key=lambda x:x[1],reverse=False)[:20]
for i in range(len(dis_dict)):
path = dis_dict[i][0].replace("/","\\")
photo = QPixmap()
photo.load(dis_dict[i][0])
self.label_list[i].setPixmap(photo)
self.label_list[i].setToolTip(path)
self.label_list[i].connect_customized_slot(lambda:os.system("explorer.exe /select,%s" % path))
pass
def create_pic(self):
"""
用于展示检索结果的界面
"""
layout = QGridLayout()
la = QGridLayout()
total = 20
sc = QScrollArea()
sc.setMinimumSize(100,100)
sc.setFixedSize(1200,1000)
layout.addWidget(sc,0,0)
a = QWidget()
self.label_list = []
# 添加显示的图像
for i in range(total):
photo = QPixmap()
path = i
label = MyQLabel()
label.setMinimumSize(300,300)
self.label_list.append(label)
label.setPixmap(photo)
label.setToolTip(str(path))
label.setStyleSheet("border:1px solid gray")
col = math.floor(i/4)
row = i-col*4
la.addWidget(label,col,row)
a.setLayout(la)
sc.setWidget(a)
photo.load("data/noise_test/noise_test\image_0002.jpg")
self.picframe.setLayout(layout)
pass
def create_ini(self):
"""
创建初始化布局
"""
# 定义控件
ini_button = QPushButton("初始化")
upini_button = QPushButton("选择图像库")
self.libpath = QLineEdit("图像库路径")
Linelabel = QLabel("初始化进度")
group = QGroupBox("进度")
gr_l = QGridLayout()
gr_l.setContentsMargins(0,0,0,0)
self.ini_bar = QProgressBar()
gr_l.addWidget(self.ini_bar)
group.setLayout(gr_l)
# 把长度定长一点
ini_button.setMinimumSize(100,60)
ini_button.setMaximumSize(100,60)
upini_button.setMaximumSize(100,60)
upini_button.setMinimumSize(100,60)
#self.libpath.setMaximumHeight(50)
#self.libpath.setMinimumWidth(100)
# 添加控件
input_layout = QGridLayout()
input_layout.setContentsMargins(30,30,30,30)
# input_layout.addWidget(Linelabel)
input_layout.addWidget(self.ini_bar,0,0,1,2)
# input_layout.addWidget(group,0,0,2,2)
input_layout.addWidget(upini_button,1,1)
input_layout.addWidget(ini_button,1,0)
"""
input_layout.addWidget(Linelabel,0,0)
input_layout.addWidget(self.ini_bar,0,1)
input_layout.addWidget(upini_button,1,0)
input_layout.addWidget(ini_button,2,0)
input_layout.addWidget(self.libpath)
self.libpath.setVisible(False)
"""
upini_button.clicked.connect(self.loadlib)
ini_button.clicked.connect(self.ini_lib)
self.ini_group.setLayout(input_layout)
def loadlib(self):
"""
加载图像库文件,连接于初始化界面
"""
path = QFileDialog.getExistingDirectory(self,"选择图像库路径..")
self.libpath.setText(path)
def ini_lib(self):
"""
初始化图像数据库
"""
dir = self.libpath.text()
sift = cv.SIFT_create()
detector = cv.DescriptorMatcher_create("BruteForce")
conv_base16 = VGG16(weights="imagenet",include_top=False, input_shape=(150,150,3),pooling='avg')
conv_base19 = VGG19(weights="imagenet",include_top=False, input_shape=(150,150,3),pooling='avg')
feature_dic = dict()
feature_dic19 = dict()
s_dic = dict()
self.ini_bar.setMinimum(0)
# 构建词袋模型
for dirname,_,filesname in os.walk(dir):
all = len(filesname)
self.ini_bar.setMaximum(2*all)
num=0
for i in filesname:
path = dir+'/'+i
img = cv.imread(path)
kp = sift.detect(img, None)
kp,des = sift.compute(img, kp)
bow = cv.BOWKMeansTrainer(20)
bow.add(des)
siftdic = bow.cluster()
num+=1
self.ini_bar.setValue(num)
np.savetxt("./LIB/siftBOW.npy",siftdic)
bowde = cv.BOWImgDescriptorExtractor(sift,detector)
bowde.setVocabulary(siftdic)
for dirname,_,filesname in os.walk(dir):
for i in filesname:
path = dir+'/'+i
img = cv.imread(path)
des = sift.detect(img)
val = bowde.compute(img,des)
s_dic[path]=val
feature = ft.extract_feature(conv_base16,path)
feature_dic[path]=feature
feature = ft.extract_feature(conv_base19,path)
feature_dic19[path]=feature
num+=1
self.ini_bar.setValue(num)
io.savemat("./LIB/VGG16_LIB",feature_dic)
io.savemat("./LIB/VGG19_LIB",feature_dic19)
io.savemat("./LIB/SIFT_LIB",s_dic)
pass
if __name__ == "__main__":
app = QApplication(sys.argv)
app.setStyleSheet(qdarkstyle.load_stylesheet_pyqt5())
dialog = WidegtGallery()
if dialog.exec_() == QDialog.Accepted:
sys.exit(app.exec_())