-
Notifications
You must be signed in to change notification settings - Fork 0
/
camera_calib.py
324 lines (266 loc) · 11.4 KB
/
camera_calib.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
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'myqt5.ui'
#
# Created by: PyQt5 UI code generator 5.15.6
#
# WARNING: Any manual changes made to this file will be lost when pyuic5 is
# run again. Do not edit this file unless you know what you are doing.
import json
from functools import partial
import cv2
import numpy as np
import sys
from PyQt5 import QtCore, QtWidgets
from PyQt5.QtCore import Qt, QPoint
from PyQt5.QtWidgets import QLabel, QApplication, QMainWindow
from PyQt5.QtGui import QPixmap, QImage, QPainter, QPen, QPolygon
points1 = []
points2 = []
flag_rgb = False
matrix = None
back_matrix = None
class MyLabel(QLabel):
# 鼠标点击事件
def mousePressEvent(self, event):
# param 表示是否是rgb图片
# points1,points2分别存放rgb和黑外的特征点
if flag_rgb is None:
return
points = points1 if flag_rgb else points2
if event.buttons() == Qt.LeftButton:
points.append([event.x(), event.y()])
print([event.x(), event.y()])
elif event.buttons() == Qt.RightButton:
if len(points) != 0:
points.pop()
# 绘制事件
def paintEvent(self, event):
super().paintEvent(event)
if flag_rgb is None:
return
painter = QPainter(self)
painter.setPen(QPen(Qt.red, 5, Qt.SolidLine))
points = points1 if flag_rgb else points2
box = []
for p in points:
box.append(QPoint(p[0], p[1]))
painter.drawPoint(p[0], p[1])
painter.drawPolygon(QPolygon(box))
# painter.drawPoints(box)
self.update()
class Ui_MainWindow(object):
def __init__(self, rbg_im, ray_im):
self.rgb_img = rbg_im
self.ray_img = ray_im
self.blend_img = None
self.h, self.w = rbg_im.shape[:2]
self.rgb_pixmap = self.opencv2Qimage(rbg_im)
self.ray_pixmap = self.opencv2Qimage(ray_im)
self.blend_pixmap = None
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(1080, 720)
MainWindow.setFixedSize(MainWindow.width(), MainWindow.height())
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.frame = QtWidgets.QFrame(self.centralwidget)
self.frame.setGeometry(QtCore.QRect(900, 50, 160, 600))
self.frame.setFrameShape(QtWidgets.QFrame.StyledPanel)
self.frame.setFrameShadow(QtWidgets.QFrame.Raised)
self.frame.setObjectName("frame")
self.frame.setStyleSheet("border: 2px solid gray")
self.rgb_label = QtWidgets.QLabel(self.frame)
self.rgb_label.setGeometry(QtCore.QRect(20, 20, 121, 61))
self.rgb_label.setObjectName("rgb_label")
self.ray_label = QtWidgets.QLabel(self.frame)
self.ray_label.setGeometry(QtCore.QRect(20, 120, 121, 81))
self.ray_label.setObjectName("ray_label")
self.compare_btn = QtWidgets.QPushButton(self.frame)
self.compare_btn.setGeometry(QtCore.QRect(20, 400, 121, 41))
self.compare_btn.setObjectName("compare_btn")
self.compare_btn.clicked.connect(MainWindow.compare)
self.finish_btn = QtWidgets.QPushButton(self.frame)
self.finish_btn.setGeometry(QtCore.QRect(20, 490, 121, 41))
self.finish_btn.setObjectName("finish_btn")
self.blend_label = QtWidgets.QLabel(self.frame)
self.blend_label.setGeometry(QtCore.QRect(20, 240, 121, 81))
self.blend_label.setObjectName("")
self.blend_label.setStyleSheet("border: 2px solid gray")
# self.image = QtWidgets.QLabel(self.centralwidget)
self.image = MyLabel(self.centralwidget)
self.image.setGeometry(QtCore.QRect(40, 50, 800, 600))
self.image.setStyleSheet("border: 2px solid gray")
self.image.setScaledContents(True)
self.image.setText("")
self.image.setObjectName("image")
MainWindow.setCentralWidget(self.centralwidget)
self.statusbar = QtWidgets.QStatusBar(MainWindow)
self.statusbar.setObjectName("statusbar")
MainWindow.setStatusBar(self.statusbar)
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def opencv2Qimage(self, img):
height, width = img.shape[:2]
bytesPerLine = 3 * width
cv2.cvtColor(img, cv2.COLOR_BGR2RGB, img)
QImg = QImage(img.data, width, height, bytesPerLine, QImage.Format_RGB888)
pixmap = QPixmap.fromImage(QImg)
return pixmap
def switchImg(self, param):
"""
根据param判断切换什么图片
param : 0 显示红外图
1 显示rgb图
2 显示融合后的图
"""
global flag_rgb
if param == 0:
flag_rgb = False
self.image.setPixmap(self.ray_pixmap)
elif param == 1:
flag_rgb = True
# self.image.resize(self.w/2*1.5, self.h/2*1.5)
self.image.setPixmap(self.rgb_pixmap)
else:
if self.blend_pixmap is None or flag_rgb is None:
return
flag_rgb = None
self.image.setPixmap(self.blend_pixmap)
def switchImg2rgb(self, param):
global flag_rgb
flag_rgb = True
# self.image.resize(self.w/2*1.5, self.h/2*1.5)
self.image.setPixmap(self.rgb_pixmap)
def switchImg2ray(self, param):
global flag_rgb
flag_rgb = False
# self.image.resize(384*2, 288*2)
self.image.setPixmap(self.ray_pixmap)
def switchImg2blend(self, param):
global flag_rgb
if self.blend_pixmap is None or flag_rgb is None:
return
flag_rgb = None
self.image.setPixmap(self.blend_pixmap)
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "红外校准"))
self.rgb_label.setText(_translate("MainWindow", "rgb_img"))
self.rgb_label.setStyleSheet("border: 2px solid gray")
self.rgb_label.setPixmap(self.rgb_pixmap)
self.rgb_label.setScaledContents(True)
self.rgb_label.mousePressEvent = self.switchImg2rgb # 设置图片点击事件 #partial(self.switchImg, 0) #
self.ray_label.setText(_translate("MainWindow", "ray_img"))
self.ray_label.setStyleSheet("border: 2px solid gray")
self.ray_label.setPixmap(self.ray_pixmap)
self.ray_label.setScaledContents(True)
self.ray_label.mousePressEvent = self.switchImg2ray
self.blend_label.setText(_translate("MainWindow", ""))
self.blend_label.mousePressEvent = self.switchImg2ray
self.blend_label.setScaledContents(True)
self.blend_label.mousePressEvent = self.switchImg2blend
self.compare_btn.setText(_translate("MainWindow", "配准"))
self.finish_btn.setText(_translate("MainWindow", "完成"))
class mywindow(QtWidgets.QMainWindow, Ui_MainWindow):
def __init__(self, img1, img2):
super(mywindow, self).__init__(rbg_im=img1, ray_im=img2)
self.setupUi(self)
# 将界面的像素坐标转换成图片实际的像素坐标
def getRealPos(self):
label_width, label_height = self.image.width(), self.image.height()
rgb_height, rgb_width = self.rgb_img.shape[:2]
ray_height, ray_width = self.ray_img.shape[:2]
self.KP1 = np.array(points1) * [rgb_width / label_width, rgb_height / label_height]
self.KP2 = np.array(points2) * [ray_width / label_width, ray_height / label_height]
# 定义按钮绑定函数
def compare(self):
self.getRealPos()
# src表示红外数据上的特征点,dst表示rgb图像上的特征点
src = np.array(self.KP2, dtype=np.float32)
dst = np.array(self.KP1, dtype=np.float32)
# 将红外的特征点绘制在红外的图像上,用于判断校准是否正确
ray_imgc = self.ray_img.copy()
x = np.array(self.KP2, dtype=np.int32)
cv2.polylines(ray_imgc, [x], True, (0, 0, 255), thickness=2)
self.A = cv2.getPerspectiveTransform(src, dst)
# 将rgb图上的点投影到红外图上
self.backproject_A = cv2.getPerspectiveTransform(dst, src)
global matrix, back_matrix
matrix = self.A
back_matrix = self.backproject_A
camera_info = {'matrix': self.A, 'back_matrix': self.backproject_A, 'ray_point': self.KP2}
np.save("./data/camera_matrix.npy", camera_info)
# cc = np.load("data.npy", allow_pickle=True)
# print(cc.item().get("a"))
# print(cc.item().get("b"))
# pp = dst.reshape(1, -1, 2).astype(np.float32)
# pp = cv2.perspectiveTransform(pp, self.backproject_A)
# print(pp)
# raypoint = backproject * rgb_point
img_warp = cv2.warpPerspective(ray_imgc, self.A, (self.w, self.h), borderValue=125)
# newimg = self.rgb_img / 2 + img_warp / 2
newimg = cv2.addWeighted(self.rgb_img, 0.5, img_warp, 0.5, 0)
self.blend_img = np.array(newimg, dtype=np.uint8)
self.blend_pixmap = self.opencv2Qimage(self.blend_img)
self.blend_label.setPixmap(self.blend_pixmap)
def get_matrix(img1, img2):
app = QtWidgets.QApplication(sys.argv)
# img1 = cv2.imread('./data/images/1.png')
# img2 = cv2.imread('./data/images/2.png')
MainWindow = mywindow(img1=img1, img2=img2)
MainWindow.show()
exit(app.exec_())
return matrix, back_matrix
# input rgb pos, output transformed ray pos
# point [[x, y],....] nx2
# 返回类型 numpy[nx2]
# def back_projection(point, back_matrix):
# if type(point) != np.ndarray:
# point = np.array(point)
# point = point.reshape(1, -1, 2).astype(np.float32)
# pp = cv2.perspectiveTransform(point, back_matrix)
# return pp.reshape(-1, 2).astype(np.int)
# # return pp.reshape(-1).astype(np.int).tolist()
# 矩形转成对应的ray的四个点
# input [[x1,y1, x2, y2]...]
# 返回类型 numpy[nx2]
def back_projection(rect_boxes, back_matrix):
ret_points = []
for box in rect_boxes:
x1, y1, x2, y2 = box
ret_points.extend([x1, y1, x2, y1, x2, y2, x1, y2])
if type(ret_points) != np.ndarray:
ret_points = np.array(ret_points)
point = ret_points.reshape(1, -1, 2).astype(np.float32)
pp = cv2.perspectiveTransform(point, back_matrix)
return pp.reshape(-1, 2).astype(np.int)
def load_matrix():
cc = np.load("./data/camera_matrix1.npy", allow_pickle=True)
return cc.item()['matrix'], cc.item()['back_matrix']
# def test(frame, ret_img):
# matrix, back_matrix = load_matrix()
# box = [[20, 40, 800, 600], [300, 400, 400, 500]]
#
# for pp in box:
# cv2.rectangle(frame, (pp[0], pp[1]), (pp[2], pp[3]), (0, 0, 255), thickness=3)
#
# points = box2points(box)
# print(points)
# points = back_projection(points, back_matrix)
# print(points)
#
# x = np.array(points, dtype=np.int32)
# cv2.polylines(ret_img, [x[:4]], True, (0, 0, 255), thickness=2)
# cv2.polylines(ret_img, [x[4:]], True, (0, 0, 255), thickness=2)
#
# cv2.imshow('frame', frame)
# cv2.imshow('ray', ret_img)
# cv2.waitKey(0)
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
img1 = cv2.imread('./data/images/1.png')
img2 = cv2.imread('./data/images/2.png')
test(img1, img2)
# MainWindow = mywindow(img1=img1, img2=img2)
# MainWindow.show()
# exit(app.exec_())