def initOutput(self): """" initOuput: init the layout of the output result by appending the OutputLayout layout 2 radio buttons and 2 ImageViewer instances with indexes 0, 1 """ outputLayout = QVBoxLayout() outputBox = QGroupBox() radioLayout = QHBoxLayout() radioGroup = QGroupBox() self.radio1 = QRadioButton("Image 1") self.radio1.setChecked(True) # At the beginning, check the first image self.radio1.toggled.connect(self.toggleOutput) self.radio2 = QRadioButton("Image 2") self.radio2.setChecked(False) self.radio2.toggled.connect(self.toggleOutput) self.radio1.setEnabled(False) self.radio2.setEnabled(False) radioLayout.addWidget(self.radio1) radioLayout.addWidget(self.radio2) radioGroup.setLayout(radioLayout) outputImagesLayout = QHBoxLayout() self.outputImages = [ImageViewer((400, 500)), ImageViewer((400, 500))] data = defaultOutput() self.outputImages[0].image.setImage(data) self.outputImages[1].image.setImage(data) outputImagesLayout.addWidget(self.outputImages[0]) outputImagesLayout.addWidget(self.outputImages[1]) outputImagesBox = QGroupBox() outputImagesBox.setLayout(outputImagesLayout) self.outputLayout.addWidget(radioGroup) self.outputLayout.addWidget(outputImagesBox)
def setImage(self, imagePath=None, image=None): # set image ImageViewer.setImage(self, imagePath, image) self.paintImage = self.Image # init mask property self.labelMask = np.zeros([self.Image.height(), self.Image.width()], dtype=int) self.labelColors = [] # update update widget self.update()
def initUi(self): ''' label mask property ''' ImageViewer.initUi(self) self.labelMask = np.array([], dtype=int) self.labelColors = [] self.remove_small_objects = 64 self.remove_small_holes = 64 self.paintImage = None self.update()
def initUi(self): ImageViewer.initUi(self) # self.polygonDrawing = False self.polygonList = [] # {geo:'',results:'', type:'', selected:False} # self.tmpPolygon = QPolygonF() self.tmpDrawPoints = [] self.drawModel = 'polygon' # 0. scaleLine, 1. cropPolygon, 2. polygon self.drawing = False # add polygon button polygonBtn = QPushButton(QIcon('./images/icons/polygon.png'), '') polygonBtn.setToolTip('Add Polygon') polygonBtn.clicked.connect(lambda: self.startDraw(mode='polygon')) self.toolBox.addWidget(polygonBtn) self.update()
def setPixmap(self, pixmap): self._pixmap = pixmap from ImageViewer import ImageViewer self._image_viewer = ImageViewer(pixmap) if pixmap.height() > self.height() or pixmap.width() > self.width(): self._image_viewer.fitToWindow() self.setCentralWidget(self._image_viewer)
def paintEvent(self, event): ImageViewer.paintEvent(self, event) if self.drawing: self.pt.begin(self) self.pt.setPen(QColor('red')) self.pt.setBrush(QColor(255, 0, 0, 10)) pp = QPolygonF() for p in self.tmpDrawPoints: pp.append(self._pix2real(p)) pp.append(self.mousePos) self.pt.drawPolygon(pp) self.pt.end() if self.drawing: self.setCursor(Qt.CrossCursor)
def mousePressEvent(self, event: QMouseEvent) -> None: ImageViewer.mousePressEvent(self, event) if event.button() == Qt.LeftButton: if self.drawing: # check draw type and points length. self.__draw(event.pos()) else: # check if something is selected for idx, polygon in enumerate(self.polygonList): p = polygon['geo'] if p.containsPoint(self._real2pix(event.pos()), Qt.OddEvenFill): self.polygonList[idx][ 'selected'] = ~self.polygonList[idx]['selected'] self.update() elif event.button() == Qt.RightButton and self.drawing: # check if it's confirm of cancel self.__drawExit()
def showimage(mimage): from ImageViewer import ImageViewer d = QDialog() d.setGeometry(50,50,700,700) layout = QVBoxLayout(d) viewer = ImageViewer(mimage) layout.addWidget(viewer) d.setWindowTitle("Dialog") d.setWindowModality(Qt.ApplicationModal) d.exec_()
def __init__(self, parent, controller): tk.Frame.__init__(self, parent) self.filename = "" self.original_image = None self.processed_image = None self.is_image_selected = False self.is_draw_state = False self.is_crop_state = False self.filter_frame = None self.adjust_frame = None self.editBar = EditBar(master=self) separator1 = ttk.Separator(master=self, orient=tk.HORIZONTAL) self.image_viewer = ImageViewer(master=self) self.editBar.pack(pady=10) separator1.pack(fill=tk.X, padx=20, pady=5) self.image_viewer.pack(fill=tk.BOTH, padx=20, pady=10, expand=1)
class ImageAnalyzer: def __init__(self, data_dir, deps_dir, output_dir): print("Constructing Image Analyzer") self.warehouse = ImageWarehouse(data_dir, deps_dir) self.viewer = ImageViewer(output_dir) def undistortImages(self, path, name): self.warehouse.importImages(path, name) def buildLidarPointCloud(self, path, name): self.warehouse.build3DPointCloud(path, name) def saveImages(self): for key, value in self.warehouse.images_dict.iteritems(): self.viewer.showImages(key, value[0]) def saveRawLidarPointClouds(self): for key, value in self.warehouse.ptcloud_dict.iteritems(): self.viewer.plot3DPointCloud(key, value[0], value[1]) def showPointCloudsOnImages(self, img_key, ptcld_key, poses_path): [images, camera_model] = self.warehouse.images_dict[img_key] for img in images: [uv, depth ] = self.warehouse.buildPtCloudOnImage(img, camera_model, ptcld_key, poses_path) self.viewer.showPointCloudOnImage(ptcld_key, img_key, img, uv, depth)
def __init__(self, titile, parent=None, pixmap=None): super(ImageWindow, self).__init__(parent) self._title_base = titile self.setWindowTitle(titile) self.setMinimumWidth(DEFAULT_CALLGRAPH_DLG_WIDTH) self.setMinimumHeight(DEFAULT_CALLGRAPH_DLG_HEIGHT) self.initMenuBar() self._pixmap = pixmap from ImageViewer import ImageViewer self._image_viewer = ImageViewer(pixmap) self.setCentralWidget(self._image_viewer)
def __init__(self): super(Application, self).__init__() self.RESIZED_WIDTH = 1500 self.RESIZED_HEIGHT = 2100 self.AREA_SIZE = 250 self.THRESHOLD_VALUE = 230 self.global_dir = r"D:\Developments\Projects\XLA\output\global" self.local_dir = r"D:\Developments\Projects\XLA\output\local" self.rotate_dir = r"D:\Developments\Projects\XLA\output\rotate" self.morphology_dir = r"D:\Developments\Projects\XLA\output\morphology" self.mark_x = 0 self.mark_y = 0 self.choice_image_path = '' self.rotated_image_path = '' self.global_threshold_path = '' self.morphology_image_path = '' self.global_threshold_image = None self.local_threshold_image = None self.morphology_image = None self.rotated_image = None self.original_image_viewer = ImageViewer() self.global_image_viewer = ImageViewer() self.local_image_viewer = ImageViewer() self.rotate_image_viewer = ImageViewer() self.morphology_image_viewer = ImageViewer() self.result_viewer = None self.setGeometry(100, 100, 300, 400) self.setWindowTitle("Image Processing") self.init_ui()
class NBrowser(QtGui.QWidget): def __init__(self, parent=None): super(NBrowser, self).__init__(parent) self.vmainLayout = QtGui.QVBoxLayout() self.hmainLayout = QtGui.QHBoxLayout() self.fs = FileSelector() self.imv = ImageViewer() self.info = InfoViewer(1) self.vmainLayout.addWidget(self.fs) self.vsecondLayout = QtGui.QVBoxLayout() self.hmainLayout.addWidget(self.imv) self.vsecondLayout.addWidget(self.info) self.vsecondLayout.addItem(QtGui.QSpacerItem(40,20,QtGui.QSizePolicy.Minimum,QtGui.QSizePolicy.Expanding)) self.hmainLayout.addLayout(self.vsecondLayout) self.vmainLayout.addLayout(self.hmainLayout) self.setLayout(self.vmainLayout) self.show() self.connect(self.fs.selectComboBox, QtCore.SIGNAL("currentIndexChanged(int)"),self.update_all) self.connect(self.imv.processComboBox, QtCore.SIGNAL("currentIndexChanged(int)"),self.update_process) self.connect(self.imv.channelComboBox, QtCore.SIGNAL("currentIndexChanged(int)"),self.update_process) self.imv.imv.getHistogramWidget().item.sigLevelsChanged.connect(self.update_process) def update_all(self): #print 'update all' self.imv.update_all(self.fs.param,self.fs.data) self.info.update_info(self.fs.param) def update_process(self): channel = str(self.imv.channelComboBox.currentText()) process_id = self.imv.processComboBox.currentIndex() min_max = self.imv.imv.getImageItem().getLevels() out = {} out[channel] = [process_id,min_max] if len(channel) > 2: self.info.update_process(out)
class AppContext(ApplicationContext): def __init__(self): super().__init__() self.image_viewer = ImageViewer() def run(self): self.image_viewer.show() self.image_viewer.show_set_Dialog() self.image_viewer.start_slideshow() return self.app.exec_()
def __init__(self, parent=None): super(NBrowser, self).__init__(parent) self.vmainLayout = QtGui.QVBoxLayout() self.hmainLayout = QtGui.QHBoxLayout() self.fs = FileSelector() self.imv = ImageViewer() self.info = InfoViewer(1) self.vmainLayout.addWidget(self.fs) self.vsecondLayout = QtGui.QVBoxLayout() self.hmainLayout.addWidget(self.imv) self.vsecondLayout.addWidget(self.info) self.vsecondLayout.addItem(QtGui.QSpacerItem(40,20,QtGui.QSizePolicy.Minimum,QtGui.QSizePolicy.Expanding)) self.hmainLayout.addLayout(self.vsecondLayout) self.vmainLayout.addLayout(self.hmainLayout) self.setLayout(self.vmainLayout) self.show() self.connect(self.fs.selectComboBox, QtCore.SIGNAL("currentIndexChanged(int)"),self.update_all) self.connect(self.imv.processComboBox, QtCore.SIGNAL("currentIndexChanged(int)"),self.update_process) self.connect(self.imv.channelComboBox, QtCore.SIGNAL("currentIndexChanged(int)"),self.update_process) self.imv.imv.getHistogramWidget().item.sigLevelsChanged.connect(self.update_process)
import sys from ImageViewer import ImageViewer from PyQt5.QtWidgets import QApplication if __name__ == '__main__': app = QApplication(sys.argv) app.setStyle("Fusion") window = ImageViewer() window.center_on_screen() window.show() sys.exit(app.exec_())
class InitConditionsWindow(QDialog): def __init__(self, Image=None, FileList = None, Folder = None, FaceCenter = None, InitFrame = None, threshold = None, EyesCenter = None): super(InitConditionsWindow, self).__init__() # self._scene = QtWidgets.QGraphicsScene(self) # self.setScene(self._scene) #FileList = ['Basler acA800-510uc (22501173)_20180523_154539113_0001.tiff', 'Basler acA800-510uc (22501173)_20180523_154539113_0002.tiff', 'Basler acA800-510uc (22501173)_20180523_154539113_0003.tiff', 'Basler acA800-510uc (22501173)_20180523_154539113_0004.tiff', 'Basler acA800-510uc (22501173)_20180523_154539113_0005.tiff', 'Basler acA800-510uc (22501173)_20180523_154539113_0006.tiff', 'Basler acA800-510uc (22501173)_20180523_154539113_0007.tiff', 'Basler acA800-510uc (22501173)_20180523_154539113_0008.tiff', 'Basler acA800-510uc (22501173)_20180523_154539113_0009.tiff'] #Folder = r'G:\VideoForWhisking\test' # RightROI = np.array([[368,387],[324,329],[299,261],[230,157],[196,78],[ 21,77],[16,581],[373,585]]) # LeftROI = np.array([[440,387],[484,329],[509,261],[578,157],[612,78],[787,77],[792,581],[435,585]]) #FaceCenter = np.array([404,302]) #InitFrame = 1 #ff = r'G:\VideoForWhisking\2018_05_23\background\Basler acA800-510uc (22501173)_20180523_145714943_0001.tiff' #threshold = cv2.imread(ff,0) self._Folder = Folder self._FileList = FileList self._InitFrame = 1 self._FaceCenter = FaceCenter self._EyesCenter = EyesCenter self._threshold = threshold self._Image = Image self._RightEyePosition = [] self._LeftEyePosition = [] self._SnoutPosition = [] self._rad = [] self._hasAngleTempRight = [[False],[False]] #a temporary version of the variable self._hasAngle self._hasAngleTempLeft = [[False],[False]] #a temporary version of the variable self._hasAngle self._temp_storage_right = [[None],[None]] self._temp_storage_left = [[None],[None]] self._rightAngle = None self._leftAngle = None self._Initial_Conditions = np.array([None, None]) self.initUI() def initUI(self): self.setWindowTitle('Visualize Initial Conditions') scriptDir = os.getcwd() self.setWindowIcon(QtGui.QIcon(scriptDir + os.path.sep + 'face_icon.ico')) self.setAttribute(QtCore.Qt.WA_DeleteOnClose) self.setWindowFlags(self.windowFlags() | QtCore.Qt.WindowSystemMenuHint | QtCore.Qt.WindowMinMaxButtonsHint) #Top part newfont = QtGui.QFont("Times", 12) self.label1 = QLabel('Initial Frame:') self.label1.setFont(newfont) self.label1.setFixedWidth(250) self._FramestoAnalizeInitEdit = QLineEdit(self) self._FramestoAnalizeInitEdit.setText(str(self._InitFrame)) self._FramestoAnalizeInitEdit.setFont(newfont) self._FramestoAnalizeInitEdit.setFixedWidth(75) validator = QtGui.QIntValidator(1, len(self._FileList)) self._FramestoAnalizeInitEdit.setValidator(validator) #buttons DoneButton = QPushButton('&Find Face Center', self) DoneButton.setFixedWidth(250) DoneButton.setFont(newfont) DoneButton.clicked.connect(self.Start) self.InitConditionsButton = QPushButton('&Compute Initial Conditions', self) self.InitConditionsButton.setFixedWidth(250) self.InitConditionsButton.setFont(newfont) self.InitConditionsButton.clicked.connect(self.Init_Conditions) self.InitConditionsButton.setEnabled(False) TopLayout = QtWidgets.QGridLayout() TopLayout.addWidget(self.label1, 0 , 0 ,1 ,1 ) TopLayout.addWidget(self._FramestoAnalizeInitEdit, 0 , 1, 1, 1) TopLayout.addWidget(DoneButton, 1 , 0, 1,1) TopLayout.addWidget(self.InitConditionsButton, 2 , 0, 1,1) buttonLayout = QtWidgets.QHBoxLayout() buttonLayout.addWidget(DoneButton) self.RightEyeButton = QPushButton('&Right Eye', self) self.RightEyeButton.setFixedWidth(150) self.RightEyeButton.setFont(newfont) self.RightEyeButton.clicked.connect(self.Locate_Right_Eye) self.LeftEyeButton = QPushButton('&Left Eye', self) self.LeftEyeButton.setFixedWidth(150) self.LeftEyeButton.setFont(newfont) self.LeftEyeButton.clicked.connect(self.Locate_Left_Eye) self.LeftEyeButton.setEnabled(False) self.SnoutButton = QPushButton('&Snout', self) self.SnoutButton.setFixedWidth(150) self.SnoutButton.setFont(newfont) self.SnoutButton.clicked.connect(self.Locate_Snout) self.SnoutButton.setEnabled(False) ButtonBox = QtWidgets.QGroupBox('') ButtonBox.setFixedWidth(170) ButtonBox.setFixedHeight(120) ButtonBox.setStyleSheet(self.getStyleSheet(scriptDir + os.path.sep + 'include' + os.path.sep + 'GroupBoxStyle.qss')) ButtonLayout = QtWidgets.QVBoxLayout() ButtonLayout.addWidget(self.RightEyeButton) ButtonLayout.addWidget(self.LeftEyeButton) ButtonLayout.addWidget(self.SnoutButton) #ButtonLayout.addWidget(self.WhiskersButton) ButtonLayout.addStretch(1) ButtonBox.setLayout(ButtonLayout) DoneButton = QPushButton('&Close', self) DoneButton.setFixedWidth(150) DoneButton.setFont(newfont) DoneButton.clicked.connect(self.Done) DoneButton.setEnabled(True) DoneButtonBox = QtWidgets.QGroupBox('') DoneButtonBox.setFixedWidth(170) DoneButtonBox.setFixedHeight(55) DoneButtonBox.setStyleSheet(self.getStyleSheet(scriptDir + os.path.sep + 'include' + os.path.sep + 'GroupBoxStyle.qss')) DoneButtonLayout = QtWidgets.QVBoxLayout() DoneButtonLayout.addWidget(DoneButton) #ButtonLayout.addWidget(self.WhiskersButton) DoneButtonLayout.addStretch(1) DoneButtonBox.setLayout(DoneButtonLayout) ViewLayout = QtWidgets.QHBoxLayout() self.displayImage = ImageViewer() color = self.palette().color(QtGui.QPalette.Background) self.displayImage.setBackgroundBrush(color) ViewLayout.addWidget(self.displayImage) #layout = QtWidgets.QVBoxLayout() layout = QtWidgets.QGridLayout() layout.addLayout(TopLayout,0,0,1,3) #layout.addLayout(buttonLayout,1,1,1,1) layout.addWidget(ButtonBox,1,0,1,1) layout.addWidget(DoneButtonBox, 2,0,1,1) layout.addLayout(ViewLayout,1,1,3,3) #layout.addLayout(ButtonBox) self.setLayout(layout) #fix the size, the user cannot change it #self.resize(self.sizeHint()) #self.setFixedSize(self.size()) self.setGeometry(100,100,300,300) self.show() def Start(self): #verify if the image viwer is empty. If then clean the image viwer if self._Image is not None: #remove all lines in the graph for item in self.displayImage._scene.items(): if isinstance(item, QtWidgets.QGraphicsLineItem): self.displayImage._scene.removeItem(item) if isinstance(item, QtWidgets.QGraphicsEllipseItem): self.displayImage._scene.removeItem(item) # #Frames to analize Init_Frame = int(self._FramestoAnalizeInitEdit.text()) if Init_Frame == 0: QtWidgets.QMessageBox.warning(self, 'Error','Frame number must be larger than 0') return #read images from memory in gray format temp_image = cv2.imread(os.path.join(self._Folder,self._FileList[Init_Frame-1])) temp_image = cv2.cvtColor(temp_image,cv2.COLOR_BGR2RGB) self._Image = cv2.cvtColor(temp_image , cv2.COLOR_BGR2GRAY) image = self._Image.copy() image = image.astype(np.uint8) height, width = image.shape bytesPerLine = 1 * width #img_Qt = QtGui.QImage(self._ImageDos.data, width, height, bytesPerLine, QtGui.QImage.Format_RGB888) img_Qt = QtGui.QImage(image.data, width, height, bytesPerLine, QtGui.QImage.Format_Indexed8) img_show = QtGui.QPixmap.fromImage(img_Qt) self.setGeometry(self.geometry().topLeft().x(),self.geometry().topLeft().y(),width+200,height+200) #show the photo if self._FaceCenter is not None: self.displayImage._FaceCenter = self._FaceCenter self.InitConditionsButton.setEnabled(True) self.displayImage.setPhotoFirstTime(img_show) else: face_center,snout,_,isFaceCenter = find_center_whiskerpad(self._Image) if isFaceCenter is True: self._FaceCenter = face_center self.displayImage._FaceCenter = face_center self.InitConditionsButton.setEnabled(True) self.displayImage.setPhotoFirstTime(img_show) self.displayImage.draw_circle(np.array([snout[0],snout[1],int((0.5/100)*width)])) else: self.displayImage.setPhotoFirstTime(img_show) #self.displayImage.setPhoto(img_show) def Init_Conditions(self): if self._FaceCenter is not None: Init_Frame = int(self._FramestoAnalizeInitEdit.text())-1 init_cond = initial_conditions(self._FileList, self._Folder, self._FaceCenter, self._threshold, Init_Frame) self._rightAngle = init_cond[0] self._leftAngle = init_cond[1] image = self._Image.copy() image = image.astype(np.uint8) height, width = image.shape bytesPerLine = 1 * width #img_Qt = QtGui.QImage(self._ImageDos.data, width, height, bytesPerLine, QtGui.QImage.Format_RGB888) img_Qt = QtGui.QImage(image.data, width, height, bytesPerLine, QtGui.QImage.Format_Indexed8) img_show = QtGui.QPixmap.fromImage(img_Qt) self.displayImage.setPhoto(img_show, init_cond) def Locate_Right_Eye(self): #doing nothin at the moment, inform the display self.displayImage._isManualEstimation = False self.displayImage._isRightEyeInit = False self.displayImage._isLeftEyeInit = False self.displayImage._isSnoutInit = False #clean screen if self._Image is not None: #remove all lines in the graph for item in self.displayImage._scene.items(): if isinstance(item, QtWidgets.QGraphicsLineItem): self.displayImage._scene.removeItem(item) if isinstance(item, QtWidgets.QGraphicsEllipseItem): self.displayImage._scene.removeItem(item) #block button that cannot be used self.LeftEyeButton.setEnabled(False) self.SnoutButton.setEnabled(False) #self.WhiskersButton.setEnabled(False) self._RightEyePosition = [] self._LeftEyePosition = [] self._SnoutPosition = [] self._rad = [] self.displayImage._isRightEyeInit = True self.displayImage.signalEmit.connect(self.Locate_Right_Eye_update) @QtCore.pyqtSlot(object,int,str) def Locate_Right_Eye_update(self, position,number, action): self._RightEyePosition=position self.displayImage.signalEmit.disconnect(self.Locate_Right_Eye_update) self.displayImage._isRightEyeInit = False self.LeftEyeButton.setEnabled(True) def Locate_Left_Eye(self): #doing nothin at the moment, inform the display self.displayImage._isManualEstimation = False self.displayImage._isRightEyeInit = False self.displayImage._isLeftEyeInit = False self.displayImage._isSnoutInit = False #clean screen if self._Image is not None: #remove all lines in the graph for item in self.displayImage._scene.items(): if isinstance(item, QtWidgets.QGraphicsLineItem): self.displayImage._scene.removeItem(item) if isinstance(item, QtWidgets.QGraphicsEllipseItem): if item.pen().color() == QtCore.Qt.cyan: pass else: self.displayImage._scene.removeItem(item) #block button that cannot be used self.SnoutButton.setEnabled(False) #self.WhiskersButton.setEnabled(False) self._LeftEyesPosition = [] self._SnoutPosition = [] self._rad = [] self.displayImage._isLeftEyeInit = True self.displayImage.signalEmit.connect(self.Locate_Left_Eye_update) @QtCore.pyqtSlot(object,int,str) def Locate_Left_Eye_update(self, position,number, action): self._LeftEyePosition=position self.displayImage.signalEmit.disconnect(self.Locate_Left_Eye_update) self.displayImage._isLeftEyeInit = False self._EyesCenter = find_center_eyes_with_click(self._Image, self._RightEyePosition, self._LeftEyePosition) rect = QtCore.QRectF(self.displayImage._photo.pixmap().rect()) #view_width=rect.width() view_height=rect.height() #self.displayImage.draw_line(0,center_eyes,view_width,center_eyes) self.displayImage.draw_line(self._EyesCenter[0],0,self._EyesCenter[0],view_height) self.SnoutButton.setEnabled(True) def Locate_Snout(self): #doing nothin at the moment, inform the display self.displayImage._isManualEstimation = False self.displayImage._isRightEyeInit = False self.displayImage._isLeftEyeInit = False self.displayImage._isSnoutInit = False #remove all blue dots for item in self.displayImage._scene.items(): if isinstance(item, QtWidgets.QGraphicsEllipseItem): if item.pen().color() == QtCore.Qt.blue: self.displayImage._scene.removeItem(item) if item.pen().color() == QtCore.Qt.yellow: self.displayImage._scene.removeItem(item) if item.pen().color() == QtCore.Qt.red: self.displayImage._scene.removeItem(item) if item.pen().color() == QtCore.Qt.white: self.displayImage._scene.removeItem(item) if isinstance(item, QtWidgets.QGraphicsLineItem): if item.boundingRect().width() > 5: self.displayImage._scene.removeItem(item) #block button that cannot be used #self.WhiskersButton.setEnabled(False) self._SnoutPosition = [] self._rad = [] self.displayImage._isSnoutInit = True self.displayImage._FaceCenter = self._EyesCenter self.displayImage.signalEmit.connect(self.Locate_Snout_update) @QtCore.pyqtSlot(object,int,str) def Locate_Snout_update(self,position,number, action): self._SnoutPosition=position self.displayImage.signalEmit.disconnect(self.Locate_Snout_update) self.displayImage._isSnoutInit = False distance_eyes_snout = (2/3)*(position[1]-self._EyesCenter[1]) #my definition of center of whisker pad is 2/3 of the distance between eyes and snout #now the we know where the snout is, update the location of FaceCenter self._FaceCenter = np.array([self._EyesCenter[0],self._EyesCenter[1] + int(round(distance_eyes_snout))]) #draw it rect = QtCore.QRectF(self.displayImage._photo.pixmap().rect()) view_width=rect.width() #view_height=rect.height() self.displayImage.draw_line(0,self._FaceCenter[1],view_width,self._FaceCenter[1]) #self.displayImage.draw_line(self._EyesCenter[0],0,self._EyesCenter[0],view_height) rad = 1.5*(1-2/3)*(position[1]-self._EyesCenter[1]) self._rad = rad #this is the radius of the circle used for location of initial conditions self.displayImage.draw_circle([self._FaceCenter[0],self._FaceCenter[1],rad], 'big') #activate whiskers button self.Locate_Whiskers() def Locate_Whiskers(self): #doing nothin at the moment, inform the display self.displayImage._isManualEstimation = False self.displayImage._isRightEyeInit = False self.displayImage._isLeftEyeInit = False self.displayImage._isSnoutInit = False #remove all blue dots for item in self.displayImage._scene.items(): if isinstance(item, QtWidgets.QGraphicsEllipseItem): if item.pen().color() == QtCore.Qt.blue: self.displayImage._scene.removeItem(item) if item.pen().color() == QtCore.Qt.red: self.displayImage._scene.removeItem(item) if isinstance(item, QtWidgets.QGraphicsLineItem): if item.pen().color() == QtCore.Qt.red: self.displayImage._scene.removeItem(item) if item.pen().color() == QtCore.Qt.blue: self.displayImage._scene.removeItem(item) self._hasAngleTempRight = [[False],[False]] #a temporary version of the variable self._hasAngle self._hasAngleTempLeft = [[False],[False]] #a temporary version of the variable self._hasAngle self._temp_storage_right = [[None],[None]] self._temp_storage_left = [[None],[None]] self.displayImage._isManualEstimation = True self.displayImage._rad = self._rad self.displayImage._FaceCenter = self._FaceCenter self.displayImage.signalEmit.connect(self.Locate_Whiskers_update) self.displayImage.finished.connect(self.Locate_Whiskers_end) @QtCore.pyqtSlot(object,int,str) def Locate_Whiskers_update(self,position,number, action): if action == 'append': #append the information in the current frame if position[0]<self._FaceCenter[0]: if number == 1: self._hasAngleTempRight[0]= True self._temp_storage_right[0]= [position[0],position[1]]#angle_est elif number == 2: self._hasAngleTempRight[1] = True self._temp_storage_right[1] = [position[0],position[1]]#angle_est elif position[0]>self._FaceCenter[0]: # angle_est = np.arctan(((position[0] - self._FaceCenter[0])/(self._FaceCenter[1]-position[1])))*(180/np.pi) # if angle_est < 0 : # angle_est = 180+angle_est if number == 1: self._hasAngleTempLeft[0] = True self._temp_storage_left[0] = [position[0],position[1]]#angle_est elif number == 2: self._hasAngleTempLeft[1] = True self._temp_storage_left[1]= [position[0],position[1]]#angle_est elif action == 'remove': #remove the information from the current frame self._hasAngleTempRight[0]= False self._temp_storage_right[0] = None self._hasAngleTempRight[1] = False self._temp_storage_right[1] = None self._hasAngleTempLeft[0] = False self._temp_storage_left[0] = None self._hasAngleTempLeft[1] = False self._temp_storage_left[1] = None def Locate_Whiskers_end(self): self.displayImage._isManualEstimation = False #end manual estimation right = None left = None if (self._hasAngleTempRight[0] is True) and (self._hasAngleTempRight[1] is True): #print(self._FaceCenter) x1 = self._FaceCenter[0] - self._temp_storage_right[0][0] y1 = self._FaceCenter[1] - self._temp_storage_right[0][1] x2 = self._FaceCenter[0] - self._temp_storage_right[1][0] y2 = self._FaceCenter[1] - self._temp_storage_right[1][1] rad = np.sqrt(x1**2 + y1**2) p = rad*(x1+x2)/(np.sqrt((x1+x2)**2 + (y1+y2)**2)) q = ((y1+y2)/(x1+x2))*p #p = self._FaceCenter[0]-p #q = self._FaceCenter[1]-q if q == 0: angle_est = 0 else: angle_est = np.arctan(((p)/(-q)))*180/np.pi + 90 # if angle_est < 0 : # angle_est = 180+angle_est right = angle_est if (self._hasAngleTempLeft[0] is True) and (self._hasAngleTempLeft[1] is True): x1 = self._FaceCenter[0] - self._temp_storage_left[0][0] y1 = self._FaceCenter[1] - self._temp_storage_left[0][1] x2 = self._FaceCenter[0] - self._temp_storage_left[1][0] y2 = self._FaceCenter[1] - self._temp_storage_left[1][1] rad = np.sqrt(x1**2 + y1**2) p = rad*(x1+x2)/(np.sqrt((x1+x2)**2 + (y1+y2)**2)) q = ((y1+y2)/(x1+x2))*p if q == 0 : angle_est = 180 else: angle_est = np.arctan(((p)/(q)))*180/np.pi -90 # if angle_est < 0 : # angle_est = 180+angle_est left = angle_est if right is not None and left is not None: self._rightAngle = right self._leftAngle = left l_bar = self._FaceCenter[1]*0.75 dy_right= l_bar*np.tan(self._rightAngle*np.pi/180) dy_left= l_bar*np.tan(self._leftAngle*np.pi/180) # self.draw_line(self._FaceCenter[0],self._FaceCenter[1], self._FaceCenter[0]-l_bar, int(self._FaceCenter[1]-dy_right),1,3) # self.draw_line(self._FaceCenter[0],self._FaceCenter[1], self._FaceCenter[0]+l_bar, int(self._FaceCenter[1]-dy_left),1,3) self.displayImage.draw_line(self._FaceCenter[0],self._FaceCenter[1], self._FaceCenter[0]-l_bar, self._FaceCenter[1]-dy_right,1,3) self.displayImage.draw_line(self._FaceCenter[0],self._FaceCenter[1], self._FaceCenter[0]+l_bar, self._FaceCenter[1]-dy_left,1,3) for item in self.displayImage._scene.items(): if isinstance(item, QtWidgets.QGraphicsEllipseItem): if item.pen().color() == QtCore.Qt.cyan: self.displayImage._scene.removeItem(item) if item.pen().color() == QtCore.Qt.magenta: self.displayImage._scene.removeItem(item) if item.pen().color() == QtCore.Qt.white: self.displayImage._scene.removeItem(item) def Done(self): self._InitFrame = int(self._FramestoAnalizeInitEdit.text())-1 self._Initial_Conditions = np.array([self._rightAngle, self._leftAngle]) if self._FaceCenter is None and self._Initial_Conditions[0] is None: #ask is the user really wants to close the app choice = QtWidgets.QMessageBox.question(self, 'Message', 'Face Center and Initial Conditions not defined. Frames cannot be proccessed.\nDo you want to exit?', QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No, QtWidgets.QMessageBox.No) if choice == QtWidgets.QMessageBox.Yes : self.close() else: return elif self._FaceCenter is None: choice = QtWidgets.QMessageBox.question(self, 'Message', 'Face Center not defined, frames cannot be proccessed.\nDo you want to exit?', QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No, QtWidgets.QMessageBox.No) if choice == QtWidgets.QMessageBox.Yes : self.close() else: return elif self._Initial_Conditions[0] is None: #ask is the user really wants to close the app choice = QtWidgets.QMessageBox.question(self, 'Message', 'Initial Conditions not defined.\nDo you want to exit?', QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No, QtWidgets.QMessageBox.No) if choice == QtWidgets.QMessageBox.Yes : self.close() else: return else: self.close() def closeEvent(self, event): event.accept() #this function read the style sheet used to presents the GroupBox, #it is located in .\include\GroupBoxStyle.qss def getStyleSheet(self, path): f = QFile(path) f.open(QFile.ReadOnly | QFile.Text) stylesheet = QTextStream(f).readAll() f.close() return stylesheet
def initUI(self): self.setWindowTitle('Visualize Initial Conditions') scriptDir = os.getcwd() self.setWindowIcon(QtGui.QIcon(scriptDir + os.path.sep + 'face_icon.ico')) self.setAttribute(QtCore.Qt.WA_DeleteOnClose) self.setWindowFlags(self.windowFlags() | QtCore.Qt.WindowSystemMenuHint | QtCore.Qt.WindowMinMaxButtonsHint) #Top part newfont = QtGui.QFont("Times", 12) self.label1 = QLabel('Initial Frame:') self.label1.setFont(newfont) self.label1.setFixedWidth(250) self._FramestoAnalizeInitEdit = QLineEdit(self) self._FramestoAnalizeInitEdit.setText(str(self._InitFrame)) self._FramestoAnalizeInitEdit.setFont(newfont) self._FramestoAnalizeInitEdit.setFixedWidth(75) validator = QtGui.QIntValidator(1, len(self._FileList)) self._FramestoAnalizeInitEdit.setValidator(validator) #buttons DoneButton = QPushButton('&Find Face Center', self) DoneButton.setFixedWidth(250) DoneButton.setFont(newfont) DoneButton.clicked.connect(self.Start) self.InitConditionsButton = QPushButton('&Compute Initial Conditions', self) self.InitConditionsButton.setFixedWidth(250) self.InitConditionsButton.setFont(newfont) self.InitConditionsButton.clicked.connect(self.Init_Conditions) self.InitConditionsButton.setEnabled(False) TopLayout = QtWidgets.QGridLayout() TopLayout.addWidget(self.label1, 0 , 0 ,1 ,1 ) TopLayout.addWidget(self._FramestoAnalizeInitEdit, 0 , 1, 1, 1) TopLayout.addWidget(DoneButton, 1 , 0, 1,1) TopLayout.addWidget(self.InitConditionsButton, 2 , 0, 1,1) buttonLayout = QtWidgets.QHBoxLayout() buttonLayout.addWidget(DoneButton) self.RightEyeButton = QPushButton('&Right Eye', self) self.RightEyeButton.setFixedWidth(150) self.RightEyeButton.setFont(newfont) self.RightEyeButton.clicked.connect(self.Locate_Right_Eye) self.LeftEyeButton = QPushButton('&Left Eye', self) self.LeftEyeButton.setFixedWidth(150) self.LeftEyeButton.setFont(newfont) self.LeftEyeButton.clicked.connect(self.Locate_Left_Eye) self.LeftEyeButton.setEnabled(False) self.SnoutButton = QPushButton('&Snout', self) self.SnoutButton.setFixedWidth(150) self.SnoutButton.setFont(newfont) self.SnoutButton.clicked.connect(self.Locate_Snout) self.SnoutButton.setEnabled(False) ButtonBox = QtWidgets.QGroupBox('') ButtonBox.setFixedWidth(170) ButtonBox.setFixedHeight(120) ButtonBox.setStyleSheet(self.getStyleSheet(scriptDir + os.path.sep + 'include' + os.path.sep + 'GroupBoxStyle.qss')) ButtonLayout = QtWidgets.QVBoxLayout() ButtonLayout.addWidget(self.RightEyeButton) ButtonLayout.addWidget(self.LeftEyeButton) ButtonLayout.addWidget(self.SnoutButton) #ButtonLayout.addWidget(self.WhiskersButton) ButtonLayout.addStretch(1) ButtonBox.setLayout(ButtonLayout) DoneButton = QPushButton('&Close', self) DoneButton.setFixedWidth(150) DoneButton.setFont(newfont) DoneButton.clicked.connect(self.Done) DoneButton.setEnabled(True) DoneButtonBox = QtWidgets.QGroupBox('') DoneButtonBox.setFixedWidth(170) DoneButtonBox.setFixedHeight(55) DoneButtonBox.setStyleSheet(self.getStyleSheet(scriptDir + os.path.sep + 'include' + os.path.sep + 'GroupBoxStyle.qss')) DoneButtonLayout = QtWidgets.QVBoxLayout() DoneButtonLayout.addWidget(DoneButton) #ButtonLayout.addWidget(self.WhiskersButton) DoneButtonLayout.addStretch(1) DoneButtonBox.setLayout(DoneButtonLayout) ViewLayout = QtWidgets.QHBoxLayout() self.displayImage = ImageViewer() color = self.palette().color(QtGui.QPalette.Background) self.displayImage.setBackgroundBrush(color) ViewLayout.addWidget(self.displayImage) #layout = QtWidgets.QVBoxLayout() layout = QtWidgets.QGridLayout() layout.addLayout(TopLayout,0,0,1,3) #layout.addLayout(buttonLayout,1,1,1,1) layout.addWidget(ButtonBox,1,0,1,1) layout.addWidget(DoneButtonBox, 2,0,1,1) layout.addLayout(ViewLayout,1,1,3,3) #layout.addLayout(ButtonBox) self.setLayout(layout) #fix the size, the user cannot change it #self.resize(self.sizeHint()) #self.setFixedSize(self.size()) self.setGeometry(100,100,300,300) self.show()
if event == CviConstants.EVENT_TIMER_TICK: # All PyGTK applications must have a gtk.main(). Control ends here # and waits for an event to occur (like a key press or mouse event). print "Running Gtk Main" idle_tag = gobject.idle_add(on_idle) gtk.main() # Never exits callback print "Disabling Timer" self.Attributes['ATTR_ENABLED'] = 0 # Disable time after first tick return 0 def ShowIcsViewer(): icsViewer = IcsViewer.IcsViewer("Test Viewer") F = FIA.FIAImage() F.load(r"C:\Documents and Settings\Pierce\Desktop\Working Area\Test Images\wallpaper_river.jpg") icsViewer.LoadImage(F.getBitmap()) icsViewer.Show() imageViewer = ImageViewer.ImageViewer() fib = FI_ICS.FreeImageIcs_LoadFIBFromIcsFilePath(r"C:\Documents and Settings\Pierce\Desktop\Working Area\Test Images\cells.ics") F = FIA.FIAImage() F.loadFromBitmap(fib) F.SetRainBowPalette() imageViewer.BasicWin32Window("Test", 100, 100, 500, 400, F.getBitmap()) Cvi.RunUserInterface()
import sys from PyQt5 import QtCore, QtWidgets from ImageViewer import ImageViewer from PyQt5.QtWidgets import QApplication if __name__ == '__main__': app = QApplication(sys.argv) app.setStyle("Fusion") window = ImageViewer() window.show() sys.exit(app.exec())
from PySide import QtGui from ImageViewer import ImageViewer import sys if __name__ == '__main__': app = QtGui.QApplication(sys.argv) imageViewer = ImageViewer() imageViewer.show() sys.exit(app.exec_())
class ImageWindow(QMainWindow): def __init__(self, titile, parent=None, pixmap=None): super(ImageWindow, self).__init__(parent) self._title_base = titile self.setWindowTitle(titile) self.setMinimumWidth(DEFAULT_CALLGRAPH_DLG_WIDTH) self.setMinimumHeight(DEFAULT_CALLGRAPH_DLG_HEIGHT) self.initMenuBar() self._pixmap = pixmap from ImageViewer import ImageViewer self._image_viewer = ImageViewer(pixmap) self.setCentralWidget(self._image_viewer) def initMenuBar(self): menubar = self.menuBar() filemenu = menubar.addMenu('&File') filemenu.addAction(QAction("Save As...", self, shortcut="Ctrl+S", triggered=self.saveImage)) filemenu.addSeparator() filemenu.addAction(QAction("&Print...", self, enabled=False, shortcut="Ctrl+P", triggered=self.printImage)) filemenu.addSeparator() filemenu.addAction(QAction("&Exit", self, shortcut=QKeySequence.Quit, triggered=self.close)) viewmenu = menubar.addMenu('&View') viewmenu.addAction(QAction("Zoom &In (25%)", self, shortcut=QKeySequence.ZoomIn, triggered=self.zoomIn)) viewmenu.addAction(QAction("Zoom &Out (25%)", self, shortcut=QKeySequence.ZoomOut, triggered=self.zoomOut)) viewmenu.addSeparator() viewmenu.addAction(QAction("Actual &Size", self, shortcut="Ctrl+=", triggered=self.setImageToActualSize)) viewmenu.addAction(QAction("Fit &To Window", self, shortcut="Ctrl+Enter", triggered=self.fitImageToWindow)) helpMenu = menubar.addMenu(self.tr('&Help')) helpMenu.addAction(QAction('&Image Controls', self, triggered=self.showControlsDialog)) def setTitleDetails(self, details): self.setWindowTitle('%s - %s' % (self._title_base, details)) def setPixmap(self, pixmap): self._pixmap = pixmap from ImageViewer import ImageViewer self._image_viewer = ImageViewer(pixmap) if pixmap.height() > self.height() or pixmap.width() > self.width(): self._image_viewer.fitToWindow() self.setCentralWidget(self._image_viewer) def saveImage(self): if not self._pixmap: QMessageBox().information(self, 'Error', 'You have no image to be saved') return filename = QFileDialog.getSaveFileName(self, 'Save As...', 'callgraph.png', self.tr('*.png')) if filename: fp = QFile(filename) fp.open(QIODevice.WriteOnly) try: self._pixmap.save(fp, 'PNG') except Exception as e: fp.close() QMessageBox().information(self, 'Error', e.message) def printImage(self): printer = QPrinter() dialog = QPrintDialog(printer, self) if dialog.exec_(): painter = QPainter(printer) rect = painter.viewport() size = self.imageLabel.pixmap().size() size.scale(rect.size(), Qt.KeepAspectRatio) painter.setViewport(rect.x(), rect.y(), size.width(), size.height()) painter.setWindow(self.imageLabel.pixmap().rect()) painter.drawPixmap(0, 0, self.imageLabel.pixmap()) def zoomIn(self): self._image_viewer.zoomIn() def zoomOut(self): self._image_viewer.zoomOut() def setImageToActualSize(self): self._image_viewer.actualSize() def fitImageToWindow(self): self._image_viewer.fitToWindow() def showControlsDialog(self): QMessageBox.information(self, "Image Controls", CALLGRAPH_DLG_CONTROLS) def keyPressEvent(self, keyEvent): # overrides to enable panning while dragging. (Shift + Mouse-Left-Button) assert isinstance(keyEvent, QKeyEvent) if keyEvent.key() == Qt.Key_Shift: if not keyEvent.isAutoRepeat() and not self._image_viewer.handDragging: self._image_viewer.enableHandDrag(True) keyEvent.accept() else: keyEvent.ignore() super(ImageWindow, self).keyPressEvent(keyEvent) def keyReleaseEvent(self, keyEvent): # overrides to disable panning while dragging. assert isinstance(keyEvent, QKeyEvent) if keyEvent.key() == Qt.Key_Shift: if not keyEvent.isAutoRepeat() and self._image_viewer.handDragging: self._image_viewer.enableHandDrag(False) keyEvent.accept() else: keyEvent.ignore() super(ImageWindow, self).keyReleaseEvent(keyEvent) def closeEvent(self, event): # overrides close event to save application settings. # self.writeSettings() event.accept() # ------------------------------------------------------------------ def writeSettings(self): settings = QSettings() settings.setValue('pos', self.pos()) settings.setValue('size', self.size()) settings.setValue('windowgeometry', self.saveGeometry()) settings.setValue('windowstate', self.saveState()) def readSettings(self): settings = QSettings() pos = settings.value('pos', QPoint(200, 200)) size = settings.value('size', QSize(400, 400)) self.move(pos) self.resize(size) if settings.contains('windowgeometry'): self.restoreGeometry(settings.value('windowgeometry')) if settings.contains('windowstate'): self.restoreState(settings.value('windowstate'))
class Application(QtWidgets.QMainWindow): def __init__(self): super(Application, self).__init__() self.RESIZED_WIDTH = 1500 self.RESIZED_HEIGHT = 2100 self.AREA_SIZE = 250 self.THRESHOLD_VALUE = 230 self.global_dir = r"D:\Developments\Projects\XLA\output\global" self.local_dir = r"D:\Developments\Projects\XLA\output\local" self.rotate_dir = r"D:\Developments\Projects\XLA\output\rotate" self.morphology_dir = r"D:\Developments\Projects\XLA\output\morphology" self.mark_x = 0 self.mark_y = 0 self.choice_image_path = '' self.rotated_image_path = '' self.global_threshold_path = '' self.morphology_image_path = '' self.global_threshold_image = None self.local_threshold_image = None self.morphology_image = None self.rotated_image = None self.original_image_viewer = ImageViewer() self.global_image_viewer = ImageViewer() self.local_image_viewer = ImageViewer() self.rotate_image_viewer = ImageViewer() self.morphology_image_viewer = ImageViewer() self.result_viewer = None self.setGeometry(100, 100, 300, 400) self.setWindowTitle("Image Processing") self.init_ui() def init_ui(self): open_btn = QtWidgets.QPushButton("Open", self) open_btn.clicked.connect(self.open) open_btn.move(30, 50) threshold_global_btn = QtWidgets.QPushButton("Global Threshold", self) threshold_global_btn.clicked.connect(self.global_threshold) threshold_global_btn.move(30, 100) threshold_local_btn = QtWidgets.QPushButton("Local Threshold", self) threshold_local_btn.clicked.connect(self.local_threshold) threshold_local_btn.move(30, 150) rotate_btn = QtWidgets.QPushButton("Rotate", self) rotate_btn.clicked.connect(self.rotate) rotate_btn.move(170, 50) morphology_btn = QtWidgets.QPushButton("Morphology", self) morphology_btn.clicked.connect(self.morphology) morphology_btn.move(170, 100) get_result_btn = QtWidgets.QPushButton("Get Result", self) get_result_btn.clicked.connect(self.get_result) get_result_btn.move(170, 150) def get_result(self): self.result_viewer = ResultViewer() if len(self.rotated_image_path) == 0: QtWidgets.QMessageBox.question( self, "Warning", "Please rotate image before get result", QtWidgets.QMessageBox.Ok) return rotated = self.rotated_image ret, image = cv2.threshold(rotated, self.THRESHOLD_VALUE, 255, cv2.THRESH_BINARY) coor = (self.mark_x, self.mark_y) marks, id_marks, answer_marks = find_coordinate(image, coor) # read image, get id, answers then save to a matrix sbd = get_id(image, marks, id_marks) answer = get_answer(image, marks, answer_marks) # read answer, id from a id matrix, answer matrix student_id = read_student_id(sbd) test_id = read_test_id(sbd) ans = read_answer(answer) self.result_viewer.create_grid_layout(student_id, test_id, ans) self.result_viewer.show_result() def open(self): file_name = QtWidgets.QFileDialog.getOpenFileName( self, 'QFileDialog.getOpenFileName()', '', 'Images (*.png *.jpeg *.jpg *.bmp *.gif)') self.choice_image_path = file_name[0] self.original_image_viewer.set_image(self.choice_image_path) self.original_image_viewer.show() def global_threshold(self): if len(self.choice_image_path) == 0: QtWidgets.QMessageBox.question( self, "Warning", "Please press \"Open\" button to choose a image", QtWidgets.QMessageBox.Ok) return directory, name = ntpath.split(self.choice_image_path) img = cv2.imread(self.choice_image_path) if len(img.shape) > 2: img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # threshold image with the fix value ret, thresh = cv2.threshold(img, self.THRESHOLD_VALUE, 255, cv2.THRESH_BINARY) self.global_threshold_image = thresh # save image for showing saved_path = self.global_dir + '\\' + name self.global_threshold_path = saved_path cv2.imwrite(saved_path, thresh) # show global threshold image self.global_image_viewer.set_image(saved_path) self.global_image_viewer.setWindowTitle("Global Threshold") self.global_image_viewer.show() def rotate(self): if len(self.morphology_image_path) == 0: QtWidgets.QMessageBox.question(self, "Warning", "Please morphology image before", QtWidgets.QMessageBox.Ok) return # get the image for rotation img = self.morphology_image # resize image to standard size dim = (self.RESIZED_WIDTH, self.RESIZED_HEIGHT) img = cv2.resize(img, dim, interpolation=cv2.INTER_AREA) # find marked point in top left and right of the image # get top left area left = img[0:self.AREA_SIZE, 0:self.AREA_SIZE] # get top right area right = img[0:self.AREA_SIZE, self.RESIZED_WIDTH - self.AREA_SIZE:self.RESIZED_WIDTH] # find mark point in area left_x, left_y, min_left = find_interested_point(left) right_x, right_y, min_right = find_interested_point(right) right_x = self.RESIZED_WIDTH - self.AREA_SIZE + right_x # calculate angle for rotation # left's mark point is center for rotation dis_y = right_y - left_y dis_x = right_x - left_x tan_alpha = dis_y / dis_x alpha_rad = np.arctan(tan_alpha) alpha_deg = np.rad2deg(alpha_rad) # calculate top right mark point after rotation self.mark_x = int( math.cos(alpha_rad) * (right_x - left_x) - math.sin(alpha_rad) * (right_y - left_y) + left_x) self.mark_y = int(-math.sin(alpha_rad) * (right_x - left_x) + math.cos(alpha_rad) * (right_y - left_y) + left_y) # rotate image m = cv2.getRotationMatrix2D((left_x, left_y), alpha_deg, 1) rotated = cv2.warpAffine(img, m, dim) # save rotation image self.rotated_image = rotated # get the directory path and file name # file name used for save processed image directory, name = ntpath.split(self.morphology_image_path) # save rotated image and show it to the window saved_path = self.rotate_dir + '\\' + name self.rotated_image_path = saved_path cv2.imwrite(saved_path, rotated) self.rotate_image_viewer.set_image(saved_path) self.rotate_image_viewer.setWindowTitle("Rotated Image") self.rotate_image_viewer.show() def local_threshold(self): if len(self.choice_image_path) == 0: QtWidgets.QMessageBox.question( self, "Warning", "Please press \"Open\" button to choose a image", QtWidgets.QMessageBox.Ok) return image = cv2.imread(self.choice_image_path) if len(image.shape) > 2: image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) id_part = image[200:700, 1100:self.RESIZED_WIDTH] answer_part = image[1000:self.RESIZED_HEIGHT, 0:self.RESIZED_WIDTH] id_thresh_val, id_threshold = cv2.threshold( id_part, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU) answer_thresh_val, answer_threshold = cv2.threshold( answer_part, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU) threshold_val = max(id_thresh_val, answer_thresh_val) ret, thresh = cv2.threshold(image, threshold_val, 255, cv2.THRESH_BINARY) self.local_threshold_image = thresh directory, name = ntpath.split(self.choice_image_path) saved_path = self.local_dir + '\\' + name cv2.imwrite(saved_path, thresh) self.local_image_viewer.set_image(saved_path) self.local_image_viewer.setWindowTitle("Local Threshold") self.local_image_viewer.show() def morphology(self): if len(self.global_threshold_path) == 0: QtWidgets.QMessageBox.question(self, "Warning", "Please global threshold before", QtWidgets.QMessageBox.Ok) return binary_image = self.global_threshold_image invert_img = cv2.bitwise_not(binary_image) opening_kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (7, 7)) opening = cv2.morphologyEx(invert_img, cv2.MORPH_OPEN, opening_kernel) closing_kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (7, 7)) closing = cv2.morphologyEx(opening, cv2.MORPH_CLOSE, closing_kernel) dilation_kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (5, 5)) morphology_image = cv2.dilate(closing, dilation_kernel, iterations=1) morphology_image = cv2.bitwise_not(morphology_image) self.morphology_image = morphology_image directory, name = ntpath.split(self.global_threshold_path) saved_path = self.morphology_dir + '\\' + name self.morphology_image_path = saved_path cv2.imwrite(saved_path, morphology_image) self.morphology_image_viewer.set_image(saved_path) self.morphology_image_viewer.setWindowTitle("Morphology Image") self.morphology_image_viewer.show() def closeEvent(self, event): widget_list = QtWidgets.QApplication.topLevelWidgets() num_windows = len(widget_list) if num_windows > 1: event.accept() else: event.ignore()
def __init__(self, data_dir, deps_dir, output_dir): print("Constructing Image Analyzer") self.warehouse = ImageWarehouse(data_dir, deps_dir) self.viewer = ImageViewer(output_dir)
def __init__(self): super().__init__() self.image_viewer = ImageViewer()
def initUI(self): self.setWindowTitle('Test Parameters') scriptDir = os.getcwd() self.setWindowIcon( QtGui.QIcon(scriptDir + os.path.sep + 'face_icon.ico')) self.setAttribute(QtCore.Qt.WA_DeleteOnClose) self.setWindowFlags(self.windowFlags() | QtCore.Qt.WindowSystemMenuHint | QtCore.Qt.WindowMinMaxButtonsHint) # # self._scene = QtWidgets.QGraphicsScene() # self._scene.setSceneRect(0, 0, 600,800) # self._photo = QtWidgets.QGraphicsPixmapItem() # self._scene.addItem(self._photo) # # self.view = QtWidgets.QGraphicsView(self) # self.view.setScene(self._scene) # #self.view.setRenderHint(QtGui.QPainter.Antialiasing) # #self.view.setFrameShape(QtWidgets.QFrame.NoFrame) # # #self.view.setFocusPolicy(QtCore.Qt.NoFocus) # color = self.palette().color(QtGui.QPalette.Background) # self.view.setBackgroundBrush(color) # # # self.view.setTransformationAnchor(QtWidgets.QGraphicsView.AnchorUnderMouse) # self.view.setResizeAnchor(QtWidgets.QGraphicsView.AnchorUnderMouse) # self.view.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff) # self.view.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff) self.spacerh = QtWidgets.QWidget(self) self.spacerh.setFixedSize(20, 0) self.spacerv = QtWidgets.QWidget(self) self.spacerv.setFixedSize(0, 5) #Top part newfont = QtGui.QFont("Times", 12) self.label1 = QLabel('Frames to Analyze:') self.label1.setFont(newfont) self.label1.setFixedWidth(250) self._FramestoAnalizeInitEdit = QLineEdit(self) self._FramestoAnalizeInitEdit.setText(str(self._InitFrame)) self._FramestoAnalizeInitEdit.setFont(newfont) self._FramestoAnalizeInitEdit.setFixedWidth(75) validator = QtGui.QIntValidator(1, len(self._FileList)) self._FramestoAnalizeInitEdit.setValidator(validator) self._FramestoAnalizeEndEdit = QLineEdit(self) self._FramestoAnalizeEndEdit.setText(str(self._EndFrame)) self._FramestoAnalizeEndEdit.setFont(newfont) self._FramestoAnalizeEndEdit.setFixedWidth(75) validator = QtGui.QIntValidator(1, len(self._FileList)) self._FramestoAnalizeEndEdit.setValidator(validator) self.label2 = QLabel('Side To Analyze') self.label2.setFont(newfont) self.label2.setFixedWidth(250) self._check_right = QCheckBox('Right') self._check_right.setFont(newfont) self._check_right.setChecked(True) self._check_right.setFixedWidth(70) self._check_left = QCheckBox('Left') self._check_left.setFont(newfont) self._check_left.setChecked(False) self._check_left.setFixedWidth(70) self._CheckButtonGroup = QtWidgets.QButtonGroup(self) self._CheckButtonGroup.addButton(self._check_right, 1) self._CheckButtonGroup.addButton(self._check_left, 2) self.label3 = QLabel('Angular Range') self.label3.setFont(newfont) self.label3.setFixedWidth(250) self._AnglesInitEdit = QLineEdit(self) self._AnglesInitEdit.setText(str(self._minAngle)) self._AnglesInitEdit.setFont(newfont) self._AnglesInitEdit.setFixedWidth(70) validator = QtGui.QDoubleValidator(-100, 100, 3) self._AnglesInitEdit.setValidator(validator) self._AnglesEndEdit = QLineEdit(self) self._AnglesEndEdit.setText(str(self._maxAngle)) self._AnglesEndEdit.setFont(newfont) self._AnglesEndEdit.setFixedWidth(70) validator = QtGui.QDoubleValidator(-100, 100, 3) self._AnglesEndEdit.setValidator(validator) self.label4 = QLabel('Number of Angles to Analyze') self.label4.setFont(newfont) self.label4.setFixedWidth(250) self._spinAngles = QSpinBox() self._spinAngles.setMinimum(1) self._spinAngles.setMaximum(1000) self._spinAngles.setFont(newfont) self._spinAngles.setValue(self._NumAngles) self._spinAngles.setFixedWidth(150) TopLayout = QtWidgets.QGridLayout() TopLayout.addWidget(self.label1, 0, 0) TopLayout.addWidget(self._FramestoAnalizeInitEdit, 0, 2) TopLayout.addWidget(self._FramestoAnalizeEndEdit, 0, 3) TopLayout.addWidget(self.label2, 1, 0) TopLayout.addWidget(self._check_right, 1, 2) TopLayout.addWidget(self._check_left, 1, 3) TopLayout.addWidget(self.label3, 2, 0) TopLayout.addWidget(self._AnglesInitEdit, 2, 2) TopLayout.addWidget(self._AnglesEndEdit, 2, 3) TopLayout.addWidget(self.label4, 3, 0) TopLayout.addWidget(self._spinAngles, 3, 2, 1, 2) #buttons DoneButton = QPushButton('&Start', self) DoneButton.setFixedWidth(75) DoneButton.setFont(newfont) DoneButton.clicked.connect(self.Start) CancelButton = QPushButton('&Close', self) CancelButton.setFixedWidth(75) CancelButton.setFont(newfont) CancelButton.clicked.connect(self.Cancel) buttonLayout = QtWidgets.QHBoxLayout() buttonLayout.addWidget(DoneButton) buttonLayout.addWidget(CancelButton) #button part self.label5 = QLabel('Angle') self.label5.setFont(newfont) #self.label5.setFixedWidth(250) self.label5.setAlignment(QtCore.Qt.AlignCenter) #angle change self._left_Angle_button = QToolButton() self._left_Angle_button.setArrowType(QtCore.Qt.LeftArrow) self._left_Angle_button.setFont(newfont) self._left_Angle_button.setFixedWidth(75) self._left_Angle_button.setEnabled(False) self._left_Angle_button.clicked.connect(self.AngleChange_Left) self._right_Angle_button = QToolButton() self._right_Angle_button.setArrowType(QtCore.Qt.RightArrow) self._right_Angle_button.setFont(newfont) self._right_Angle_button.setFixedWidth(75) self._right_Angle_button.setEnabled(False) self._right_Angle_button.clicked.connect(self.AngleChange_Right) self._Angle = QLineEdit(self) self._Angle.setText(str(self._angle)) self._Angle.setFont(newfont) self._Angle.setFixedWidth(150) validator = QtGui.QDoubleValidator(self._minAngle, self._maxAngle, 3) self._Angle.setValidator(validator) self._Angle.setAlignment(QtCore.Qt.AlignCenter) self._Angle.setEnabled(False) self._Angle.textChanged.connect(self.AngleChange) AngleLayout = QtWidgets.QHBoxLayout() AngleLayout.addWidget(self._left_Angle_button) AngleLayout.addWidget(self._Angle) AngleLayout.addWidget(self._right_Angle_button) #Threshold change self.label6 = QLabel('Threshold') self.label6.setFont(newfont) #self.label5.setFixedWidth(250) self.label6.setAlignment(QtCore.Qt.AlignCenter) self._left_Threshold_button = QToolButton() self._left_Threshold_button.setArrowType(QtCore.Qt.LeftArrow) self._left_Threshold_button.setFont(newfont) self._left_Threshold_button.setFixedWidth(75) self._left_Threshold_button.setEnabled(False) self._left_Threshold_button.clicked.connect(self.ThresholdChange_Left) self._right_Threshold_button = QToolButton() self._right_Threshold_button.setArrowType(QtCore.Qt.RightArrow) self._right_Threshold_button.setFont(newfont) self._right_Threshold_button.setFixedWidth(75) self._right_Threshold_button.setEnabled(False) self._right_Threshold_button.clicked.connect( self.ThresholdChange_Right) self._Threshold = QLineEdit(self) self._Threshold.setText(str(self._threshold)) self._Threshold.setFont(newfont) self._Threshold.setFixedWidth(150) validator = QtGui.QIntValidator(0, 255) self._Threshold.setValidator(validator) self._Threshold.setAlignment(QtCore.Qt.AlignCenter) self._Threshold.setEnabled(False) self._Threshold.textChanged.connect(self.ThresholdChange) ThresholdLayout = QtWidgets.QHBoxLayout() ThresholdLayout.addWidget(self._left_Threshold_button) ThresholdLayout.addWidget(self._Threshold) ThresholdLayout.addWidget(self._right_Threshold_button) #Threshold change self.label7 = QLabel('Rotation') self.label7.setFont(newfont) #self.label5.setFixedWidth(250) self.label7.setAlignment(QtCore.Qt.AlignCenter) self._left_Rotation_button = QToolButton() self._left_Rotation_button.setArrowType(QtCore.Qt.LeftArrow) self._left_Rotation_button.setFont(newfont) self._left_Rotation_button.setFixedWidth(75) self._left_Rotation_button.setEnabled(False) self._left_Rotation_button.clicked.connect(self.RotationChange_Left) self._right_Rotation_button = QToolButton() self._right_Rotation_button.setArrowType(QtCore.Qt.RightArrow) self._right_Rotation_button.setFont(newfont) self._right_Rotation_button.setFixedWidth(75) self._right_Rotation_button.setEnabled(False) self._right_Rotation_button.clicked.connect(self.RotationChange_Right) self._Rotation = QLineEdit(self) self._Rotation.setText(str(self._rotation)) self._Rotation.setFont(newfont) self._Rotation.setFixedWidth(150) validator = QtGui.QDoubleValidator(-15, 15, 3) self._Rotation.setValidator(validator) self._Rotation.setAlignment(QtCore.Qt.AlignCenter) self._Rotation.setEnabled(False) self._Rotation.textChanged.connect(self.RotationChange) RotationLayout = QtWidgets.QHBoxLayout() RotationLayout.addWidget(self._left_Rotation_button) RotationLayout.addWidget(self._Rotation) RotationLayout.addWidget(self._right_Rotation_button) #Estimated Correlation self.label8 = QLabel('Estimated Correlation') self.label8.setFont(newfont) #self.label5.setFixedWidth(250) self.label8.setAlignment(QtCore.Qt.AlignCenter) self._Correlation = QPlainTextEdit(self) self._Correlation.clear() self._Correlation.setPlainText(str(0)) self._Correlation.setFont(newfont) self._Correlation.setFixedWidth(250) self._Correlation.setFixedHeight(30) #validator = QtGui.QDoubleValidator(-1, 1,5) #self._Correlation.setValidator(validator) #self._Correlation.setAlignment(QtCore.Qt.AlignCenter) self._Correlation.setEnabled(False) self._Correlation.setReadOnly(True) CorrelationLayout = QtWidgets.QHBoxLayout() #CorrelationLayout.addWidget(self._left_Threshold_button) CorrelationLayout.addWidget(self._Correlation) #CorrelationLayout.addWidget(self._right_Threshold_button) ViewLayout = QtWidgets.QHBoxLayout() self.displayImage = ImageViewer() color = self.palette().color(QtGui.QPalette.Background) self.displayImage.setBackgroundBrush(color) ViewLayout.addWidget(self.displayImage) layout = QtWidgets.QVBoxLayout() layout.addLayout(TopLayout) layout.addLayout(buttonLayout) #layout.addWidget(self.view) layout.addLayout(ViewLayout) layout.addWidget(self.label5) layout.addLayout(AngleLayout) layout.addWidget(self.label6) layout.addLayout(ThresholdLayout) layout.addWidget(self.label7) layout.addLayout(RotationLayout) layout.addWidget(self.label8) layout.addLayout(CorrelationLayout) self.setLayout(layout) #fix the size, the user cannot change it #self.resize(self.sizeHint()) #self.setFixedSize(self.size()) self.setGeometry(300, 300, 400, 800) self.show()
from tkinter import * # Import tkinter from ImageViewer import ImageViewer window = Tk() # Create a window window.title("Six Flags") # Set title imageViewer = ImageViewer(window, "img/ca.gif", 90, 50, 400, 200) # Create a clock window.mainloop() # Create an event loop
class TestWindow(QDialog): def __init__(self, FileList=None, Folder=None, RightROI=None, LeftROI=None, FaceCenter=None): super(TestWindow, self).__init__() # self._scene = QtWidgets.QGraphicsScene(self) # self.setScene(self._scene) # FileList = ['Basler acA800-510uc (22501173)_20171212_190308266_0001.tiff', 'Basler acA800-510uc (22501173)_20171212_190308266_0002.tiff', 'Basler acA800-510uc (22501173)_20171212_190308266_0003.tiff', 'Basler acA800-510uc (22501173)_20171212_190308266_0004.tiff', 'Basler acA800-510uc (22501173)_20171212_190308266_0005.tiff', 'Basler acA800-510uc (22501173)_20171212_190308266_0006.tiff', 'Basler acA800-510uc (22501173)_20171212_190308266_0007.tiff', 'Basler acA800-510uc (22501173)_20171212_190308266_0008.tiff', 'Basler acA800-510uc (22501173)_20171212_190308266_0009.tiff', 'Basler acA800-510uc (22501173)_20171212_190308266_0010.tiff'] # Folder = r'C:/Users/GUARIND/Videos/Basler/test3' # RightROI = np.array([[368,387],[324,329],[299,261],[230,157],[196,78],[ 21,77],[16,581],[373,585]]) # LeftROI = np.array([[440,387],[484,329],[509,261],[578,157],[612,78],[787,77],[792,581],[435,585]]) # FaceCenter = np.array([404,302]) self._Folder = Folder self._FileList = FileList self._InitFrame = 1 self._EndFrame = self._InitFrame + 1 #len(self._List) self._NumAngles = 50 self._minAngle = -3.5 self._maxAngle = 3.5 self._FaceCenter = FaceCenter self._RightROI = RightROI self._LeftROI = LeftROI self._ImageUno = None self._ImageDos = None self._angles = None #all avaliable angles self._angle = 0 #current angle to analize self._angle_index = 0 #index of current angle self._threshold = 255 #threshold value self._rotation = 0 #rotation value self._AnalizeSide = None self.initUI() def initUI(self): self.setWindowTitle('Test Parameters') scriptDir = os.getcwd() self.setWindowIcon( QtGui.QIcon(scriptDir + os.path.sep + 'face_icon.ico')) self.setAttribute(QtCore.Qt.WA_DeleteOnClose) self.setWindowFlags(self.windowFlags() | QtCore.Qt.WindowSystemMenuHint | QtCore.Qt.WindowMinMaxButtonsHint) # # self._scene = QtWidgets.QGraphicsScene() # self._scene.setSceneRect(0, 0, 600,800) # self._photo = QtWidgets.QGraphicsPixmapItem() # self._scene.addItem(self._photo) # # self.view = QtWidgets.QGraphicsView(self) # self.view.setScene(self._scene) # #self.view.setRenderHint(QtGui.QPainter.Antialiasing) # #self.view.setFrameShape(QtWidgets.QFrame.NoFrame) # # #self.view.setFocusPolicy(QtCore.Qt.NoFocus) # color = self.palette().color(QtGui.QPalette.Background) # self.view.setBackgroundBrush(color) # # # self.view.setTransformationAnchor(QtWidgets.QGraphicsView.AnchorUnderMouse) # self.view.setResizeAnchor(QtWidgets.QGraphicsView.AnchorUnderMouse) # self.view.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff) # self.view.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff) self.spacerh = QtWidgets.QWidget(self) self.spacerh.setFixedSize(20, 0) self.spacerv = QtWidgets.QWidget(self) self.spacerv.setFixedSize(0, 5) #Top part newfont = QtGui.QFont("Times", 12) self.label1 = QLabel('Frames to Analyze:') self.label1.setFont(newfont) self.label1.setFixedWidth(250) self._FramestoAnalizeInitEdit = QLineEdit(self) self._FramestoAnalizeInitEdit.setText(str(self._InitFrame)) self._FramestoAnalizeInitEdit.setFont(newfont) self._FramestoAnalizeInitEdit.setFixedWidth(75) validator = QtGui.QIntValidator(1, len(self._FileList)) self._FramestoAnalizeInitEdit.setValidator(validator) self._FramestoAnalizeEndEdit = QLineEdit(self) self._FramestoAnalizeEndEdit.setText(str(self._EndFrame)) self._FramestoAnalizeEndEdit.setFont(newfont) self._FramestoAnalizeEndEdit.setFixedWidth(75) validator = QtGui.QIntValidator(1, len(self._FileList)) self._FramestoAnalizeEndEdit.setValidator(validator) self.label2 = QLabel('Side To Analyze') self.label2.setFont(newfont) self.label2.setFixedWidth(250) self._check_right = QCheckBox('Right') self._check_right.setFont(newfont) self._check_right.setChecked(True) self._check_right.setFixedWidth(70) self._check_left = QCheckBox('Left') self._check_left.setFont(newfont) self._check_left.setChecked(False) self._check_left.setFixedWidth(70) self._CheckButtonGroup = QtWidgets.QButtonGroup(self) self._CheckButtonGroup.addButton(self._check_right, 1) self._CheckButtonGroup.addButton(self._check_left, 2) self.label3 = QLabel('Angular Range') self.label3.setFont(newfont) self.label3.setFixedWidth(250) self._AnglesInitEdit = QLineEdit(self) self._AnglesInitEdit.setText(str(self._minAngle)) self._AnglesInitEdit.setFont(newfont) self._AnglesInitEdit.setFixedWidth(70) validator = QtGui.QDoubleValidator(-100, 100, 3) self._AnglesInitEdit.setValidator(validator) self._AnglesEndEdit = QLineEdit(self) self._AnglesEndEdit.setText(str(self._maxAngle)) self._AnglesEndEdit.setFont(newfont) self._AnglesEndEdit.setFixedWidth(70) validator = QtGui.QDoubleValidator(-100, 100, 3) self._AnglesEndEdit.setValidator(validator) self.label4 = QLabel('Number of Angles to Analyze') self.label4.setFont(newfont) self.label4.setFixedWidth(250) self._spinAngles = QSpinBox() self._spinAngles.setMinimum(1) self._spinAngles.setMaximum(1000) self._spinAngles.setFont(newfont) self._spinAngles.setValue(self._NumAngles) self._spinAngles.setFixedWidth(150) TopLayout = QtWidgets.QGridLayout() TopLayout.addWidget(self.label1, 0, 0) TopLayout.addWidget(self._FramestoAnalizeInitEdit, 0, 2) TopLayout.addWidget(self._FramestoAnalizeEndEdit, 0, 3) TopLayout.addWidget(self.label2, 1, 0) TopLayout.addWidget(self._check_right, 1, 2) TopLayout.addWidget(self._check_left, 1, 3) TopLayout.addWidget(self.label3, 2, 0) TopLayout.addWidget(self._AnglesInitEdit, 2, 2) TopLayout.addWidget(self._AnglesEndEdit, 2, 3) TopLayout.addWidget(self.label4, 3, 0) TopLayout.addWidget(self._spinAngles, 3, 2, 1, 2) #buttons DoneButton = QPushButton('&Start', self) DoneButton.setFixedWidth(75) DoneButton.setFont(newfont) DoneButton.clicked.connect(self.Start) CancelButton = QPushButton('&Close', self) CancelButton.setFixedWidth(75) CancelButton.setFont(newfont) CancelButton.clicked.connect(self.Cancel) buttonLayout = QtWidgets.QHBoxLayout() buttonLayout.addWidget(DoneButton) buttonLayout.addWidget(CancelButton) #button part self.label5 = QLabel('Angle') self.label5.setFont(newfont) #self.label5.setFixedWidth(250) self.label5.setAlignment(QtCore.Qt.AlignCenter) #angle change self._left_Angle_button = QToolButton() self._left_Angle_button.setArrowType(QtCore.Qt.LeftArrow) self._left_Angle_button.setFont(newfont) self._left_Angle_button.setFixedWidth(75) self._left_Angle_button.setEnabled(False) self._left_Angle_button.clicked.connect(self.AngleChange_Left) self._right_Angle_button = QToolButton() self._right_Angle_button.setArrowType(QtCore.Qt.RightArrow) self._right_Angle_button.setFont(newfont) self._right_Angle_button.setFixedWidth(75) self._right_Angle_button.setEnabled(False) self._right_Angle_button.clicked.connect(self.AngleChange_Right) self._Angle = QLineEdit(self) self._Angle.setText(str(self._angle)) self._Angle.setFont(newfont) self._Angle.setFixedWidth(150) validator = QtGui.QDoubleValidator(self._minAngle, self._maxAngle, 3) self._Angle.setValidator(validator) self._Angle.setAlignment(QtCore.Qt.AlignCenter) self._Angle.setEnabled(False) self._Angle.textChanged.connect(self.AngleChange) AngleLayout = QtWidgets.QHBoxLayout() AngleLayout.addWidget(self._left_Angle_button) AngleLayout.addWidget(self._Angle) AngleLayout.addWidget(self._right_Angle_button) #Threshold change self.label6 = QLabel('Threshold') self.label6.setFont(newfont) #self.label5.setFixedWidth(250) self.label6.setAlignment(QtCore.Qt.AlignCenter) self._left_Threshold_button = QToolButton() self._left_Threshold_button.setArrowType(QtCore.Qt.LeftArrow) self._left_Threshold_button.setFont(newfont) self._left_Threshold_button.setFixedWidth(75) self._left_Threshold_button.setEnabled(False) self._left_Threshold_button.clicked.connect(self.ThresholdChange_Left) self._right_Threshold_button = QToolButton() self._right_Threshold_button.setArrowType(QtCore.Qt.RightArrow) self._right_Threshold_button.setFont(newfont) self._right_Threshold_button.setFixedWidth(75) self._right_Threshold_button.setEnabled(False) self._right_Threshold_button.clicked.connect( self.ThresholdChange_Right) self._Threshold = QLineEdit(self) self._Threshold.setText(str(self._threshold)) self._Threshold.setFont(newfont) self._Threshold.setFixedWidth(150) validator = QtGui.QIntValidator(0, 255) self._Threshold.setValidator(validator) self._Threshold.setAlignment(QtCore.Qt.AlignCenter) self._Threshold.setEnabled(False) self._Threshold.textChanged.connect(self.ThresholdChange) ThresholdLayout = QtWidgets.QHBoxLayout() ThresholdLayout.addWidget(self._left_Threshold_button) ThresholdLayout.addWidget(self._Threshold) ThresholdLayout.addWidget(self._right_Threshold_button) #Threshold change self.label7 = QLabel('Rotation') self.label7.setFont(newfont) #self.label5.setFixedWidth(250) self.label7.setAlignment(QtCore.Qt.AlignCenter) self._left_Rotation_button = QToolButton() self._left_Rotation_button.setArrowType(QtCore.Qt.LeftArrow) self._left_Rotation_button.setFont(newfont) self._left_Rotation_button.setFixedWidth(75) self._left_Rotation_button.setEnabled(False) self._left_Rotation_button.clicked.connect(self.RotationChange_Left) self._right_Rotation_button = QToolButton() self._right_Rotation_button.setArrowType(QtCore.Qt.RightArrow) self._right_Rotation_button.setFont(newfont) self._right_Rotation_button.setFixedWidth(75) self._right_Rotation_button.setEnabled(False) self._right_Rotation_button.clicked.connect(self.RotationChange_Right) self._Rotation = QLineEdit(self) self._Rotation.setText(str(self._rotation)) self._Rotation.setFont(newfont) self._Rotation.setFixedWidth(150) validator = QtGui.QDoubleValidator(-15, 15, 3) self._Rotation.setValidator(validator) self._Rotation.setAlignment(QtCore.Qt.AlignCenter) self._Rotation.setEnabled(False) self._Rotation.textChanged.connect(self.RotationChange) RotationLayout = QtWidgets.QHBoxLayout() RotationLayout.addWidget(self._left_Rotation_button) RotationLayout.addWidget(self._Rotation) RotationLayout.addWidget(self._right_Rotation_button) #Estimated Correlation self.label8 = QLabel('Estimated Correlation') self.label8.setFont(newfont) #self.label5.setFixedWidth(250) self.label8.setAlignment(QtCore.Qt.AlignCenter) self._Correlation = QPlainTextEdit(self) self._Correlation.clear() self._Correlation.setPlainText(str(0)) self._Correlation.setFont(newfont) self._Correlation.setFixedWidth(250) self._Correlation.setFixedHeight(30) #validator = QtGui.QDoubleValidator(-1, 1,5) #self._Correlation.setValidator(validator) #self._Correlation.setAlignment(QtCore.Qt.AlignCenter) self._Correlation.setEnabled(False) self._Correlation.setReadOnly(True) CorrelationLayout = QtWidgets.QHBoxLayout() #CorrelationLayout.addWidget(self._left_Threshold_button) CorrelationLayout.addWidget(self._Correlation) #CorrelationLayout.addWidget(self._right_Threshold_button) ViewLayout = QtWidgets.QHBoxLayout() self.displayImage = ImageViewer() color = self.palette().color(QtGui.QPalette.Background) self.displayImage.setBackgroundBrush(color) ViewLayout.addWidget(self.displayImage) layout = QtWidgets.QVBoxLayout() layout.addLayout(TopLayout) layout.addLayout(buttonLayout) #layout.addWidget(self.view) layout.addLayout(ViewLayout) layout.addWidget(self.label5) layout.addLayout(AngleLayout) layout.addWidget(self.label6) layout.addLayout(ThresholdLayout) layout.addWidget(self.label7) layout.addLayout(RotationLayout) layout.addWidget(self.label8) layout.addLayout(CorrelationLayout) self.setLayout(layout) #fix the size, the user cannot change it #self.resize(self.sizeHint()) #self.setFixedSize(self.size()) self.setGeometry(300, 300, 400, 800) self.show() def Start(self): #compute angles value_init = float(self._AnglesInitEdit.text()) value_end = float(self._AnglesEndEdit.text()) if value_end <= value_init: QtWidgets.QMessageBox.warning( self, 'Error', 'Final Angle must be greather than Initial Angle') return # if value_init > 0 : # QtWidgets.QMessageBox.warning(self, 'Error','Initial Angle must be less or equal than zero') # return # # if value_end < 0 : # QtWidgets.QMessageBox.warning(self, 'Error','Final Angle must be greather or equal than zero') # return self._minAngle = value_init self._maxAngle = value_end self._NumAngles = self._spinAngles.value() angles = np.linspace(self._minAngle, self._maxAngle, self._NumAngles) print(self._minAngle * self._maxAngle) #verify that there are positive and negative angles if self._minAngle * self._maxAngle < 0: zero_ind = np.where(angles == 0)[0] if zero_ind.size == 1: pass elif zero_ind.size > 0: QtWidgets.QMessageBox.warning( self, 'Error', 'This is weird. There are more than one zero in the angles to evaluate....' ) return elif zero_ind.size == 0: #add zero to the list of angles sgn_change_ind = np.where(np.diff(np.sign(angles)))[0] angles_neg = angles[:sgn_change_ind[0] + 1] angles_pos = angles[sgn_change_ind[0]:] angles = np.r_[angles_neg, [np.float(0)], angles_pos[1:]] else: QtWidgets.QMessageBox.warning( self, 'Error', 'This is weird. Unknown error with the angles.') return self._angles = np.asarray(angles) self._angle_index = int(np.where(self._angles == 0)[0]) self._angle = self._angles[self._angle_index] self._Angle.setText(str(np.round(self._angle, 5))) else: self._angles = np.asarray(angles) self._angle = 0 self._Angle.setText(str(np.round(self._angle, 5))) #Frames to analize Init_Frame = int(self._FramestoAnalizeInitEdit.text()) if Init_Frame == 0: QtWidgets.QMessageBox.warning( self, 'Error', 'Frame number must be larger than 0') return End_Frame = int(self._FramestoAnalizeEndEdit.text()) if End_Frame == 0: QtWidgets.QMessageBox.warning( self, 'Error', 'Frame number must be larger than 0') return if Init_Frame > End_Frame: QtWidgets.QMessageBox.warning( self, 'Error', 'Initial Frame cannot be larger than Final Frame') return if self._check_right.isChecked(): self._AnalizeSide = 'Right' elif self._check_left.isChecked(): self._AnalizeSide = 'Left' #read images from memory in gray format temp_image = cv2.imread( os.path.join(self._Folder, self._FileList[Init_Frame])) temp_image = cv2.cvtColor(temp_image, cv2.COLOR_BGR2RGB) self._ImageUno = cv2.cvtColor(temp_image, cv2.COLOR_BGR2GRAY) temp_image = cv2.imread( os.path.join(self._Folder, self._FileList[End_Frame])) temp_image = cv2.cvtColor(temp_image, cv2.COLOR_BGR2RGB) self._ImageDos = cv2.cvtColor(temp_image, cv2.COLOR_BGR2GRAY) h_orig, w_orig = self._ImageUno.shape #original shape blended = self.create_blend_image() if self._AnalizeSide == 'Right': ROI = self._RightROI image = blended.copy() image = image[:, 0:self._FaceCenter[0]] #take right side else: ROI = self._LeftROI ROI = ROI - [self._FaceCenter[0], 0] #ROI = [2*self._FaceCenter[0],0]-ROI #mirror the left ROI to the right #ROI[:,1]=abs(ROI[:,1]) #correct the minus sign in the y column image = blended.copy() #image = cv2.flip(image,1) #mirror it image = image[:, self._FaceCenter[0]:-1] #take left side image = image.astype(np.uint8) # cv2.namedWindow("Video", cv2.WINDOW_NORMAL+cv2.WINDOW_KEEPRATIO) # cv2.imshow("Video", image) # cv2.waitKey(0) # cv2.destroyAllWindows() height, width = image.shape bytesPerLine = 1 * width #img_Qt = QtGui.QImage(self._ImageDos.data, width, height, bytesPerLine, QtGui.QImage.Format_RGB888) img_Qt = QtGui.QImage(image.data, width, height, bytesPerLine, QtGui.QImage.Format_Indexed8) img_show = QtGui.QPixmap.fromImage(img_Qt) self.displayImage.setPhoto(img_show) self.displayImage.draw_polygon(ROI) self._left_Angle_button.setEnabled(True) self._right_Angle_button.setEnabled(True) self._Angle.setEnabled(True) self._left_Threshold_button.setEnabled(True) self._right_Threshold_button.setEnabled(True) self._Threshold.setEnabled(True) self._left_Rotation_button.setEnabled(True) self._right_Rotation_button.setEnabled(True) self._Rotation.setEnabled(True) self._Correlation.setEnabled(True) self.ProcessFrames() def create_blend_image(self): h, w = self._ImageUno.shape #rotate both images M = cv2.getRotationMatrix2D((int(w / 2), int(h / 2)), self._rotation, 1.0) imageuno = cv2.warpAffine(self._ImageUno, M, (w, h)) imagedos = cv2.warpAffine(self._ImageDos, M, (w, h)) imageuno[imageuno > self._threshold] = 255 imagedos[imagedos > self._threshold] = 255 blend = cv2.addWeighted(imageuno, 0.5, imagedos, 0.5, 0) return blend #----------------------------------------------- def AngleChange(self): if float(self._Angle.text()) > self._maxAngle: self._angle = self._maxAngle self._Angle.setText(str(np.round(self._angle, 5))) elif float(self._Angle.text()) < self._minAngle: self._angle = self._minAngle self._Angle.setText(str(np.round(self._angle, 5))) self.ProcessFrames() def AngleChange_Right(self): if self._angle_index < len(self._angles) - 1: self._angle_index += 1 self._angle = self._angles[self._angle_index] self._Angle.setText(str(np.round(self._angle, 5))) def AngleChange_Left(self): if self._angle_index > 0: self._angle_index -= 1 self._angle = self._angles[self._angle_index] self._Angle.setText(str(np.round(self._angle, 5))) #----------------------------------------------- def ThresholdChange(self): if int(self._Threshold.text()) > 255: self._threshold = 255 self._Threshold.setText(str(np.round(self._threshold))) elif int(self._Threshold.text()) < 0: self._threshold = 0 self._Threshold.setText(str(np.round(self._threshold))) self.ProcessFrames() def ThresholdChange_Right(self): if self._threshold < 255: self._threshold += 1 self._Threshold.setText(str(np.round(self._threshold))) def ThresholdChange_Left(self): if self._threshold > 0: self._threshold -= 1 self._Threshold.setText(str(np.round(self._threshold))) #----------------------------------------------- def RotationChange(self): if float(self._Rotation.text()) > 15: self._rotation = 15 self._Rotation.setText(str(np.round(self._rotation, 5))) elif float(self._Rotation.text()) < -15: self._rotation = -15 self._Rotation.setText(str(np.round(self._rotation, 5))) self.ProcessFrames() def RotationChange_Right(self): if self._rotation < 15: self._rotation = self._rotation + 0.25 self._Rotation.setText(str(np.round(self._rotation, 5))) def RotationChange_Left(self): if self._rotation > -15: self._rotation = self._rotation - 0.25 self._Rotation.setText(str(np.round(self._rotation, 5))) #--------------------------------------------------------- def ProcessFrames(self): self._rotation = float(self._Rotation.text()) self._angle = float(self._Angle.text()) self._threshold = int(self._Threshold.text()) #apply threshold and rotation and blend both images imageuno = self._ImageUno.copy() imagedos = self._ImageDos.copy() h, w = imageuno.shape #rotation that will be applied to both image M = cv2.getRotationMatrix2D((int(w / 2), int(h / 2)), self._rotation, 1.0) imageuno = cv2.warpAffine(imageuno, M, (w, h)) imagedos = cv2.warpAffine(imagedos, M, (w, h)) imageuno[imageuno > self._threshold] = 255 imagedos[imagedos > self._threshold] = 255 if self._AnalizeSide == 'Right': ROI = self._RightROI imageuno = imageuno[:, 0:self._FaceCenter[0]] #take right side imagedos = imagedos[:, 0:self._FaceCenter[0]] #take right side #rotation that will be applied to second image M_angle = cv2.getRotationMatrix2D(tuple(self._FaceCenter), self._angle, 1) else: ROI = self._LeftROI ROI = ROI - [self._FaceCenter[0], 0] imageuno = imageuno[:, self._FaceCenter[0]:-1] #take left side imagedos = imagedos[:, self._FaceCenter[0]:-1] #take left side M_angle = cv2.getRotationMatrix2D((0, self.FaceCenter[1]), self._angle, 1) #invert image imageuno = cv2.bitwise_not(imageuno) imagedos = cv2.bitwise_not(imagedos) #create the mask that will cover only the whiskers in left and right sides of the face mask = np.zeros(imageuno.shape, np.uint8) cv2.fillConvexPoly(mask, ROI, (255, 255, 255)) tempuno = np.zeros(imageuno.shape, np.uint8) cv2.bitwise_and(imageuno, mask, tempuno) height, width = imageuno.shape imagedos = cv2.warpAffine(imagedos, M_angle, (width, height)) tempdos = np.zeros(imagedos.shape, np.uint8) cv2.bitwise_and(imagedos, mask, tempdos) blended = cv2.addWeighted(imageuno, 0.5, imagedos, 0.5, 0) blended = blended.astype(np.uint8) # cv2.namedWindow("Video", cv2.WINDOW_NORMAL+cv2.WINDOW_KEEPRATIO) # cv2.imshow("Video", blended) # cv2.waitKey(0) # cv2.destroyAllWindows() #height, width = blended.shape blended = cv2.bitwise_not(blended) bytesPerLine = 1 * width #img_Qt = QtGui.QImage(self._ImageDos.data, width, height, bytesPerLine, QtGui.QImage.Format_RGB888) img_Qt = QtGui.QImage(blended.data, width, height, bytesPerLine, QtGui.QImage.Format_Indexed8) img_show = QtGui.QPixmap.fromImage(img_Qt) self.displayImage.setPhoto(img_show) #find the correlation between the previous frame and the rotate version of the current frame correl = cv2.matchTemplate(cv2.resize(tempuno, (0, 0), fx=0.5, fy=0.5), cv2.resize(tempdos, (0, 0), fx=0.5, fy=0.5), cv2.TM_CCORR_NORMED)[0] #show results self._Correlation.setPlainText(str(np.round(correl[0], 5))) def Cancel(self): self.close() def closeEvent(self, event): event.accept()