Debian Codegraph @

planetary_system_stacker/Test_programs/frame_viewer_test.py

raw symbols SCIP
1 from sys import argv
2
3 from PyQt5 import QtCore, QtGui, QtWidgets
4 from cv2 import NORM_MINMAX, normalize, cvtColor, COLOR_GRAY2RGB, circle, line
5 from numpy import uint8, uint16
6
7 from exceptions import NotSupportedError
8 from frame_viewer_test_gui import Ui_Frame
9 from frames import Frames
10
11
12 class FrameViewer(QtWidgets.QGraphicsView):
13 """
14 This widget implements a frame viewer. Panning and zooming is implemented by using the mouse
15 and scroll wheel.
16
17 """
18
19 def __init__(self):
20 super(FrameViewer, self).__init__()
21 self._empty = True
22
23 # Initialize a flag which indicates when an image is being loaded.
24 self.image_loading_busy = False
25
26 # Initialize the scene. This object handles mouse events if not in drag mode.
27 self._scene = QtWidgets.QGraphicsScene()
28 # Initialize the photo object. No image is loaded yet.
29 self._photo = QtWidgets.QGraphicsPixmapItem()
30 self._scene.addItem(self._photo)
31 self.setScene(self._scene)
32
33 self.setTransformationAnchor(QtWidgets.QGraphicsView.AnchorUnderMouse)
34 self.setResizeAnchor(QtWidgets.QGraphicsView.AnchorUnderMouse)
35 self.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
36 self.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
37 self.setBackgroundBrush(QtGui.QBrush(QtGui.QColor(30, 30, 30)))
38 self.setFrameShape(QtWidgets.QFrame.NoFrame)
39 self.setDragMode(QtWidgets.QGraphicsView.ScrollHandDrag)
40 self.drag_mode = True
41
42 # Set the focus on the viewer.
43 self.setFocus()
44
45 def resizeEvent(self, event):
46 """
47 This method is called when the window size changes. In this case the image is zoomed so it
48 fills the entire view.
49
50 :param event: Resize event.
51 :return: -
52 """
53
54 # Set the rectangle surrounding the current view.
55 self.viewrect = self.viewport().rect()
56 self.fitInView()
57 return super(FrameViewer, self).resizeEvent(event)
58
59 def hasPhoto(self):
60 return not self._empty
61
62 def fitInView(self):
63 """
64 Scale the scene such that it fits into the window completely.
65
66 :return: -
67 """
68
69 if not self.photorect.isNull():
70 if self.hasPhoto():
71 factor = min(self.viewrect.width() / self.scenerect.width(),
72 self.viewrect.height() / self.scenerect.height())
73 self.scale(factor, factor)
74 self.scenerect = self.transform().mapRect(self.photorect)
75
76 def set_original_scale(self):
77 """
78 Scale the scene to the original size of the photo. If the photo has more pixels than the
79 current view, only part of the image is displayed.
80
81 :return: -
82 """
83
84 if not self.photorect.isNull():
85 if self.hasPhoto():
86 factor = min(self.photorect.width() / self.scenerect.width(),
87 self.photorect.height() / self.scenerect.height())
88 self.scale(factor, factor)
89 self.scenerect = self.transform().mapRect(self.photorect)
90
91 def setPhoto(self, image, overlay_exclude_mark=False):
92 """
93 Convert a color or grayscale image to a pixmap and assign it to the photo object.
94
95 :param image: Image to be displayed. The image is assumed to be in color or grayscale
96 format of length uint8 or uint16.
97 :param overlay_exclude_mark: If True, overlay a crossed-out red circle in the upper left
98 corner of the image.
99 :return: -
100 """
101
102 # Indicate that an image is being loaded.
103 self.image_loading_busy = True
104
105 # Convert the image into uint8 format. If the frame type is uint16, values correspond to
106 # 16bit resolution.
107 if image.dtype == uint16:
108 image_uint8 = (image / 256.).astype(uint8)
109 elif image.dtype == uint8:
110 image_uint8 = image.astype(uint8)
111 else:
112 raise NotSupportedError("Attempt to set a photo in frame viewer with type neither"
113 " uint8 nor uint16")
114
115 self.shape_y = image_uint8.shape[0]
116 self.shape_x = image_uint8.shape[1]
117
118 # Normalize the frame brightness.
119 image_uint8 = normalize(image_uint8, None, alpha=0, beta=255, norm_type=NORM_MINMAX)
120
121 # Overlay a crossed-out red circle in the upper left image corner.
122 if overlay_exclude_mark:
123 if len(image_uint8.shape) == 2:
124 image_uint8 = cvtColor(image_uint8, COLOR_GRAY2RGB)
125
126 # The position and size of the mark are relative to the image size.
127 pos_x = int(round(self.shape_x / 10))
128 pos_y = int(round(self.shape_y / 10))
129 diameter = int(round(min(pos_x, pos_y) / 4))
130 circle(image_uint8, (pos_x, pos_y), diameter, (255, 0, 0), 2)
131 line(image_uint8, (pos_x - diameter, pos_y + diameter),
132 (pos_x + diameter, pos_y - diameter), (255, 0, 0), 2)
133
134 # The image is monochrome:
135 if len(image_uint8.shape) == 2:
136 qt_image = QtGui.QImage(image_uint8, self.shape_x, self.shape_y, self.shape_x,
137 QtGui.QImage.Format_Grayscale8)
138 # The image is RGB color.
139 else:
140 qt_image = QtGui.QImage(image_uint8, self.shape_x,
141 self.shape_y, 3 * self.shape_x, QtGui.QImage.Format_RGB888)
142 pixmap = QtGui.QPixmap(qt_image)
143
144 if pixmap and not pixmap.isNull():
145 self._empty = False
146 self._photo.setPixmap(pixmap)
147 else:
148 self._empty = True
149 self._photo.setPixmap(QtGui.QPixmap())
150
151 # Set the new rectangles surrounding the photo and the current scene.
152 self.photorect = QtCore.QRectF(self._photo.pixmap().rect())
153 self.scenerect = self.transform().mapRect(self.photorect)
154
155 # Release the image loading flag.
156 self.image_loading_busy = False
157
158 def wheelEvent(self, event):
159 """
160 Handle scroll events for zooming in and out of the scene. This is only active when a photo
161 is loaded.
162
163 :param event: wheel event object
164 :return: -
165 """
166
167 if self.drag_mode:
168 # Depending of wheel direction, set the direction value to greater or smaller than 1.
169 self.zoom(event.angleDelta().y())
170 print ("Wheel event")
171
172 # If not in drag mode, the wheel event is handled at the scene level.
173 else:
174 self._scene.wheelEvent(event)
175
176 def zoom(self, direction):
177 """
178 Zoom in or out. This is only active when a photo is loaded. For small images (smaller than
179 the current view), zooming out is limited by the original photo resolution. For larger
180 images zooming out stops when the scene fills the entire view.
181
182 :param direction: If > 0, zoom in, otherwise zoom out.
183 :return: -
184 """
185
186 if self.hasPhoto():
187 # Depending of direction value, set the zoom factor to greater or smaller than 1.
188 if direction > 0:
189 factor = 1.25
190 else:
191 min_factor = min(
192 min(self.photorect.width(), self.viewrect.width()) / self.scenerect.width(),
193 min(self.photorect.height(), self.viewrect.height()) / self.scenerect.height())
194 factor = max(0.8, min_factor)
195
196 self.scale(factor, factor)
197 self.scenerect = self.transform().mapRect(self.photorect)
198
199 def keyPressEvent(self, event):
200 """
201 The + and - keys are used for zooming.
202
203 :param event: event object
204 :return: -
205 """
206
207 # If the "+" key is pressed, zoom in. If "-" is pressed, zoom out.
208 if event.key() == QtCore.Qt.Key_Plus and not event.modifiers() & QtCore.Qt.ControlModifier:
209 self.zoom(1)
210 elif event.key() == QtCore.Qt.Key_Minus and not event.modifiers() & QtCore.Qt.ControlModifier:
211 self.zoom(-1)
212 elif event.key() == QtCore.Qt.Key_1 and not event.modifiers() & QtCore.Qt.ControlModifier:
213 self.set_original_scale()
214 else:
215 super(FrameViewer, self).keyPressEvent(event)
216
217
218 class FrameViewerWidget(QtWidgets.QFrame, Ui_Frame):
219
220 def __init__(self, input_image):
221 super(FrameViewerWidget, self).__init__()
222 self.setupUi(self)
223 frame_viewer = FrameViewer()
224 frame_viewer.setObjectName("frame_viewer")
225 frame_viewer.setFrameShape(QtWidgets.QFrame.Panel)
226 frame_viewer.setFrameShadow(QtWidgets.QFrame.Sunken)
227 frame_viewer.setMinimumSize(600, 600)
228 frame_viewer.setPhoto(input_image)
229 self.gridLayout.addWidget(frame_viewer, 0, 0, 1, 1)
230
231
232 if __name__ == '__main__':
233 # input_file_name = "D:\SW-Development\Python\PlanetarySystemStacker\Examples\Jupiter_Richard\\2020-07-29-2145_3-L-Jupiter_ALTAIRGP224C_pss_gpp.png"
234 input_file_name = "D:\SW-Development\Python\PlanetarySystemStacker\Examples\Jupiter_Richard\\" \
235 "2020-07-29-2145_3-L-Jupiter_ALTAIRGP224C_pss_p70_b48.png"
236 # input_file_name = "D:\SW-Development\Python\PlanetarySystemStacker\Examples\Moon_2018-03-24\Moon_Tile-024_043939_pss_drizzle2_gpp.png"
237 input_image = Frames.read_image(input_file_name)
238
239 app = QtWidgets.QApplication(argv)
240
241 window = FrameViewerWidget(input_image)
242 window.showMaximized()
243 app.exec_()