opticalbackground.py 9.66 KB
Newer Older
Josef Brandt's avatar
 
Josef Brandt committed
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
# -*- 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/>.
"""

from PyQt5 import QtCore, QtWidgets, QtGui
import cv2
import numpy as np
import os

from helperfunctions import cv2imread_fix

class BackGroundManager(QtWidgets.QWidget):
    managerClosed = QtCore.pyqtSignal()
    readBackground = QtCore.pyqtSignal(int)
    
    def __init__(self, parentOSwidget):
        super(BackGroundManager, self).__init__()
        self.setFixedSize(1500, 900)
        self.setWindowTitle('Optical Background Manager')
        self.parentOSwidget = parentOSwidget
        self.parentOSwidget.backGroundSavedToPath.connect(self.updateChildImage)
        self.ramanctrl = self.parentOSwidget.ramanctrl
        
        layout = QtWidgets.QHBoxLayout()
        self.setLayout(layout)
        
        self.imagesGroup = QtWidgets.QGroupBox('Current Background Images')
        self.imagesLayout = QtWidgets.QGridLayout()        
        
        self.imgContainers = []
        self.avgImg = None
        self.presetIndividualImages()
        
        self.previewImage = QtWidgets.QGraphicsView()
        self.setupGraphicsView(self.previewImage, scaleFactor=0.8)
        
        previewGroup = QtWidgets.QGroupBox()
        previewLayout = QtWidgets.QVBoxLayout()
        self.blurspinbox = QtWidgets.QSpinBox(self)
        self.blurspinbox.setMinimum(3)
        self.blurspinbox.setMaximum(99)
        self.blurspinbox.setSingleStep(2)
        self.blurspinbox.setValue(5)
        self.blurspinbox.valueChanged.connect(self.calculateAverageImage)
        self.blurspinbox.setMaximumWidth(150)
        
        self.previewCurrentViewBtn = QtWidgets.QPushButton('Acquire 3x3 area and preview subtracted result')
        self.previewCurrentViewBtn.clicked.connect(self.previewStitchedArea)
        self.previewArea = QtWidgets.QGraphicsView()
        self.setupGraphicsView(self.previewArea, scaleFactor=0.5)
        
        previewLayout.addWidget(QtWidgets.QLabel('Radius for blur'))
        previewLayout.addWidget(self.blurspinbox)
        previewLayout.addWidget(QtWidgets.QLabel('Preview of averaged and smoothed image'))
        previewLayout.addWidget(self.previewImage)
        previewLayout.addWidget(self.previewCurrentViewBtn)
        previewLayout.addWidget(self.previewArea)
        
        previewGroup.setLayout(previewLayout)
        
        layout.addWidget(self.imagesGroup)
        layout.addWidget(previewGroup)
        
    def presetIndividualImages(self, nrows=3, ncols=2):
        index = 0
        for row in range(nrows):
            for col in range(ncols):
                self.imgContainers.append(SingleImageContainer(self, index))
                self.imagesLayout.addWidget(self.imgContainers[-1], row, col)
                index += 1
                
        self.imagesGroup.setLayout(self.imagesLayout)
    
    def previewStitchedArea(self):
        if self.avgImg is None:
            QtWidgets.QMessageBox.about(self, 'Warning', 'No Background Image is aquired')
            return
        else:
            from opticalscan import loadAndPasteImage
            self.dataset = self.parentOSwidget.dataset
            
            #acquire images in 3x3 area to preview quality of background subtraction
            x, y, z = self.ramanctrl.getPosition()
            micMode = self.parentOSwidget.view.microscopeMode
            width, height, angle = self.ramanctrl.getImageDimensions(micMode)
            startPoint = [x-width, y-height]
            endPoint = [x+width, y+height]
            points = np.concatenate(([startPoint], [endPoint]), axis=0)
            p0 = [points[:,0].min(), points[:,1].max()]
            p1 = [points[:,0].max(), points[:,1].min()]
            
            reply = QtWidgets.QMessageBox.question(self, 'Message',f"The stage will move {round(3*width)} in x and {round(3*height)} in y.\nContinue?", 
                                                   QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No, QtWidgets.QMessageBox.No)
            if reply == QtWidgets.QMessageBox.Yes:
                fullimg = None
                zimg = None
         
                for row in range(3):
                    for col in range(3):
                        curPoint = [startPoint[0] + row*width, startPoint[1] + col*height]
                        self.ramanctrl.moveToAbsolutePosition(curPoint[0], curPoint[1])
                        self.ramanctrl.saveImage(self.dataset.getTmpImageName())
                        
                        fullimg, zimg = loadAndPasteImage([self.dataset.getTmpImageName()], fullimg, zimg, width, height, angle, p0, p1, curPoint, background=self.avgImg)
                        self.updateGraphicsView(self.previewArea, fullimg, convertColors=True)


    def setupGraphicsView(self, graphView, scaleFactor=1.):
        graphView.item = QtWidgets.QGraphicsPixmapItem()
        scene = QtWidgets.QGraphicsScene(graphView)
        scene.addItem(graphView.item)
        graphView.setScene(scene)
        graphView.scale(scaleFactor, scaleFactor)
    
    def updateGraphicsView(self, graphView, img, convertColors=False):
        if img is not None:
            prevImg = img
        else:
            prevImg = np.zeros((300, 300))
        
        if convertColors:
            prevImg = cv2.cvtColor(img, cv2.COLOR_RGB2BGR)
            
        height, width = prevImg.shape[:2]
        bytesPerLine = 3 * width
        pix = QtGui.QPixmap()
        pix.convertFromImage(QtGui.QImage(prevImg, width, height, bytesPerLine, QtGui.QImage.Format_RGB888))
        graphView.item.setPixmap(pix)
    
    @QtCore.pyqtSlot(int, str) 
    def updateChildImage(self, index, path):
        self.imgContainers[index].updateImage(path)
        self.calculateAverageImage()
    
    def calculateAverageImage(self):
        curImgs = [i.getImage() for i in self.imgContainers if i.getImage() is not None]
                
        if len(curImgs) > 0:
            curImgs = np.array(curImgs)
            self.avgImg = np.sum(curImgs, axis=0)/len(curImgs)
            radius = self.blurspinbox.value()
            if radius %2 == 0:
                radius += 1
            if radius < 0:
                radius = 1    
            self.avgImg = cv2.GaussianBlur(self.avgImg, (radius, radius), 0)
            self.avgImg = np.uint8(self.avgImg)
            self.parentOSwidget.writeBackGroundImage(self.avgImg)
        else:
            self.avgImg = None
            self.parentOSwidget.deleteBackGroundImage()
            
        self.updateGraphicsView(self.previewImage, self.avgImg)
        
    def closeEvent(self, event):
        self.managerClosed.emit()
        event.accept()
    
    
class SingleImageContainer(QtWidgets.QGroupBox):
    def __init__(self, parent, index):
        super(SingleImageContainer, self).__init__()
        self.index = index
        self.parent = parent
        
        layout = QtWidgets.QVBoxLayout()
        layout.addWidget(QtWidgets.QLabel(f'Background {index+1}'))
        
        readBtn = QtWidgets.QPushButton('ReadImage')
        readBtn.clicked.connect(self.readImage)
        
        self.image = ImagePixmap()
        
        delBtn = QtWidgets.QPushButton('Delete Image')
        delBtn.clicked.connect(self.clearImage)
        
        layout.addWidget(readBtn)
        layout.addWidget(self.image)
        layout.addWidget(delBtn)
        
        self.setLayout(layout)
    
    def readImage(self):
        self.parent.readBackground.emit(self.index)
    
    def updateImage(self, path):
        self.image.updateImage(path)
    
    def clearImage(self):
        self.image.clearImage()
        self.parent.calculateAverageImage()
        
    def getImage(self):
        return self.image.imgdata


class ImagePixmap(QtWidgets.QGraphicsView):
    def __init__(self):
        super(ImagePixmap, self).__init__()
        self.item = QtWidgets.QGraphicsPixmapItem()
        self.item.setPos(0, 0)
        self.item.setAcceptedMouseButtons(QtCore.Qt.NoButton)
        self.imgdata = None
        
        scene = QtWidgets.QGraphicsScene(self)
        scene.addItem(self.item)
        self.setScene(scene)
        
        self.scale(0.4, 0.4)
        self.updateImage()
        
    def updateImage(self, img_path=None):
        if img_path is None:
            self.loadImageIntoPixmap(self.createBlancImage())
            
        elif os.path.exists(img_path):
            self.imgdata = cv2.cvtColor(cv2imread_fix(img_path), cv2.COLOR_BGR2RGB)
            self.loadImageIntoPixmap(self.imgdata)

    def createBlancImage(self):
        blancImg = np.zeros((300, 500, 3))
        cv2.putText(blancImg, 'None selected', (150, 150), cv2.FONT_HERSHEY_COMPLEX, 1, (255, 255, 255), 2)
        return blancImg
    
    def loadImageIntoPixmap(self, img):
        height, width = img.shape[:2]
        bytesPerLine = 3 * width
        pix = QtGui.QPixmap()
        pix.convertFromImage(QtGui.QImage(img, width, height, bytesPerLine, QtGui.QImage.Format_RGB888))
        self.item.setPixmap(pix)
    
    def clearImage(self):
        self.imgdata = None
        self.updateImage()