scenePyramid.py 33.8 KB
Newer Older
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
# -*- coding: utf-8 -*-
"""
GEPARD - Gepard-Enabled PARticle Detection
Copyright (C) 2018  Lars Bittrich and Josef Brandt, Leibniz-Institut für
Polymerforschung Dresden e. V. <bittrich-lars@ipfdd.de>

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program, see COPYING.
If not, see <https://www.gnu.org/licenses/>.
"""

import os
import warnings

import cv2
import math
import copy
import numpy as np
29
from .errors import TileSizeError
30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
from .helperfunctions import cv2imread_fix, cv2imwrite_fix
from PIL import Image
from PyQt5 import QtCore, QtGui, QtWidgets


# from .dataset import DataSet


class ScenePyramid:
    @staticmethod
    def getDefaults():
        """
        default values for all params, that get saved in dataset
        :return:
        """
        return {
46
            'scanModeComplete': False,
47
            'maxSliceNumber': 0,
48
            'tileDim': (1000, 1000),  # as np.ndarray.shape (i.e. (height, width))
49 50 51 52 53 54
            'scalingFactor': .5,
            'tileSets': {},
            'fullImageWidth': 0,
            'fullImageHeight': 0
        }

55
    def __init__(self, view: QtWidgets.QGraphicsView, logger=None):
56 57 58 59
        # references to other objects
        self.view: QtWidgets.QGraphicsView = view
        self.scene = self.view.scene()
        self.dataset = None
60
        self.logger = logger
61 62 63

        #
        self.opacity = 1
64 65 66 67
        self.npHeightIdx = 0  # np.ndarray.shape height idx
        self.npWidthIdx = 1   # np.ndarray.shape width idx
        self.cvHeightIdx = 1  # cv2 height idx
        self.cvWidthIdx = 0   # cv2 width idx
68 69 70 71 72
        self.currentSlice = None
        self.microscopeMode = None
        self.currentTiles = None
        self.tileWorkingSets = None

73
        self.scanModeComplete = None
74
        self.maxSliceNumber = None
75
        self.tileDim = None  # as np.ndarray.shape (i.e. (height, width))
76 77 78 79 80 81 82
        self.scalingFactor = None
        self.tileSets = None
        self.fullImageWidth = None
        self.fullImageHeight = None

        # params to be saved to dataset
        self.datasetParams = [
83
            'scanModeComplete',
84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103
            'maxSliceNumber',
            'tileDim',
            'scalingFactor',
            'tileSets',
            'fullImageWidth',
            'fullImageHeight'
        ]

        self.initDefaults()

    def initDefaults(self):
        p = ScenePyramid.getDefaults()
        for i in p:
            setattr(self, i, p[i])

        self.currentSlice = 0
        self.microscopeMode = None
        self.currentTiles = []
        self.tileWorkingSets = {}

104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119
    def startScanMode(self):
        """

        :return:
        """
        self.scanModeComplete = False
        return self

    def endScanMode(self):
        """

        :return:
        """
        self.scanModeComplete = True
        return self

120 121 122 123 124
    def onScale(self):
        """
        gets called on zoom event in QGraphicsView
        :return:
        """
125
        if self.scanModeComplete:
126 127 128 129 130 131 132
            self.updateScene()

    def onMove(self):
        """
        gets called on scroll event in QGraphicsView
        :return:
        """
133
        if self.scanModeComplete:
134 135 136
            self.updateScene()

    def initScene(self):
137
        if self.scanModeComplete:
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
            self.updateScene()

    def updateScene(self):
        """
        gets called on move and scale of scene (scrolling and zooming)

        first determines pyramid slice to use so that
         width of slice >= self.view.mapFromScene(x, 0) - self.view.mapFromScene(0, 0)
        then, checks visibility of all view tiles and removes all that are invisible
         and renders those, that are visible
        :return:
        """
        current_slice = self.currentSlice
        self.determineSlice()

        slice_changed = current_slice != self.currentSlice

        if slice_changed:
            self.resetScene()

        # map viewport to scene
        view_origin = self.view.mapToScene(0, 0)
        view_max_x_y = self.view.mapToScene(self.view.width(), self.view.height())

        # get scene origin (given in microscope coords) in pixel coords
        scene_origin_x, scene_origin_y = (0, 0)  # self.dataset.mapToPixel(p, self.microscopeMode, force=True)

        # default width, height of view tiles
