GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing github.com — SimplePCV/main.py at master · s-du/SimplePCV Expand file tree/ Copy pathmain.pyMore file actions 346 lines (268 loc) · 11.9 KB / Copy pathmain.pyFile metadata and controls346 lines (268 loc) · 11.9 KB 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 """ This is a super simple script to create PCV renders from height maps Based on Duguet, Florent & Girardeau-Montaut, Daniel. (2004). Rendu en Portion de Ciel Visible de Gros Nuages de Points 3D. """ import os import numpy as np import rasterio as rio import sys from PySide6.QtWidgets import * from PySide6.QtCore import * from PySide6.QtUiTools import QUiLoader from PySide6.QtGui import * import simplepcv as spcv import test_opti SCALE_FACTOR = 100 IMAGE_PATH = 'raster.tif' # Replace with path to image class UiLoader(QUiLoader): """ Subclass :class:`~PySide.QtUiTools.QUiLoader` to create the user interface in a base instance. Unlike :class:`~PySide.QtUiTools.QUiLoader` itself this class does not create a new instance of the top-level widget, but creates the user interface in an existing instance of the top-level class. This mimics the behaviour of :func:`PyQt4.uic.loadUi`. """ def __init__(self, baseinstance, customWidgets=None): """ Create a loader for the given ``baseinstance``. The user interface is created in ``baseinstance``, which must be an instance of the top-level class in the user interface to load, or a subclass thereof. ``customWidgets`` is a dictionary mapping from class name to class object for widgets that you've promoted in the Qt Designer interface. Usually, this should be done by calling registerCustomWidget on the QUiLoader, but with PySide 1.1.2 on Ubuntu 12.04 x86_64 this causes a segfault. ``parent`` is the parent object of this loader. """ QUiLoader.__init__(self, baseinstance) self.baseinstance = baseinstance self.customWidgets = customWidgets def createWidget(self, class_name, parent=None, name=''): """ Function that is called for each widget defined in ui file, overridden here to populate baseinstance instead. """ if parent is None and self.baseinstance: # supposed to create the top-level widget, return the base instance # instead return self.baseinstance else: if class_name in self.availableWidgets(): # create a new widget for child widgets widget = QUiLoader.createWidget(self, class_name, parent, name) else: # if not in the list of availableWidgets, must be a custom widget # this will raise KeyError if the user has not supplied the # relevant class_name in the dictionary, or TypeError, if # customWidgets is None try: widget = self.customWidgets[class_name](parent) except (TypeError, KeyError) as e: raise Exception( 'No custom widget ' + class_name + ' found in customWidgets param of UiLoader __init__.') if self.baseinstance: # set an attribute for the new child widget on the base # instance, just like PyQt4.uic.loadUi does. setattr(self.baseinstance, name, widget) # this outputs the various widget names, e.g. # sampleGraphicsView, dockWidget, samplesTableView etc. # print(name) return widget def loadUi(uifile, baseinstance=None, customWidgets=None, workingDirectory=None): """ Dynamically load a user interface from the given ``uifile``. ``uifile`` is a string containing a file name of the UI file to load. If ``baseinstance`` is ``None``, the a new instance of the top-level widget will be created. Otherwise, the user interface is created within the given ``baseinstance``. In this case ``baseinstance`` must be an instance of the top-level widget class in the UI file to load, or a subclass thereof. In other words, if you've created a ``QMainWindow`` interface in the designer, ``baseinstance`` must be a ``QMainWindow`` or a subclass thereof, too. You cannot load a ``QMainWindow`` UI file with a plain :class:`~PySide.QtGui.QWidget` as ``baseinstance``. ``customWidgets`` is a dictionary mapping from class name to class object for widgets that you've promoted in the Qt Designer interface. Usually, this should be done by calling registerCustomWidget on the QUiLoader, but with PySide 1.1.2 on Ubuntu 12.04 x86_64 this causes a segfault. :method:`~PySide.QtCore.QMetaObject.connectSlotsByName()` is called on the created user interface, so you can implemented your slots according to its conventions in your widget class. Return ``baseinstance``, if ``baseinstance`` is not ``None``. Otherwise return the newly created instance of the user interface. """ loader = UiLoader(baseinstance, customWidgets) if workingDirectory is not None: loader.setWorkingDirectory(workingDirectory) widget = loader.load(uifile) QMetaObject.connectSlotsByName(widget) return widget class PhotoViewer(QGraphicsView): def __init__(self, parent): super(PhotoViewer, self).__init__(parent) self._zoom = 0 self._empty = True self._scene = QGraphicsScene(self) self._photo = QGraphicsPixmapItem() self._scene.addItem(self._photo) self.setScene(self._scene) self.setTransformationAnchor(QGraphicsView.AnchorUnderMouse) self.setResizeAnchor(QGraphicsView.AnchorUnderMouse) self.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOn) self.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOn) self.setBackgroundBrush(QBrush(QColor(255, 255, 255))) self.setFrameShape(QFrame.NoFrame) self.setMinimumSize(400, 600) self.rect = False self.select_point = False self.setMouseTracking(True) self.origin = QPoint() self._current_rect_item = None self._current_point = None def has_photo(self): return not self._empty def showEvent(self, event): self.fitInView() super(PhotoViewer, self).showEvent(event) def fitInView(self, scale=True): rect = QRectF(self._photo.pixmap().rect()) print(rect) if not rect.isNull(): self.setSceneRect(rect) if self.has_photo(): unity = self.transform().mapRect(QRectF(0, 0, 1, 1)) print('unity: ', unity) self.scale(1 / unity.width(), 1 / unity.height()) viewrect = self.viewport().rect() print('view: ', viewrect) scenerect = self.transform().mapRect(rect) print('scene: ', viewrect) factor = min(viewrect.width() / scenerect.width(), viewrect.height() / scenerect.height()) self.scale(factor, factor) self._zoom = 0 def setPhoto(self, pixmap=None): self._zoom = 0 if pixmap and not pixmap.isNull(): self._empty = False self.setDragMode(QGraphicsView.ScrollHandDrag) self._photo.setPixmap(pixmap) else: self._empty = True self.setDragMode(QGraphicsView.NoDrag) self._photo.setPixmap(QPixmap()) self.fitInView() def toggleDragMode(self): if self.rect or self.select_point: self.setDragMode(QGraphicsView.NoDrag) else: if self.dragMode() == QGraphicsView.ScrollHandDrag: self.setDragMode(QGraphicsView.NoDrag) elif not self._photo.pixmap().isNull(): self.setDragMode(QGraphicsView.ScrollHandDrag) def get_selected_point(self): print(self._current_point) return self._current_point # mouse events def wheelEvent(self, event): print(self._zoom) if self.has_photo(): if event.angleDelta().y() > 0: factor = 1.25 self._zoom += 1 else: factor = 0.8 self._zoom -= 1 if self._zoom > 0: self.scale(factor, factor) elif self._zoom == 0: self.fitInView() else: self._zoom = 0 def mousePressEvent(self, event): if self.rect: pass elif self.select_point: pass super(PhotoViewer, self).mousePressEvent(event) def mouseMoveEvent(self, event): if self.rect: pass super(PhotoViewer, self).mouseMoveEvent(event) def mouseReleaseEvent(self, event): if self.rect: pass super(PhotoViewer, self).mouseReleaseEvent(event) def numpy_array_to_qpixmap(arr): height, width = arr.shape[:2] arr_rgb = np.ascontiguousarray(arr[..., ::-1]) # Convert BGR to RGB and ensure C-contiguity qimg = QImage(arr_rgb.data, width, height, arr_rgb.strides[0], QImage.Format_RGB888) return QPixmap.fromImage(qimg) class ImageViewer(QMainWindow): def __init__(self, image, type='PCV'): super().__init__() # load the ui basepath = os.path.dirname(__file__) basename = 'simplepcv' uifile = os.path.join(basepath, '%s.ui' % basename) print(uifile) loadUi(uifile, self) self.setWindowTitle('Create PCV Renders') self.image = image self.comboBox.addItems(['Red', 'Green', 'Blue']) # add viewer self.viewer = PhotoViewer(self) self.horizontalLayout_6.addWidget(self.viewer) if type=='PCV': vmin,vmax = spcv.compute_optimal_vmin_vmax(self.image) # Create the sliders and their labels self.slider_min.setMinimum(int(np.nanmin(self.image) * SCALE_FACTOR)) self.slider_min.setMaximum(int(np.nanmax(self.image) * SCALE_FACTOR)) if type=='PCV': self.slider_min.setValue(int(vmin * SCALE_FACTOR)) self.slider_min.valueChanged.connect(self.update_image) self.slider_max.setMinimum(int(np.nanmin(self.image) * SCALE_FACTOR)) self.slider_max.setMaximum(int(np.nanmax(self.image) * SCALE_FACTOR)) if type == 'PCV': self.slider_max.setValue(int(vmax * SCALE_FACTOR)) self.slider_max.valueChanged.connect(self.update_image) self.dial.valueChanged.connect(self.update_image) self.comboBox.currentIndexChanged.connect(self.update_image) # Compute gradient gradient_y, gradient_x = np.gradient(image) self.magnitude = np.sqrt(gradient_x ** 2 + gradient_y ** 2) self.threshold = np.percentile(self.magnitude, 85) self.max_gradient_zones = self.magnitude > self.threshold self.update_image() def update_image(self): # Get the min and max values from the sliders and rescale them vmin = self.slider_min.value() / SCALE_FACTOR vmax = self.slider_max.value() / SCALE_FACTOR color_factor = self.dial.value() / 100 color_choice = self.comboBox.currentIndex() # Update the labels with the current slider values self.min_value_label.setText(f"Current Min Value: {vmin:.4f}") self.max_value_label.setText(f"Current Max Value: {vmax:.4f}") pix = spcv.export_results(self.image, vmin, vmax, color_choice,color_factor, optimize_vrange=False) self.viewer.setPhoto(numpy_array_to_qpixmap(pix)) # Press the green button in the gutter to run the script. if __name__ == '__main__': # Test path with rio.open(IMAGE_PATH) as src: elevation = src.read(1) # Set masked values to np.nan elevation[elevation < 0] = np.nan height_data = elevation cellsize = 1 z_factor = 1 # Test the individual functions altitude = 45 # Default altitude azimuth = 315 # Default azimuth visibility = spcv.compute_sky_visibility(height_data) # visibility = spcv.compute_hillshade_for_grid(height_data) app = QApplication(sys.argv) viewer = ImageViewer(visibility, type='PCV') viewer.show() sys.exit(app.exec()) |
| You are visitor 01402792 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |