class MultiPageTIFFViewerQt(QWidget): """ Multi-page TIFF image stack viewer using tiffcapture (https://github.com/cdw/TiffCapture). Uses ImageViewerQt (https://github.com/marcel-goldschen-ohm/ImageViewerQt) to display the stack frames and handle mouse interaction (pan, zoom, click signals). Uses qimage2ndarray (https://github.com/hmeine/qimage2ndarray) to convert the format of stack frames from NumPy ndarray to QImage as requried by ImageViewerQt. Frame traversal via a slider and arrow buttons. """ frameChanged = pyqtSignal([], [int]) def __init__(self): QWidget.__init__(self) # Handle to the image stack tiffcapture object. self._tiffCaptureHandle = None self.currentFrameIndex = None # Image frame viewer. self.viewer = ImageViewerQt() # Slider and arrow buttons for frame traversal. self.frameSlider = QSlider(Qt.Horizontal) self.prevFrameButton = QPushButton("<") self.nextFrameButton = QPushButton(">") self.currentFrameLabel = QLabel() self.prevFrameButton.clicked.connect(self.prevFrame) self.nextFrameButton.clicked.connect(self.nextFrame) self.frameSlider.valueChanged.connect(self.showFrame) # Layout. grid = QGridLayout(self) grid.addWidget(self.currentFrameLabel, 0, 0, 1, 3) grid.addWidget(self.viewer, 1, 0, 1, 3) grid.addWidget(self.prevFrameButton, 2, 0) grid.addWidget(self.frameSlider, 2, 1) grid.addWidget(self.nextFrameButton, 2, 2) grid.setContentsMargins(2, 2, 2, 2) grid.setSpacing(0) def hasImageStack(self): """ Return whether or not an image stack is currently loaded. """ return self._tiffCaptureHandle is not None def clearImageStack(self): """ Clear the current image stack if it exists. """ if self._tiffCaptureHandle is not None: self.viewer.clearImage() self._tiffCaptureHandle = None def setImageStack(self, tiffCaptureHandle): """ Set the scene's current TIFF image stack to the input TiffCapture object. Raises a RuntimeError if the input tiffCaptureHandle has type other than TiffCapture. :type tiffCaptureHandle: TiffCapture """ if type(tiffCaptureHandle) is not tiffcapture.TiffCapture: raise RuntimeError("MultiPageTIFFViewerQt.setImageStack: Argument must be a TiffCapture object.") self._tiffCaptureHandle = tiffCaptureHandle self.showFrame(0) def loadImageStackFromFile(self, fileName=''): """ Load an image stack from file. Without any arguments, loadImageStackFromFile() will popup a file dialog to choose the image file. With a fileName argument, loadImageStackFromFile(fileName) will attempt to load the specified file directly. """ if len(fileName) == 0: if QT_VERSION_STR[0] == '4': fileName = QFileDialog.getOpenFileName(self, "Open TIFF stack file.") elif QT_VERSION_STR[0] == '5': fileName, dummy = QFileDialog.getOpenFileName(self, "Open TIFF stack file.") fileName = str(fileName) if len(fileName) and os.path.isfile(fileName): self._tiffCaptureHandle = tiffcapture.opentiff(fileName) self.showFrame(0) def numFrames(self): """ Return the number of image frames in the stack. """ if self._tiffCaptureHandle is not None: # !!! tiffcapture has length=0 for a single page TIFF. # If our handle is valid, we'll assume we have at least one image. return max([1, self._tiffCaptureHandle.length]) return 0 def getAllFrames(self): """ Return the entire image stack as a NumPy ndarray. !!! This currently ONLY works for grayscale image stacks that can be represented as 3D arrays. !!! For large image stacks this can be time and memory hungry. """ if self._tiffCaptureHandle is None: return None imageWidth = self._tiffCaptureHandle.shape[0] imageHeight = self._tiffCaptureHandle.shape[1] numFrames = self.numFrames() entireStackArray = np.empty((imageWidth, imageHeight, numFrames)) progress = QProgressDialog(self) progress.setLabelText("Loading TIFF image stack...") progress.setRange(0, numFrames) progress.setValue(0) progress.setWindowModality(Qt.WindowModal) progress.show() for i, frame in enumerate(self._tiffCaptureHandle): entireStackArray[:,:,i] = frame progress.setValue(i) if progress.wasCanceled(): return None progress.close() return entireStackArray def getFrame(self, i=None): """ Return the i^th image frame as a NumPy ndarray. If i is None, return the current image frame. """ if self._tiffCaptureHandle is None: return None if i is None: i = self.currentFrameIndex if (i is None) or (i < 0) or (i >= self.numFrames()): return None return self._tiffCaptureHandle.find_and_read(i) def showFrame(self, i=None): """ Display the i^th frame in the viewer. Also update the frame slider position and current frame text. """ frame = self.getFrame(i) if frame is None: return # Convert frame ndarray to a QImage. qimage = qimage2ndarray.array2qimage(frame, normalize=True) self.viewer.setImage(qimage) self.currentFrameIndex = i # Update frame slider position (hide frame slider if we only have one image frame). numFrames = self.numFrames() if numFrames > 1: self.frameSlider.setRange(1, numFrames) self.frameSlider.setValue(i) self.frameSlider.show() self.prevFrameButton.show() self.nextFrameButton.show() self.currentFrameLabel.setText(str(i+1) + "/" + str(numFrames)) self.currentFrameLabel.show() else: self.frameSlider.hide() self.prevFrameButton.hide() self.nextFrameButton.hide() self.currentFrameLabel.hide() self.frameChanged.emit() self.frameChanged[int].emit(i) def prevFrame(self): """ Show previous frame in stack. """ self.showFrame(self.currentFrameIndex - 1) def nextFrame(self): """ Show next frame in stack. """ self.showFrame(self.currentFrameIndex + 1)
class MultiPageTIFFViewerQt(QWidget): """ Multi-page TIFF image stack viewer using tiffcapture (https://github.com/cdw/TiffCapture). Uses ImageViewerQt (https://github.com/marcel-goldschen-ohm/ImageViewerQt) to display the stack frames and handle mouse interaction (pan, zoom, click signals). Uses qimage2ndarray (https://github.com/hmeine/qimage2ndarray) to convert the format of stack frames from NumPy ndarray to QImage as requried by ImageViewerQt. Frame traversal via a slider and arrow buttons. """ frameChanged = pyqtSignal([], [int]) def __init__(self): QWidget.__init__(self) # Handle to the image stack tiffcapture object. self._tiffCaptureHandle = None self.currentFrameIndex = None # Image frame viewer. self.viewer = ImageViewerQt() # Slider and arrow buttons for frame traversal. self.frameSlider = QSlider(Qt.Horizontal) self.prevFrameButton = QPushButton("<") self.nextFrameButton = QPushButton(">") self.currentFrameLabel = QLabel() self.prevFrameButton.clicked.connect(self.prevFrame) self.nextFrameButton.clicked.connect(self.nextFrame) self.frameSlider.valueChanged.connect(self.showFrame) # Layout. grid = QGridLayout(self) grid.addWidget(self.currentFrameLabel, 0, 0, 1, 3) grid.addWidget(self.viewer, 1, 0, 1, 3) grid.addWidget(self.prevFrameButton, 2, 0) grid.addWidget(self.frameSlider, 2, 1) grid.addWidget(self.nextFrameButton, 2, 2) grid.setContentsMargins(2, 2, 2, 2) grid.setSpacing(0) def hasImageStack(self): """ Return whether or not an image stack is currently loaded. """ return self._tiffCaptureHandle is not None def clearImageStack(self): """ Clear the current image stack if it exists. """ if self._tiffCaptureHandle is not None: self.viewer.clearImage() self._tiffCaptureHandle = None def setImageStack(self, tiffCaptureHandle): """ Set the scene's current TIFF image stack to the input TiffCapture object. Raises a RuntimeError if the input tiffCaptureHandle has type other than TiffCapture. :type tiffCaptureHandle: TiffCapture """ if type(tiffCaptureHandle) is not tiffcapture.TiffCapture: raise RuntimeError( "MultiPageTIFFViewerQt.setImageStack: Argument must be a TiffCapture object." ) self._tiffCaptureHandle = tiffCaptureHandle self.showFrame(0) def loadImageStackFromFile(self, fileName=''): """ Load an image stack from file. Without any arguments, loadImageStackFromFile() will popup a file dialog to choose the image file. With a fileName argument, loadImageStackFromFile(fileName) will attempt to load the specified file directly. """ if len(fileName) == 0: if QT_VERSION_STR[0] == '4': fileName = QFileDialog.getOpenFileName( self, "Open TIFF stack file.") elif QT_VERSION_STR[0] == '5': fileName, dummy = QFileDialog.getOpenFileName( self, "Open TIFF stack file.") fileName = str(fileName) if len(fileName) and os.path.isfile(fileName): self._tiffCaptureHandle = tiffcapture.opentiff(fileName) self.showFrame(0) def numFrames(self): """ Return the number of image frames in the stack. """ if self._tiffCaptureHandle is not None: # !!! tiffcapture has length=0 for a single page TIFF. # If our handle is valid, we'll assume we have at least one image. return max([1, self._tiffCaptureHandle.length]) return 0 def getAllFrames(self): """ Return the entire image stack as a NumPy ndarray. !!! This currently ONLY works for grayscale image stacks that can be represented as 3D arrays. !!! For large image stacks this can be time and memory hungry. """ if self._tiffCaptureHandle is None: return None imageWidth = self._tiffCaptureHandle.shape[0] imageHeight = self._tiffCaptureHandle.shape[1] numFrames = self.numFrames() entireStackArray = np.empty((imageWidth, imageHeight, numFrames)) progress = QProgressDialog(self) progress.setLabelText("Loading TIFF image stack...") progress.setRange(0, numFrames) progress.setValue(0) progress.setWindowModality(Qt.WindowModal) progress.show() for i, frame in enumerate(self._tiffCaptureHandle): entireStackArray[:, :, i] = frame progress.setValue(i) if progress.wasCanceled(): return None progress.close() return entireStackArray def getFrame(self, i=None): """ Return the i^th image frame as a NumPy ndarray. If i is None, return the current image frame. """ if self._tiffCaptureHandle is None: return None if i is None: i = self.currentFrameIndex if (i is None) or (i < 0) or (i >= self.numFrames()): return None return self._tiffCaptureHandle.find_and_read(i) def showFrame(self, i=None): """ Display the i^th frame in the viewer. Also update the frame slider position and current frame text. """ frame = self.getFrame(i) if frame is None: return # Convert frame ndarray to a QImage. qimage = qimage2ndarray.array2qimage(frame, normalize=True) self.viewer.setImage(qimage) self.currentFrameIndex = i # Update frame slider position (hide frame slider if we only have one image frame). numFrames = self.numFrames() if numFrames > 1: self.frameSlider.setRange(1, numFrames) self.frameSlider.setValue(i) self.frameSlider.show() self.prevFrameButton.show() self.nextFrameButton.show() self.currentFrameLabel.setText(str(i + 1) + "/" + str(numFrames)) self.currentFrameLabel.show() else: self.frameSlider.hide() self.prevFrameButton.hide() self.nextFrameButton.hide() self.currentFrameLabel.hide() self.frameChanged.emit() self.frameChanged[int].emit(i) def prevFrame(self): """ Show previous frame in stack. """ self.showFrame(self.currentFrameIndex - 1) def nextFrame(self): """ Show next frame in stack. """ self.showFrame(self.currentFrameIndex + 1)
class Seg_label_tool(QtGui.QMainWindow): def __init__(self, args): super(Seg_label_tool, self).__init__() self.InitUI() self.image_view.Moustmove_leftMouseButtonClicked.connect( self.mousemove_slot) self.curimg = None self.showimg = None self.curlabel = None def InitUI(self): self.layout_design() self.menu_tootbar_design() self.sBar = self.statusBar() def layout_design(self): self.setGeometry(0, 0, WINDOW_SIZE[0], WINDOW_SIZE[1]) self.move_to_center() self.setWindowTitle('seg_label_tool') self.left_QWidget = QtGui.QWidget(self) self.left_QWidget.setGeometry(10, 10, L_WINDOW[0], L_WINDOW[1]) vbox = QtGui.QVBoxLayout() hbox1 = QtGui.QHBoxLayout() labname_lab = QtGui.QLabel('label', self.left_QWidget) self.labname_edit = QtGui.QLineEdit('defect', self.left_QWidget) hbox1.addWidget(labname_lab) hbox1.addWidget(self.labname_edit) vbox.addLayout(hbox1) hbox2 = QtGui.QHBoxLayout() radius_lab = QtGui.QLabel('radius', self.left_QWidget) self.radius_edit = QtGui.QLineEdit('50', self.left_QWidget) hbox2.addWidget(radius_lab) hbox2.addWidget(self.radius_edit) vbox.addLayout(hbox2) labbtn = QtGui.QPushButton('lab', self.left_QWidget) labbtn.clicked.connect(self.labaction) labbtn.setShortcut('Ctrl+N') vbox.addWidget(labbtn) # labsavebtn = QtGui.QPushButton('lab_save',self.left_QWidget) # labsavebtn.clicked.connect(self.labSaveAction) # labsavebtn.setShortcut('s') # vbox.addWidget(labsavebtn) labcancelbtn = QtGui.QPushButton('lab_erase', self.left_QWidget) labcancelbtn.clicked.connect(self.labCancelAction) labcancelbtn.setShortcut('c') vbox.addWidget(labcancelbtn) self.left_QWidget.setLayout(vbox) self.image_view = ImageViewerQt(self) self.image_view.setGeometry(R_WINDOW) def menu_tootbar_design(self): exitAction = QtGui.QAction(QtGui.QIcon('./icon/quit.png'), '&Exit', self) exitAction.setShortcut('Ctrl+Q') exitAction.setStatusTip('Exit application') exitAction.triggered.connect(QtGui.QApplication.quit) saveAction = QtGui.QAction(QtGui.QIcon('./icon/save.png'), '&save', self) saveAction.setShortcut('Ctrl+S') saveAction.setStatusTip('save inf') saveAction.triggered.connect(self.savefile) opendirAction = QtGui.QAction(QtGui.QIcon('./icon/opendir.png'), '&opendir', self) opendirAction.setShortcut('Ctrl+O') opendirAction.setStatusTip('opendir inf') opendirAction.triggered.connect(self.opendir) nextAction = QtGui.QAction(QtGui.QIcon('./icon/next.png'), '&nextimg', self) nextAction.setShortcut('n') nextAction.setStatusTip('nextimg inf') nextAction.triggered.connect(self.nextimg) prevAction = QtGui.QAction(QtGui.QIcon('./icon/prev.png'), '&previmg', self) prevAction.setShortcut('p') prevAction.setStatusTip('prevtimg inf') prevAction.triggered.connect(self.previmg) menubar = self.menuBar() fileMenu = menubar.addMenu('&File') viewMenu = menubar.addMenu('&View') fileMenu.addAction(exitAction) toolbar = self.addToolBar('opendir') toolbar.addAction(opendirAction) toolbar = self.addToolBar('save') toolbar.addAction(saveAction) toolbar = self.addToolBar('Next') toolbar.addAction(nextAction) toolbar = self.addToolBar('prev') toolbar.addAction(prevAction) toolbar = self.addToolBar('Exit') toolbar.addAction(exitAction) def savefile(self): if self.showimg is not None and self.curlabel is not None: cv2.imwrite(self.filelist[self.curimg_index][0], self.showimg[:, :, (2, 1, 0)]) cv2.imwrite(self.filelist[self.curimg_index][1], self.curlabel[:, :, (2, 1, 0)]) def opendir(self): dirname = None dirname = QtGui.QFileDialog.getExistingDirectory( self, 'open dir', './') dirname = str(dirname) if dirname: # QtGui.QMessageBox.information(self,'inf',dirname) self.filelist = [] if os.path.isdir(dirname): self.result_img_dir = './result/img' self.result_label_dir = './result/label' if os.path.exists(self.result_img_dir): shutil.rmtree(self.result_img_dir) if os.path.exists(self.result_label_dir): shutil.rmtree(self.result_label_dir) os.makedirs(self.result_label_dir) shutil.copytree(dirname, self.result_img_dir) for file in os.listdir(dirname): if os.path.splitext(file)[1] == IMG_EXT: self.filelist.append( (self.result_img_dir + '/' + file, self.result_label_dir + '/' + file)) print len(self.filelist) self.filelist.sort() self.curimg_index = -1 self.nextimg() else: print 'please select a dir' def show_img_fun(self, img, init=True): frame = QtGui.QImage(img.data, img.shape[1], img.shape[0], img.shape[1] * 3, QtGui.QImage.Format_RGB888) self.image_view.setImage(frame, init) def nextimg(self): self.savefile() self.curimg_index += 1 if self.curimg_index == len(self.filelist): self.curimg_index -= 1 QtGui.QMessageBox.information(self, 'inf', 'this is no more image') else: self.curimg = cv2.imread(self.filelist[self.curimg_index][0]) self.curimg = cv2.cvtColor(self.curimg, cv2.COLOR_BGR2RGB) self.curlabel = np.zeros_like(self.curimg) self.showimg = np.copy(self.curimg) self.show_img_fun(self.curimg, True) self.isdrawing = True self.islabing = True self.sBar.showMessage( self.filelist[self.curimg_index][0].split('/')[-1]) def previmg(self): self.savefile() self.curimg_index -= 1 if self.curimg_index < 0: self.curimg_index += 1 QtGui.QMessageBox.information(self, 'inf', 'this is first image') else: self.curimg = cv2.imread(self.filelist[self.curimg_index][0]) self.curimg = cv2.cvtColor(self.curimg, cv2.COLOR_BGR2RGB) self.curlabel = np.zeros_like(self.curimg) self.showimg = np.copy(self.curimg) self.show_img_fun(self.showimg, True) self.isdrawing = True self.islabing = True def keyPressEvent(self, e): if e.key() == QtCore.Qt.Key_Control: self.image_view.canPan = True self.isdrawing = False QtGui.QMainWindow.keyPressEvent(self, e) def keyReleaseEvent(self, QKeyEvent): if QKeyEvent.key() == QtCore.Qt.Key_Control: self.image_view.canPan = False self.isdrawing = True QtGui.QMainWindow.keyReleaseEvent(self, QKeyEvent) def labaction(self): self.islabing = True # self.setCursor(QtCore.Qt.CrossCursor) def labCancelAction(self): self.islabing = False # print 'helo' # self.setCursor(QtCore.Qt.UpArrowCursor) def move_to_center(self): qr = self.frameGeometry() cp = QtGui.QDesktopWidget().availableGeometry().center() qr.moveCenter(cp) self.move(qr.topLeft()) def _cal_showimg(self, curimg, label): tmp = np.copy(curimg) tmp[np.where(label[:, :, 0] == 255)] = (255, 0, 0) return tmp def mousemove_slot(self, x, y): if self.isdrawing: rad = int(self.radius_edit.text()) if rad < 0: rad = 10 print 'radius is must positive ,now rad:%d' % rad if self.islabing: cv2.circle(self.curlabel, (x, y), radius=rad, color=(255, 255, 255), thickness=cv2.cv.CV_FILLED) self.showimg = self._cal_showimg(self.curimg, self.curlabel) self.show_img_fun(self.showimg, False) self.sBar.showMessage('labing') else: cv2.circle(self.curlabel, (x, y), radius=rad, color=(0, 0, 0), thickness=cv2.cv.CV_FILLED) self.showimg = self._cal_showimg(self.curimg, self.curlabel) self.show_img_fun(self.showimg, False) self.sBar.showMessage('lab_erase')