166
        view_tile_height, view_tile_width = self.tileDim
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

        inv_scaling = (1 / self.scalingFactor) ** self.currentSlice

        if self.currentSlice in self.tileWorkingSets:
            for i in self.tileWorkingSets[self.currentSlice]:
                for j in self.tileWorkingSets[self.currentSlice][i]:
                    # check visibility of view tile
                    tile_width, tile_height = self.getTileDimensions(i, j)

                    if tile_width is not False and tile_height is not False:
                        # get scene coords of tile
                        tile_origin_x = max(0, i * view_tile_width) + scene_origin_x
                        tile_origin_y = max(0, j * view_tile_height) + scene_origin_y

                        # view tile is of constant size, but will be scaled according to slice number (scaling)
                        # so its appearent size in the scene will be bigger
                        # and it will appear at a different position
                        t_o_x = max(0, i * inv_scaling * view_tile_width) + scene_origin_x
                        t_o_y = max(0, j * inv_scaling * view_tile_height) + scene_origin_y

                        # if tile intersects with viewport
                        if QtCore.QRectF(
                                t_o_x,
                                t_o_y,
                                tile_width * inv_scaling,
                                tile_height * inv_scaling
                        ).intersects(
                            QtCore.QRectF(
                                view_origin.x(),
                                view_origin.y(),
                                view_max_x_y.x() - view_origin.x(),
                                view_max_x_y.y() - view_origin.y()
                            )
                        ):
                            # show/reload tile
                            self.renderTile(i, j, tile_origin_x, tile_origin_y)
                        else:
                            # check if tile needs to be removed
                            self.removeTile(i, j)

        self.setTileOpacity(self.opacity)

    def determineSlice(self):
        """
        calculates current slice by using the view to scene ratio of the the image
        :return:
        """
        if 0 == self.fullImageWidth:
            self.currentSlice = 0
216
            return
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

        # tiles get added to the (theoretically infinite) scene which can be zoomed and translated
        # full image width and height are width and height in scene coordinates
        # we only see parts of the scene by using a view

        # gets the position of left upper tile origin (from scene) in view coordinates
        origin = self.view.mapFromScene(QtCore.QPoint(0, 0))
        # gets the position of lower right tile (from scene) in view coordinates
        max_x_y = self.view.mapFromScene(QtCore.QPoint(self.fullImageWidth, self.fullImageHeight))
        # current view size of all tiles
        cur_width = max_x_y.x() - origin.x()

        '''
         with f  = scaling factor
              s  = slice number
              w  = full image width
              w' = image width of slice
         a slices width can be calculated by
           w' = f^s * w
         the current slice can be calculated by
           s = floor( log( w/w', f ) )
         with accounting for lowest = 0 and highest slice number = s_max we get
           s = min( s_max, max( 0, floor( log( w/w', f )))
        '''
        self.currentSlice = min(
            self.maxSliceNumber,
            max(
                0,
                math.floor(
                    math.log(
                        cur_width / self.fullImageWidth,
                        self.scalingFactor
                    )
                )
            )
        )

    def updateSceneAfterViewTileUpdate(self, scan_tile_pos):
        """
        gets called by self.addSrcTile after adding a new scan tile, to update all view tiles, that may have changed
        up to 4 tiles may have to be updated. and because we are lazy we update all 4 every time
        after determining the view tile (i, j) that holds the origin of the last added scan tile, we update
        (i, J    ), (i + 1, j    )
        (i, j + 1), (i + 1, j + 1)
        :param scan_tile_pos:
        :return:
        """
        self.determineSlice()

        cur_scaling = self.scalingFactor ** self.currentSlice
        inv_scaling = 1 / cur_scaling
        cur_full_image_width = cur_scaling * self.fullImageWidth
        cur_full_image_height = cur_scaling * self.fullImageHeight

        # get scene origin (given in microscope coords) in pixel coords
        p = self.dataset.maxdim[:2]
        scene_origin_x, scene_origin_y = (0, 0)  # self.dataset.mapToPixel(p, self.microscopeMode, force=True)

        # scaled position of currently added scan tile
276 277
        pos_x = cur_scaling * scan_tile_pos[self.npHeightIdx]
        pos_y = cur_scaling * scan_tile_pos[self.npWidthIdx]
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

        # default width, height of view tiles
        view_tile_width, view_tile_height = self.tileDim

        # indices of the tile, the src tiles origin is located in
        i = math.floor(pos_x / view_tile_width)
        j = math.floor(pos_y / view_tile_height)

        # max tile count in either direction on current scaling
        max_tiles_x = math.ceil(cur_full_image_width / view_tile_width)
        max_tiles_y = math.ceil(cur_full_image_height / view_tile_height)

        # map viewport to scene
        view_origin = self.view.mapToScene(0, 0)
        view_max_x_y = self.view.mapToScene(self.view.width(), self.view.height())

        for t_i in [0, 1]:
            for t_j in [0, 1]:
                i_cur = i + t_i
                j_cur = j + t_j
                if i_cur <= max_tiles_x and j_cur <= max_tiles_y:
                    # determine visibility of tile (i_cur, j_cur)
                    # get true width and height of tile (i_cur, j_cur)
                    tile_width, tile_height = self.getTileDimensions(i_cur, j_cur)

                    if tile_width is not False and tile_height is not False:
                        # get scene coords of tile
                        tile_origin_x = max(0, i_cur * view_tile_width) + scene_origin_x
                        tile_origin_y = max(0, j_cur * view_tile_height) + scene_origin_y

                        # view tile is of constant size, but will be scaled according to slice number (scaling)
                        # so its appearent size in the scene will be bigger
                        # and it will appear at a different position
                        t_o_x = max(0, i_cur * inv_scaling * view_tile_width) + scene_origin_x
                        t_o_y = max(0, j_cur * inv_scaling * view_tile_height) + scene_origin_y

                        # if tile intersects with viewport
                        if QtCore.QRectF(
                                t_o_x,
                                t_o_y,
                                tile_width * inv_scaling,
                                tile_height * inv_scaling
                        ).intersects(
                            QtCore.QRectF(
                                view_origin.x(),
                                view_origin.y(),
                                view_max_x_y.x() - view_origin.x(),
                                view_max_x_y.y() - view_origin.y()
                            )
                        ):
                            # show/reload tile
                            self.renderTile(i_cur, j_cur, tile_origin_x, tile_origin_y, force=True)

    def getTile(self, i, j, use_slice=None):
        """
        returns tile (i, j) of current (self.currentSlice) or given slice.
        tile (i, j) contains the dimensions of the corresponding tile image
        and a reference to the rendered QGraphicsPixmapItem

        :param int i:
        :param int j:
        :param int use_slice:
        :return: tile or False
        :rtype: QtWidgets.QGraphicsPixmapItem or False
        """
        s = self.currentSlice if use_slice is None else use_slice
        if s in self.tileWorkingSets \
                and i in self.tileWorkingSets[s] \
                and j in self.tileWorkingSets[s][i]:
            return self.tileWorkingSets[s][i][j]

        return False

    def getTileDimensions(self, i, j, use_slice=None):
        """
        returns dimensions of tile (i, j) in slice use_slice
        @see self.getTile
        :param int i: row
        :param int j: line
        :param int use_slice: slice
        :return: (width, height)
        :rtype: (int, int) or (bool, bool)
        """

        tile = self.getTile(i, j, use_slice)
        if tile:
            return tile['dimensions']
        return False, False

    def removeTile(self, i, j, use_slice=None):
        """
        removes tile (i, j) of current (self.currentSlice) or given slice from scene
        and removes references to Qt object from pyramid and list of currently rendered tiles
        :param i:
        :param j:
        :param use_slice:
        :return:
        """
        tile = self.getTile(i, j, use_slice)
        if tile['rendered']:
            self.scene.removeItem(tile['rendered'])
            self.currentTiles.remove(tile['rendered'])
            tile['rendered'] = False

    def renderTile(self, i, j, x, y, force=False):
        """
        renders tile (i, j) to scene at position (x, y), if tile (i, j),
        saves a reference to a list of all currently rendered tiles and
        to the tile entry in the (multidimensional) list of all tiles
        if not rendered already (check omitted on force = True)
        :param i:
        :param j:
        :param x:
        :param y:
        :param force:
        :return:
        """
        rendered = not not self.tileWorkingSets[self.currentSlice][i][j]['rendered']
        if not rendered or force:
            if force:
                self.removeTile(i, j)

            img = self.readViewTile(self.currentSlice, i, j)
            item = QtWidgets.QGraphicsPixmapItem()

            # scale lower resolution tiles up (on slice > 0)
            inv_scale_factor = (1 / self.scalingFactor) ** self.currentSlice
            item.setScale(inv_scale_factor)

            # and adjust position of tile accordingly
408 409
            x += i * (inv_scale_factor - 1) * int(self.tileDim[self.npWidthIdx])
            y += j * (inv_scale_factor - 1) * int(self.tileDim[self.npHeightIdx])
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

            item.setPos(x, y)

            item.setAcceptedMouseButtons(QtCore.Qt.NoButton)
            height, width, channel = img.shape
            pix = QtGui.QPixmap()
            pix.convertFromImage(
                QtGui.QImage(img, width, height, 3 * width, QtGui.QImage.Format_RGB888)
            )
            item.setPixmap(pix)
            self.scene.addItem(item)
            self.currentTiles[len(self.currentTiles):] = [item]
            self.tileWorkingSets[self.currentSlice][i][j]['rendered'] = item

    def reset(self):
        """
        @todo pydoc
        :return:
        """
        self.resetScene()
        self.initDefaults()

    def resetScene(self):
        """
        removes all tiles and its references from scene and list of currently rendered tiles
        :return:
        """
        for s in self.tileWorkingSets:
            for i in self.tileWorkingSets[s]:
                for j in self.tileWorkingSets[s][i]:
                    self.removeTile(i, j, use_slice=s)
        # remove anything that may be left
        [self.scene.removeItem(i) for i in self.currentTiles]
        self.currentTiles = []

    def fromDataset(self, dataset=None):
        """
        set pyramid parameters loaded from dataset
        :param dataset:
        :return:
        """
        if dataset is not None:
            self.dataset = dataset

        if self.dataset is not None:
            pyramid_params = self.dataset.getPyramidParams()
            if pyramid_params is None:
                self.reset()
            else:
                for i in self.datasetParams:
460 461 462
                    if i in pyramid_params:
                        setattr(self, i, pyramid_params[i])

463
                self.tileWorkingSets = copy.deepcopy(self.tileSets)
464
                self.fixMissingTiles()
465 466 467 468 469 470 471 472 473

            self.setMicroscopeMode(self.dataset.imagescanMode)

    def toDataset(self):
        """
        saves pyramid params to dataset
        :return:
        """
        pyramid_params = {}
474
        self.fixMissingTiles()
475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494
        for i in self.datasetParams:
            pyramid_params[i] = getattr(self, i)

        if self.dataset:
            self.dataset.setPyramidParams(pyramid_params)

    def setMicroscopeMode(self, microscopemode):
        """
        sets microscope mode
        :param microscopemode:
        :return:
        """
        self.microscopeMode = microscopemode

    def getBoundingRectDim(self):
        """
        returns bounding rectangle of all currently rendered tiles
        :return: (width, height)
        :rtype: (int, int)
        """
495
        return self.fullImageWidth, self.fullImageHeight
496 497 498 499 500 501 502 503

    def addSrcTileSimple(self, img, pos, p):
        """
        gets called by opticalscan.takePoint() in scan setup process

        adds a src tile by pos and dimension
        """
        item = QtWidgets.QGraphicsPixmapItem()
504
        item.setPos(pos[self.cvWidthIdx], pos[self.cvHeightIdx])
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
        item.setAcceptedMouseButtons(QtCore.Qt.NoButton)
        height, width, channel = img.shape
        pix = QtGui.QPixmap()
        pix.convertFromImage(
            QtGui.QImage(img, width, height, 3 * width, QtGui.QImage.Format_RGB888)
        )
        item.setPixmap(pix)

        if 0 < len(self.currentTiles) and self.dataset.lastpos is not None:
            lp = self.dataset.lastpos
            dx, dy = (lp[0] - p[0]) / width * img.shape[1], (p[1] - lp[1]) / height * img.shape[0]
            li: QtWidgets.QGraphicsItem = self.currentTiles[-1:][0]
            newpos = li.pos()
            newpos.setX(newpos.x() + dx)
            newpos.setY(newpos.y() + dy)
            li.setPos(newpos)

        self.scene.addItem(item)
        self.currentTiles[len(self.currentTiles):] = [item]

    def addSrcTile(self, img, m_rot, v_trans, fullimgsize):
        """
        gets called by opticalscan.loadAndPasteImage() while scanning takes place
        adds a src tile by img data, transformation matrix, position, size of full image
        :param img:
        :param m_rot:
        :param v_trans:
        :param fullimgsize:
        :return:
        """
535 536
        self.fullImageWidth = current_full_image_width = fullimgsize[self.cvWidthIdx]
        self.fullImageHeight = current_full_image_height = fullimgsize[self.cvHeightIdx]
537 538

        # width, height of view tiles
539
        view_tile_height, view_tile_width = self.tileDim
540 541 542 543 544 545 546 547 548 549 550

        # dst pos of src tile
        pos_x, pos_y = v_trans

        breakof_pixel_count = max(self.tileDim) * self.scalingFactor
        current_scaling_factor = 1
        slice_nr = 0

        # if src tile dim < view tile dim, a single src tile s may be part of up to 4 view tiles v(i, j)
        while max(current_full_image_width, current_full_image_height) > breakof_pixel_count:
            # resize from original image, when adding src tile to scaled pyramid slices
551 552 553 554 555 556 557
            current_src_img = cv2.resize(
                img,
                None,
                fx=current_scaling_factor,
                fy=current_scaling_factor,
                interpolation=cv2.INTER_AREA
            )
558

559 560 561
            pos_x_scaled = current_scaling_factor * pos_x
            pos_y_scaled = current_scaling_factor * pos_y

562 563 564
            # width, height of src tile
            src_tile_height, src_tile_width = current_src_img.shape[:2]

565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583
            # position of src tile in first view tile
            src_tile_pos_x = pos_x_scaled % view_tile_width
            src_tile_pos_y = pos_y_scaled % view_tile_height

            # indices of tile, the src tiles origin is located in
            io = math.floor(pos_x_scaled / view_tile_width)
            jo = math.floor(pos_y_scaled / view_tile_height)

            # indices of tiles, the src tile is reaching in
            ie = math.floor((pos_x_scaled + src_tile_width) / view_tile_width)
            je = math.floor((pos_y_scaled + src_tile_height) / view_tile_height)

            # move in x direction
            for i in range(io, ie + 1):
                cur_src_tile_pos_y = src_tile_pos_y
                # move in y direction
                for j in range(jo, je + 1):
                    # add to v(i, j)
                    tile = self.readViewTile(slice_nr, i, j)
584
                    size = (tile.shape[self.npWidthIdx], tile.shape[self.npHeightIdx])  # (w, h)
585 586 587 588 589 590 591 592 593
                    # translation matrix
                    m = np.float32([
                        [1, 0, src_tile_pos_x],
                        [0, 1, cur_src_tile_pos_y]
                    ])
                    cv2.warpAffine(current_src_img, m, size, tile, borderMode=cv2.BORDER_TRANSPARENT)
                    self.saveViewTile(tile, slice_nr, i, j)
                    cur_src_tile_pos_y -= view_tile_height
                src_tile_pos_x -= view_tile_width
594 595 596 597 598 599 600 601 602 603 604 605

            current_scaling_factor *= self.scalingFactor
            slice_nr += 1
            current_full_image_height *= self.scalingFactor
            current_full_image_width *= self.scalingFactor
            del current_src_img

        self.maxSliceNumber = slice_nr - 1
        self.updateSceneAfterViewTileUpdate(v_trans)

    def saveViewTile(self, img, slice_nr, i, j):
        """
606
        saves tile to file system and remembers the dimension as (width, height)
607 608 609 610 611 612 613
        :param img:
        :param slice_nr:
        :param i:
        :param j:
        :return:
        """
        tile_path = os.path.join(self.dataset.getTilePath(), f"tile_{slice_nr}_{i}_{j}.tif")
614
        cv2imwrite_fix(tile_path, img)
615 616 617 618 619 620 621 622

        if slice_nr not in self.tileWorkingSets:
            self.tileWorkingSets[slice_nr] = {}
            self.tileSets[slice_nr] = {}
        if i not in self.tileWorkingSets[slice_nr]:
            self.tileWorkingSets[slice_nr][i] = {}
            self.tileSets[slice_nr][i] = {}
        if j not in self.tileWorkingSets[slice_nr][i]:
623 624 625 626 627 628 629 630
            self.tileWorkingSets[slice_nr][i][j] = {
                "dimensions": (img.shape[self.npWidthIdx], img.shape[self.npHeightIdx]),
                "rendered": False
            }
            self.tileSets[slice_nr][i][j] = {
                "dimensions": (img.shape[self.npWidthIdx], img.shape[self.npHeightIdx]),
                "rendered": False
            }
631 632 633 634 635 636 637 638 639 640 641

    def readViewTile(self, slice_nr, i, j):
        """
        gets tile i, j of slice slice_nr
        if file doesn't exist returns a correctly sized empty image
        :param slice_nr:
        :param i:
        :param j:
        :return:
        """

642 643
        tile = None

644
        tile_path = os.path.join(self.dataset.getTilePath(), f"tile_{slice_nr}_{i}_{j}.tif")
645 646
        if not os.path.exists(tile_path):
            # fallback for datasets still using *.bmp
647 648
            tile_path = os.path.join(self.dataset.getTilePath(), f"tile_{slice_nr}_{i}_{j}.bmp")

649 650 651 652 653
        if os.path.exists(tile_path):
            try:
                tile = cv2imread_fix(tile_path)
            except OSError:
                None
654

655 656 657
        # as full image size might not be divisible by tile dimensions, we have to determine correct tile size
        # tile numbering is 0 based
        scaling = self.scalingFactor ** slice_nr
658
        max_y, max_x = self.tileDim
659 660 661 662 663 664 665
        fiw = scaling * self.fullImageWidth
        fih = scaling * self.fullImageHeight

        tile_w = int(math.ceil(max(min(max_x, fiw - i * max_x), 0)))
        tile_h = int(math.ceil(max(min(max_y, fih - j * max_y), 0)))

        # tile does exists but its shape is not correct
666
        '''
667 668 669 670 671
        if tile is not None and (tile_h, tile_w) != tile.shape[:2]:
            # this should not happen
            raise TileSizeError(
                f"tile should have dim ({tile_w}; {tile_h}), but has dim ({tile.shape[1]}; {tile.shape[0]})"
            )
672
        '''
673 674

        # tile does not even exist, create
675
        if tile is None:
676
            tile = np.zeros((tile_h, tile_w, 3), np.uint8)
677 678 679 680 681 682 683 684 685 686 687 688 689 690
        return tile

    def createFullImage(self):
        """
        creates full size image of highest resolution
        :return:
        """
        width = self.fullImageWidth
        height = self.fullImageHeight
        fullsize_img = Image.new('RGB', (width, height), 'black')

        for i in self.tileWorkingSets[0]:
            for j in self.tileWorkingSets[0][i]:
                timg = Image.fromarray(self.readViewTile(0, i, j))
691
                pos = (i * self.tileDim[self.npWidthIdx], j * self.tileDim[self.npHeightIdx])  # as (w, h)
692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707
                fullsize_img.paste(timg, pos)

        fullsize_img.save(self.dataset.getImageName(), 'tiff', save_all=True, compression='tiff_deflate')

    @staticmethod
    def createFromFullImage(dset):
        """
        creates tiles and pyramid parameters from the full image
        must load the full image which uses a large amount of ram
        :param DataSet dset:
        :return:
        """
        src_img = dset.getImageName()
        tile_base_path = dset.getTilePath()

        p = ScenePyramid.getDefaults()
708 709
        tile_x = p['tileDim'][1]  # self.npWidthIdx
        tile_y = p['tileDim'][0]  # self.npHeightIdx
710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762
        scaling = p['scalingFactor']

        warnings.simplefilter('ignore', Image.DecompressionBombError)
        warnings.simplefilter('ignore', Image.DecompressionBombWarning)
        # sqr(6GB / 3) ~  45.000 x 45000
        Image.MAX_IMAGE_PIXELS = 6 * 1024 ** 3
        img = Image.open(src_img)
        warnings.simplefilter('always', Image.DecompressionBombError)
        warnings.simplefilter('always', Image.DecompressionBombWarning)

        p['preScanModeComplete'] = True
        p['fullImageWidth'] = img.width
        p['fullImageHeight'] = img.height

        '''
        1. chop full image up in tiles
        2. scale full image down to new full image
        3. if max(width, height) of full image > breakof_pixel_count, go to 1.
        '''
        slice_nr = 0
        breakof_pixel_count = max(tile_y, tile_x)

        while max(img.width, img.height) > breakof_pixel_count:
            tiles_x = math.ceil(img.width / tile_x)
            tiles_y = math.ceil(img.height / tile_y)
            p['tileSets'][slice_nr] = {}
            for (i, x) in zip(range(tiles_x), range(0, img.width, tile_x)):
                p['tileSets'][slice_nr][i] = {}
                for (j, y) in zip(range(tiles_y), range(0, img.height, tile_y)):
                    tile = img.crop((
                        x,
                        y,
                        min(x + tile_x, img.width),
                        min(y + tile_y, img.height)
                    ))
                    tile_path = os.path.join(tile_base_path, f"tile_{slice_nr}_{i}_{j}.tif")
                    tile.save(tile_path, 'tiff', save_all=True, compression='tiff_deflate')
                    tile.close()
                    p['tileSets'][slice_nr][i][j] = {
                        "dimensions": (tile.width, tile.height),
                        "rendered": False
                    }

            img = img.resize((
                int(img.width * scaling),
                int(img.height * scaling)
            ), Image.LANCZOS)
            slice_nr += 1

        img.close()
        p['maxSliceNumber'] = slice_nr - 1
        dset.setPyramidParams(p)

763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780
    def getSubImage(self, clip):
        """
        :param (int, int, int, int) clip: (y1, y2, x1, x2)
        :return:
        :rtype: (np.array, QtGui.QPixmap)
        """
        y1, y2, x1, x2 = clip
        width = x2 - x1
        height = y2 - y1
        subimg = self.getImagePart(y1, y2, x1, x2)

        pix = QtGui.QPixmap()
        pix.convertFromImage(
            QtGui.QImage(subimg, width, height, 3 * width, QtGui.QImage.Format_RGB888)
        )

        return subimg, pix

781 782 783 784 785 786 787 788 789 790 791 792 793 794
    def getImagePart(self, p0y, p1y, p0x, p1x):
        """
        returns part of the full img
        :param int ymin:
        :param int ymax:
        :param int xmin:
        :param int xmax:
        :return:
        """
        '''
        we want to extract pixels of highest resolution from p0(xmin, ymin) to p1(xmax, ymax)
        with
          k(i,j) = tile at pos (i, j)
          h, w = base height, base width of tile
795
        we need to extract subimage from tiles k(i, j) with i, j in:
796 797 798 799 800 801 802 803 804 805 806 807 808
          imin = floor(xmin/w) <= i <= floor(xmax/w) = imax
          jmin = floor(ymin/h) <= j <= floor(ymax/h) = jmax
        transform p0, p1 (relative to origin of tile k(imin, jmin)):
          p0' = (
            xmin % w,
            ymin % h
          )
          p1' = (
            xmax % w + (imax - imin) * w,
            ymax % h + (jmax - jmin) * h
          )
        extract pixels
        '''
809 810
        w = self.tileDim[self.npWidthIdx]
        h = self.tileDim[self.npHeightIdx]
811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840
        imin = math.floor(p0x / w)
        imax = math.floor(p1x / w)
        jmin = math.floor(p0y / h)
        jmax = math.floor(p1y / h)

        ci = imax - imin + 1
        cj = jmax - jmin + 1

        # p0 relative to origin of tile k(imin, jmin)
        p0x_ = p0x % w
        p0y_ = p0y % h

        m_trans = np.float32([[1, 0, 0], [0, 1, 0]])
        img = np.zeros((p1y - p0y, p1x - p0x, 3), np.uint8)
        size = (p1x - p0x, p1y - p0y)
        for i in range(ci):
            for j in range(cj):
                tile = self.readViewTile(0, imin + i, jmin + j)
                # xmin of current tile in tile based sub image (relative to tile k(imin, jmin))
                xmin_t = i * w
                # ymin
                ymin_t = j * h

                # position in subimage to copy to
                m_trans[0][2] = xmin_t - p0x_
                m_trans[1][2] = ymin_t - p0y_

                cv2.warpAffine(tile, m_trans, size, img, flags=cv2.INTER_CUBIC, borderMode=cv2.BORDER_TRANSPARENT)

        # comment in(?) to check result in tile path
841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865
        # self.imageOut(img, f"_image_part.tif")

        return img

    def getFullImage(self, scale=1.):
        """
        returns full image scaled to the given value
        for this we use numpy to concatenate the tile images
        :param: float scale
        :return: full size image
        :rtype: np.array
        """
        assert 0. <= scale <= 1.

        first_col = True
        img = None
        col = None
        # for big images use np.concatenate
        # for each tile col
        for x in range(len(self.tileWorkingSets[0])):
            first_tile = True
            # for each tile in col
            for y in range(len(self.tileWorkingSets[0][x])):
                tile = self.readViewTile(0, x, y)
                if 1. != scale:
866 867
                    w = math.floor(scale * tile.shape[self.npWidthIdx])
                    h = math.floor(scale * tile.shape[self.npHeightIdx])
868 869 870 871 872 873 874 875 876 877 878 879 880 881 882
                    tile = np.array(Image.fromarray(tile).resize((w, h), resample=Image.BICUBIC))

                if not first_tile:
                    col = np.concatenate((col, tile), axis=0)
                else:
                    col = tile
                    first_tile = False
                # self.imageOut(col, f"_col_{x}_{y}.tif")

            # self.imageOut(col, f"_col_{x}.tif")
            if not first_col:
                img = np.concatenate((img, col), axis=1)
            else:
                img = col
                first_col = False
883

884
        # self.imageOut(img, f"_fullimage.tif")
885 886 887 888
        return img

    def imageOut(self, img, name):
        path = os.path.join(self.dataset.getTilePath(), name)
889
        cv2imwrite_fix(path, img)
890 891 892 893 894 895 896 897 898 899 900

    def setTileOpacity(self, opacity):
        """
        sets opacity of all currently shown tiles
        :param float opacity:
        :return:
        """
        assert 0 <= opacity <= 1
        self.opacity = opacity
        [tile.setOpacity(opacity) for tile in self.currentTiles]

901 902 903 904 905
    def fixMissingTiles(self):
        """
        :return:
        """
        scaling = 1
906 907 908
        tile_height, tile_width = self.tileDim
        # for every slice
        for pslice in range(0, self.maxSliceNumber + 1):
909 910 911 912 913 914 915
            img_width = math.ceil(scaling * self.fullImageWidth)
            img_height = math.ceil(scaling * self.fullImageHeight)
            # tiles in x direction
            col_tile_count = math.ceil(img_width / tile_width)
            # tiles in y direction
            row_tile_count = math.ceil(img_height / tile_height)

916
            # col in x direction
917 918
            for i in range(0, col_tile_count):
                w_tile = (tile_width if i + 1 < col_tile_count else img_width % tile_width)
919 920 921 922 923
                if i not in self.tileSets[pslice]:
                    self.tileSets[pslice][i] = {}
                    self.tileWorkingSets[pslice][i] = {}
                col = self.tileSets[pslice][i]
                # row in y direction
924 925 926
                for j in range(0, row_tile_count):
                    h_tile = (tile_height if j + 1 < row_tile_count else img_height % tile_height)
                    if j not in col or col[j]["dimensions"] != (w_tile, h_tile):
927 928
                        tile = self.readViewTile(pslice, i, j)
                        self.saveViewTile(tile, pslice, i, j)
929 930 931

            scaling *= self.scalingFactor

932 933 934 935 936 937 938 939
    def destruct(self):
        """
        removes all graphics items from scene
        and saves itself to the dataset
        :return:
        """
        self.toDataset()
        self.resetScene()