def handle_drawing(self, pos): if self.current and self.current.reach_max_points() is False: init_pos = self.current[0] target_pos = self.line[1] p1, p2 = calc_extra_points( -1 / (calc_shib(init_pos, target_pos)), init_pos, max_d=calc_distance(init_pos, target_pos) / 2) self.current.add_point(p1) self.current.add_point(target_pos) self.current.add_point(p2) self.finalise() elif not self.out_of_pixmap(pos): self.current = Shape() self.current.add_point(pos) self.line.points = [pos, pos] self.set_hiding() self.drawingPolygon.emit(True) self.update()
def mousePressEvent(self, ev): pos = self.transformPos(ev.pos()) if ev.button() == Qt.LeftButton: if self.drawing(): # self.handleDrawing(pos) # OLD if self.current and self.fourpoint: # ADD IF # Add point to existing shape. print('Adding points in mousePressEvent is ', self.line[1]) self.current.addPoint(self.line[1]) self.line[0] = self.current[-1] if self.current.isClosed(): # print('1111') self.finalise() elif not self.outOfPixmap(pos): # Create new shape. self.current = Shape( ) # self.current = Shape(shape_type=self.createMode) self.current.addPoint(pos) # if self.createMode == "point": # self.finalise() # else: # if self.createMode == "circle": # self.current.shape_type = "circle" self.line.points = [pos, pos] self.setHiding() self.drawingPolygon.emit(True) self.update() else: selection = self.selectShapePoint(pos) self.prevPoint = pos if selection is None: #pan QApplication.setOverrideCursor(QCursor(Qt.OpenHandCursor)) self.pan_initial_pos = pos elif ev.button() == Qt.RightButton and self.editing(): self.selectShapePoint(pos) self.prevPoint = pos self.update()
def handle_drawing(self, pos): if self.current and self.current.reach_max_points() is False: init_pos = self.current[0] min_x = init_pos.x() min_y = init_pos.y() target_pos = self.line[1] max_x = target_pos.x() max_y = target_pos.y() self.current.add_point(QPointF(max_x, min_y)) self.current.add_point(target_pos) self.current.add_point(QPointF(min_x, max_y)) self.finalise() elif not self.out_of_pixmap(pos): self.current = Shape(parent=self.parent().window()) self.current.add_point(pos) self.line.points = [pos, pos] self.set_hiding() self.drawingPolygon.emit(True) self.update()
def handleDrawing(self, pos): if self.current and self.current.reachMaxPoints() is False: initPos = self.current[0] minX = initPos.x() minY = initPos.y() targetPos = self.line[1] maxX = targetPos.x() maxY = targetPos.y() self.current.addPoint(QPointF(maxX, minY)) self.current.addPoint(targetPos) self.current.addPoint(QPointF(minX, maxY)) self.finalise() elif not self.outOfPixmap(pos): self.current = Shape() self.current.addPoint(pos) self.line.points = [pos, pos] self.setHiding() self.drawingPolygon.emit(True) self.update()
def createBox(self, pos=None): if pos is None: pos = self.mousepos if self.quickbox: if not self.outOfPixmap(pos): shape = Shape(label="sugar-beet") dim = self.box_size / 2 x = pos.x() y = pos.y() points = ((x - dim, y - dim), (x + dim, y - dim), (x + dim, y + dim), (x - dim, y + dim)) for p in points: shape.addPoint(QPointF(*p)) shape.close() self.shapes.append(shape) self.boxCreated.emit() return True return False
def set_detect_shape(self, relative_point, shape_points): #self.selectedShape = self.current #self.deleteSelected() print('relative pt : ', relative_point) self.current = Shape() self.current.shapeType = 1 print(len(shape_points)) shape_points.sort(key=lambda tup: tup[0]) for pt in shape_points: self.current.addPoint( QPointF(relative_point[0] + pt[0], relative_point[1] + pt[1])) #self.current.close() self.shapes.append(self.current) self.current = None self.setHiding(False) self.drawingPolygon.emit(False) self.update()
def handlePoint(self, pos): if not self.outOfPixmap(pos): # initPos = self.current[0] # minX = initPos.x() # minY = initPos.y() # targetPos = self.line[1] # maxX = targetPos.x() # maxY = targetPos.y() # self.current.addPoint(QPointF(maxX, minY)) # self.current.addPoint(targetPos) # self.current.addPoint(QPointF(minX, maxY)) # self.finalisePolygon() # todo---> self.current = Shape() self.current.addPoint(pos) self.current.addPoint(pos) self.setHiding() self.drawingPolygon.emit(True) self.update() self.finalisePoint()
def __init__(self, *args, **kwargs): super(Canvas, self).__init__(*args, **kwargs) # Initialise local state. self.mode = self.EDIT self.shapes = [] self.shapesBackups = [] self.current = None # self.currentShapeType = shapeTypes.shape # newly added self.shapeFactory = shapeFactory() self.selectedShape = None # save the selected shape here self.selectedShapeCopy = None self.drawingLineColor = QColor(0, 0, 255) self.drawingRectColor = QColor(0, 0, 255) # self.line represents: # - createMode == 'polygon': edge from last point to current # - createMode == 'rectangle': diagonal line of the rectangle # - createMode == 'line': the line # - createMode == 'point': the point # - createMode == 'ellipse': edge from last point to current self.line = Shape(line_color=self.drawingLineColor) self.prevPoint = QPointF() self.prevMovePoint = QPoint() # newly added self.offsets = QPointF(), QPointF() self.scale = 1.0 self.pixmap = QPixmap() self.visible = {} self._hideBackround = False self.hideBackround = False self.hShape = None self.hVertex = None self.hEdge = None # newly added self.movingShape = False # newly added self._painter = QPainter() self._cursor = CURSOR_DEFAULT # Menus: self.menus = (QMenu(), QMenu()) # Set widget options. self.setMouseTracking(True) # allow mouseMoveEvent() self.setFocusPolicy(Qt.WheelFocus) self.verified = False
def handleDrawing(self, pos): if self.current: if not self.current.isEllipse: if not self.current.reachMaxPoints(): initPos = self.current[0] minX = initPos.x() minY = initPos.y() targetPos = self.line[1] maxX = targetPos.x() maxY = targetPos.y() self.current.addPoint( QPointF(maxX, minY), self.transformToLatLon(QPointF(maxX, minY), True)) self.current.addPoint( targetPos, self.transformToLatLon(targetPos, True)) self.current.addPoint( QPointF(minX, maxY), self.transformToLatLon(QPointF(minX, maxY), True)) # self.finalise() else: self.current.addPoint(pos, self.transformToLatLon(pos, True)) if len(self.current) == 3: self.current.close() self.finalise() elif not self.outOfPixmap(pos): self.current = Shape(parent_canvas=self) # mk self.current.isEllipse = True self.current.addPoint(pos, self.transformToLatLon(pos, True)) if not self.current.isEllipse: self.line.points = [pos, pos] self.setHiding() self.drawingPolygon.emit(True) self.recalculateMovedLatlonPointsSelectedShape() self.update()
def __init__(self, *args, **kwargs): super(Canvas, self).__init__(*args, **kwargs) # Initialise local state. self.mode = self.EDIT self.shapes = [] self.current = None self.selectedShape = None # save the selected shape here self.selectedShapeCopy = None self.drawingLineColor = QColor(0, 0, 255) self.drawingRectColor = QColor(0, 0, 255) self.line = Shape(line_color=self.drawingLineColor) self.prevPoint = QPointF() self.offsets = QPointF(), QPointF() self.scale = 1.0 self.labelFontSize = 8 self.pixmap = QPixmap() self.visible = {} self._hideBackround = False self.hideBackround = False self.hShape = None self.hVertex = None self._painter = QPainter() self._cursor = CURSOR_DEFAULT # Draw options self.forceFill = False self.hideVertices = False self.opaqueFill = False # Menus: self.menus = (QMenu(), QMenu()) # Set widget options. self.setMouseTracking(True) self.setFocusPolicy(Qt.WheelFocus) self.verified = False self.drawSquare = False # initialisation for panning self.pan_initial_pos = QPoint()
def loadParams(self): try: params = load_from_json("params/param.json") shapes = params["shapes"] for sh in shapes: index, label, r = sh["id"], sh["label"], sh["rect"] generate_color = generateColorByText(label) shape = Shape(label=label, line_color=generate_color, paintLabel=True) # shape.fill = True shape.fill_color = generate_color shape.points = 4 * [QPoint()] shape.points[0] = QPointF(r[0], r[1]) shape.points[1] = QPointF(r[0] + r[2], r[1]) shape.points[2] = QPointF(r[0] + r[2], r[1] + r[3]) shape.points[3] = QPointF(r[0], r[1] + r[3]) shape.close() self.canvas.shapes.append(shape) self.addLabel(shape) except: pass
def loadLabels(self, shapes): s = [] for label, points, line_color, fill_color, difficult in shapes: shape = Shape(label=label) for x, y in points: shape.addPoint(QPointF(x, y)) shape.difficult = difficult shape.close() s.append(shape) self.addLabel(shape) if line_color: shape.line_color = QColor(*line_color) if fill_color: shape.fill_color = QColor(*fill_color) self.canvas.loadShapes(s)
def mousePressEvent(self, ev): pos = self.transformPos(ev.pos()) if ev.button() == Qt.LeftButton: if self.drawing(): if self.shape_type == self.POLYGON_SHAPE and self.current: self.current.addPoint(self.line[1]) self.line[0] = self.current[-1] if self.current.isClosed(): self.finalise() elif self.shape_type == self.RECT_SHAPE and self.current and self.current.reachMaxPoints() is False: initPos = self.current[0] minX = initPos.x() minY = initPos.y() targetPos = self.line[1] maxX = targetPos.x() maxY = targetPos.y() self.current.addPoint(QPointF(minX, maxY)) self.current.addPoint(targetPos) self.current.addPoint(QPointF(maxX, minY)) self.current.addPoint(initPos) self.line[0] = self.current[-1] if self.current.isClosed(): self.finalise() elif not self.outOfPixmap(pos): self.current = Shape(shape_type=self.shape_type) self.current.addPoint(pos) self.line.points = [pos, pos] self.setHiding() self.drawingPolygon.emit(True) self.update() else: self.selectShapePoint(pos) self.prevPoint = pos self.repaint() elif ev.button() == Qt.RightButton and self.editing(): self.selectShapePoint(pos) self.prevPoint = pos self.repaint()
def mousePressEvent(self, ev): pos = self.transformPos(ev.pos()) if ev.button() == Qt.LeftButton: if self.drawing(): # self.handleDrawing(pos) # OLD if self.current: if self.fourpoint: # ADD IF # Add point to existing shape. # print('Adding points in mousePressEvent is ', self.line[1]) self.current.addPoint(self.line[1]) self.line[0] = self.current[-1] if self.current.isClosed(): # print('1111') self.finalise() elif self.drawSquare: # 增加 assert len(self.current.points) == 1 self.current.points = self.line.points self.finalise() elif not self.outOfPixmap(pos): # Create new shape. self.current = Shape() self.current.addPoint(pos) self.line.points = [pos, pos] self.setHiding() self.drawingPolygon.emit(True) self.update() else: group_mode = int(ev.modifiers()) == Qt.ControlModifier self.selectShapePoint(pos, multiple_selection_mode=group_mode) self.prevPoint = pos self.pan_initial_pos = pos elif ev.button() == Qt.RightButton and self.editing(): group_mode = int(ev.modifiers()) == Qt.ControlModifier self.selectShapePoint(pos, multiple_selection_mode=group_mode) self.prevPoint = pos self.update()
def __init__(self, *args, **kwargs): super(Canvas, self).__init__(*args, **kwargs) # Initialise local state. self.mode = self.EDIT self.shapes = [] self.current = None self.selected_shape = None # save the selected shape here self.selected_shape_copy = None self.drawing_bad_color = QColor(255, 0, 0) self.drawing_bad_fill_color = QColor(255, 0, 0, 155) self.drawing_line_color = QColor(0, 0, 255) self.drawing_rect_color = QColor(0, 0, 255) self.line = Shape(line_color=self.drawing_line_color) self.prev_point = QPointF() self.offsets = QPointF(), QPointF() self.scale = 1.0 self.label_font_size = 8 self.pixmap = QPixmap() self.visible = {} self._hide_background = False self.hide_background = False self.h_shape = None self.h_vertex = None self._painter = QPainter() self._cursor = CURSOR_DEFAULT # Menus: self.menus = (QMenu(), QMenu()) # Set widget options. self.setMouseTracking(True) self.setFocusPolicy(Qt.WheelFocus) self.verified = False self.draw_square = False self.label = None # initialisation for panning self.pan_initial_pos = QPoint()
def __init__(self, *args, **kwargs): super(Canvas, self).__init__(*args, **kwargs)#*args将输入的参数存放为元组,**kwargs将输入的参数存放为字典 # Initialise local state. self.shape_type = self.POLYGON_SHAPE self.brush_point = None self.task_mode = 3 self.erase_mode = False self.current_brush_path = None self.mask_Image = None self.brush_color =QColor(255,0,0,255) self.brush_size = 10 self.brush = QPainter(); self.mode = self.EDIT self.shapes = [] self.current = None self.selectedShape = None # save the selected shape here self.selectedShapeCopy = None self.lineColor = QColor(0, 0, 255) self.line = Shape(line_color=self.lineColor) self.prevPoint = QPointF() self.offsets = QPointF(), QPointF() self.scale = 1.0 self.bg_image = QImage() self.visible = {} self._hideBackround = False self.hideBackround = False self.hShape = None self.hVertex = None self._painter = QPainter(self) self.font_size = 50 self._cursor = CURSOR_DEFAULT # Menus: self.menus = (QMenu(), QMenu()) # Set widget options. self.setMouseTracking(True) self.setFocusPolicy(Qt.WheelFocus)
def __init__(self, *args, **kwargs): super(Canvas, self).__init__(*args, **kwargs) # Initialise local state. self.mode = self.EDIT self.contourMode = False self.shapes = [] self.current = None self.selectedShape = None # save the selected shape here self.selectedShapeCopy = None self.globalMousePos = None self.memIdx = list() self.currentIdx = 0 # only needed for toggling between multiple overlaying cells # self.drawingLineColor = QColor(0, 0, 255) # self.drawingRectColor = QColor(0, 0, 255) self.drawingLineColor = QColor(255, 255, 255, 255) self.drawingRectColor = QColor(255, 255, 255, 255) self.drawingContourColor = QColor(255, 0, 0) self.line = Shape(line_color=self.drawingLineColor) self.prevPoint = QPointF() self.offsets = QPointF(), QPointF() self.scale = 1.0 self.pixmap = QPixmap() self.visible = {} self._hideBackround = False self.hideBackround = False self.hShape = None self.hVertex = None self._painter = QPainter() self._cursor = CURSOR_DEFAULT # Menus: self.menus = (QMenu(), QMenu()) # Set widget options. self.setMouseTracking(True) self.setFocusPolicy(Qt.WheelFocus) self.verified = False self.showContourOverlay = False
def randomTable(num): # Create a black image img = np.zeros((512, 512, 3), np.uint8) img.fill(255) left = random.randint(20, 50) top = random.randint(50, 50) width = random.randint(100, 150) height = random.randint(30, 70) row = 4 #random.randint(1, 4) column = 3 # random.randint(1, 3) if row == 1 and column == 1: width, height = width * 2, height * 2 rectShapes = [] # print("image:{}, row num={}, column num ={} ".format(num, row, column)) for r in range(0, row): for c in range(0, column): start_point = (left + c * width, top + r * height) text_start_point = (start_point[0] + int(width * 0.1), start_point[1] + int(height * 0.1)) end_point = (left + (c + 1) * width, top + (r + 1) * height) # PIL image转换成array img = Image.fromarray(np.uint8(img)) draw = ImageDraw.Draw(img) word_height = int(height * 0.6) FONT = ImageFont.truetype('fonts/simhei.ttf', word_height) # 填字 draw.text(text_start_point, randomText(int(width / word_height - 1)), BLACK, font=FONT) # array转换成image img = np.asarray(img) # 画框 thickness = [1, 2] # 表格线粗细随机 cv.rectangle(img, start_point, end_point, BLACK, random.choice(thickness)) points = [start_point, end_point] shape = Shape(label='rect') for x, y in points: shape.addPoint(Point(x, y)) shape.close() rectShapes.append(shape) imagePath = 'VOC2007/JPEGImages/' xmlPath = 'VOC2007/Annotations/' fileName = imagePath + num + IMAGE_EXT xmlName = xmlPath + num + XML_EXT # print('fileName=', fileName) noise_percetage = random.uniform(0, .25) # print('noise_percetage=', noise_percetage) salt_noise_image = SaltAndPepper(img, noise_percetage) # 添加的椒盐噪声 gaussian_noise_image = addGaussianNoise(salt_noise_image) # 添加的高斯噪声 cv.imwrite(fileName, gaussian_noise_image) savePascalVocFormat(xmlName, rectShapes, imagePath, img)
def loadLabels(self, shapes): s = [] self.initLabelList() idx = len(self.labelInfoDict) for label, lineWidth, points, ellipse_points, rotate, r1, r2, center in shapes: if label not in self.labelInfoDict.keys(): with open( os.path.join(os.path.dirname(__file__), "predefined_labels.json")) as f: predefined_json = json.load(f) new_append_predefined_dict = { "name": "", "isPathClosed": True, "type": 0, "enable": True } new_append_predefined_dict['name'] = label if r1: new_append_predefined_dict['type'] = 1 predefined_json['labels'].append( new_append_predefined_dict) with open( os.path.join(os.path.dirname(__file__), "predefined_labels.json"), "w") as f: json.dump(predefined_json, f, indent=4) self.canvas.LABEL_COLORS.extend(self.canvas.random_colors(N=1)) self.labelInfoDict[label] = ( True, new_append_predefined_dict['type'], self.canvas.LABEL_COLORS[idx]) item = HashableQListWidgetItem(label) item.setFlags(item.flags() | Qt.ItemIsUserCheckable) item.setCheckState(Qt.Checked) item.setSelected(True) self.ui.labelList.addItem(item) self.labelToItem[label] = item idx = idx + 1 shape = Shape(label=label) shape.lineWidth = lineWidth shape.isPathClosed = self.labelInfoDict[label][0] shape.d_type = self.labelInfoDict[label][1] shape.lineColor = self.labelInfoDict[label][2] shape.rotate = rotate shape.r1 = r1 shape.r2 = r2 shape.center = center for x, y in points: shape.addPoint(QPointF(x, y)) for x, y in ellipse_points: shape.ellipse_points.append(QPointF(x, y)) if shape.d_type == self.canvas.Ellipse: shape.sampleEllipsePoints() shape.close() s.append(shape) self.addShapeList(shape) self.canvas.loadShapes(s)
def randomTable(num): # Create a black image img = np.zeros((512, 512, 3), np.uint8) img.fill(255) left = random.randint(20, 50) top = random.randint(50, 60) width = random.randint(40, 50) height = random.randint(30, 70) row = random.randint(2, 5) column = random.randint(4, 8) if row == 1 and column == 1: width, height = width * 2, height * 2 rectShapes = [] # print("image:{}, row num={}, column num ={} ".format(num, row, column)) for r in range(0, row): if r % 2 == 0: cell_width = column * width start_point = (left, top + r * height) text_start_point = (start_point[0] + int(width * 0.2), start_point[1] + int(height * 0.2)) end_point = (left + cell_width, top + (r + 1) * height) # PIL image转换成array img = Image.fromarray(np.uint8(img)) draw = ImageDraw.Draw(img) word_height = int(height * 0.6) FONT = ImageFont.truetype('fonts/simhei.ttf', word_height) # 字数量 word_sum = int(cell_width / word_height - 1) random_text = randomText(word_sum) text_end_point = (text_start_point[0] + word_height * word_sum, text_start_point[1] + word_height) # 填字 draw.text(text_start_point, random_text, BLACK, font=FONT) # 标注文字 text_points = [text_start_point, text_end_point] text_shape = Shape(label='text') for x, y in text_points: text_shape.addPoint(Point(x, y)) text_shape.close() rectShapes.append(text_shape) # array转换成image img = np.asarray(img) # 画框 thickness = [1, 2] # 表格线粗细随机 # cv.rectangle(img, start_point, end_point, BLACK, random.choice(thickness)) # 用线画矩形 top_right_point = (end_point[0], start_point[1]) bottom_left_point = (start_point[0], end_point[1]) cv.line(img, start_point, top_right_point, BLACK, 1) # draw top line cv.line(img, bottom_left_point, end_point, BLACK, 1) # draw bottom line cv.line(img, start_point, bottom_left_point, BLACK, 1) # draw left line cv.line(img, top_right_point, end_point, BLACK, 1) # draw right line points = [start_point, end_point] shape = Shape(label='rect') for x, y in points: shape.addPoint(Point(x, y)) shape.close() rectShapes.append(shape) continue for c in range(0, column): start_point = (left + c * width, top + r * height) text_start_point = (start_point[0] + int(width * 0.2), start_point[1] + int(height * 0.2)) end_point = (left + (c + 1) * width, top + (r + 1) * height) # PIL image转换成array img = Image.fromarray(np.uint8(img)) draw = ImageDraw.Draw(img) word_height = int(height * 0.6) FONT = ImageFont.truetype('fonts/simhei.ttf', word_height) text_end_point = (text_start_point[0] + word_height * 0.75, text_start_point[1] + word_height) # 填字 draw.text(text_start_point, random.choice(TEXT2), BLACK, font=FONT) # 标注文字 text_points = [text_start_point, text_end_point] text_shape = Shape(label='text') for x, y in text_points: text_shape.addPoint(Point(x, y)) text_shape.close() rectShapes.append(text_shape) # array转换成image img = np.asarray(img) # 画框 thickness = [1, 2] # 表格线粗细随机 # cv.rectangle(img, start_point, end_point, BLACK, random.choice(thickness)) # 用线画矩形 top_right_point = (end_point[0], start_point[1]) bottom_left_point = (start_point[0], end_point[1]) cv.line(img, start_point, top_right_point, BLACK, 1) # draw top line cv.line(img, bottom_left_point, end_point, BLACK, 1) # draw bottom line cv.line(img, start_point, bottom_left_point, BLACK, 1) # draw left line cv.line(img, top_right_point, end_point, BLACK, 1) # draw right line points = [start_point, end_point] shape = Shape(label='rect') for x, y in points: shape.addPoint(Point(x, y)) shape.close() rectShapes.append(shape) # cv.namedWindow(num, 0) # cv.imshow(num, img) # cv.waitKey(0) imagePath = 'VOC2007/JPEGImages/' xmlPath = 'VOC2007/Annotations/' fileName = imagePath + num + IMAGE_EXT xmlName = xmlPath + num + XML_EXT # print('fileName=', fileName) noise_percetage = random.uniform(0, .20) # print('noise_percetage=', noise_percetage) salt_noise_image = SaltAndPepper(img, noise_percetage) # 添加的椒盐噪声 gaussian_noise_image = addGaussianNoise(salt_noise_image) # 添加的高斯噪声 cv.imwrite(fileName, gaussian_noise_image) savePascalVocFormat(xmlName, rectShapes, imagePath, img)
def handleDrawing(self, pos): if self.drawRegion: if self.current: #initPos = self.current[0] self.current.addPoint(self.line[1]) self.finalise_region() elif not self.outOfPixmap(pos): self.current = Shape(drawRegion=True) self.current.addPoint(pos) self.line.points = [pos, pos] self.setHiding() self.drawingPolygon.emit(True) self.update() else: if self.current and self.current.reachMaxPoints() is False: initPos = self.current[0] minX = initPos.x() minY = initPos.y() if Canvas.FIXED_HEIGHT == 0 and Canvas.FIXED_WIDTH == 0: targetPos = self.line[1] maxX = targetPos.x() maxY = targetPos.y() else: self.current.clearPoints() orig_minX = minX orig_minY = minY minX = minX - Canvas.FIXED_WIDTH / 2 minY = minY - Canvas.FIXED_HEIGHT / 2 maxX = minX + Canvas.FIXED_WIDTH maxY = minY + Canvas.FIXED_HEIGHT # lef scale if minX < 25: maxX = maxX + (25 - minX) minX = 25 if maxX > 740: minX = minX - (maxX - 740) maxX = 740 # top if minY < 155: maxY = maxY + (155 - minY) minY = 155 # if maxY > 540: minY = minY - (maxY - 540) maxY = 540 if orig_minX <= 378: # left image if minY <= 200 and maxX > 310: #avoid color bar if orig_minY < 200: minX = minX - (maxX - 310) maxX = 310 else: minX = minX - (maxX - 378) maxX = 378 maxY = maxY - (minY - 200) minY = 200 elif maxX > 378: minX = minX - (maxX - 378) maxX = 378 else: # right image if minY <= 200 and maxX > 690: # avoid color bar if orig_minY < 200: minX = minX - (maxX - 690) maxX = 690 else: minX = minX - (maxX - 740) maxX = 740 maxY = maxY - (minY - 192) minY = 200 else: if maxX > 740: minX = minX - (maxX - 740) maxX = 740 if minX < 378: maxX = maxX + (378 - minX) minX = 378 if minY < 170: maxY = maxY + (170 - minY) minY = 170 self.current.addPoint(QPointF(minX, minY)) targetPos = QPointF(maxX, maxY) self.line[1] = targetPos self.current.addPoint(QPointF(maxX, minY)) self.current.addPoint(targetPos) self.current.addPoint(QPointF(minX, maxY)) self.finalise() elif not self.outOfPixmap(pos): self.current = Shape() self.current.addPoint(pos) self.line.points = [pos, pos] self.setHiding() self.drawingPolygon.emit(True) self.update()
def __init__(self, *args, **kwargs): super(Canvas, self).__init__(*args, **kwargs) #*args将输入的参数存放为元组,**kwargs将输入的参数存放为字典 # Initialise local state. PP = Predefined_Points() self.shape_type = self.POLYGON_SHAPE self.image = QImage() self.brush_point = None self.task_mode = 3 self.erase_mode = False self.current_brush_path = None self.mask_Image = None self.brush_color = QColor(255, 0, 0, 255) self.brush_size = 10 self.brush = QPainter() self.mode = self.EDIT self.shapes = [] self.current = None self.selectedShape = None # save the selected shape here self.selectedShapeCopy = None self.lineColor = QColor(0, 0, 255) self.line = Shape(line_color=self.lineColor) self.prevPoint = QPointF() self.offsets = QPointF(), QPointF() self.scale = 1.2 self.bg_image = QImage() self.visible = {} self._hideBackround = False self.hideBackround = False self.hShape = None self.hVertex = None self._painter = QPainter(self) self.font_size = 50 self._cursor = CURSOR_DEFAULT # Menus: self.menus = (QMenu(), QMenu()) # Set widget options. self.setMouseTracking(True) self.setFocusPolicy(Qt.WheelFocus) ##point self.point_point = None self.point_point_list = [] self.point_point_list_tmp = [] self.point_dex = None self.point_color = [ QColor(r, g, b) for r in [0, 160, 120, 30, 40] for g in [0, 160, 120, 30, 90] for b in [0, 160, 120, 30] ] self.point_move = None self.point_path = None self.point_selecteditem = None self.point_delete = False self.point_modified = False self.point_shape = {} self.point_link = PP.define_points_links() self.point_num = max(np.array(self.point_link)[:, 1]) # self.point_visible = {i:True for i in range(len(self.point_link))} self.point_visible = {i: True for i in range(self.point_num + 1)} self.point_cover = {i: 2 for i in range(self.point_num)} self.point_deletedid = [] self.point_ids = [] self.point_all_deleted = False self.point_save = [] self.point_link_save = [] self.point_rect = [] self.point_rects = [] self.point_rects_index = 0 self.point_next_rect = False self.point_shape = {} self.point_changed = False self.point_cover_change = False self.point_cover_change_dex = 0 self.point_cover_dict = {} #parse self.parse_rects = {} self.parse_rects_index = 0 self.parse_rects_num = 0 self.parse_shapes = {} self.xuxian = None self.start = False self.started = False
def mousePressEvent(self, ev): mods = ev.modifiers() pos = self.transformPos(ev.pos()) task_mode = self.task_mode if self.start == True and task_mode == 0: self.started = True self.xuxian = None if ev.button() == Qt.LeftButton: if self.drawing(): # if self.shape_type == self.POLYGON_SHAPE and self.current: self.current.addPoint(self.line[1]) self.line[0] = self.current[-1] if self.current.isClosed(): self.finalise() elif self.shape_type == self.RECT_SHAPE and self.current and self.current.reachMaxPoints( ) is False: if self.task_mode == 5 and len(self.shapes) >= 3: self.current = None self.xuxian = None self.start = False self.started = False QMessageBox.about( self, "About", self.tr('<p><b>%s</b></p>%s <p>%s</p>' % ('注意标注已经为', str(3) + '个', '只可修改'))) return # self.repaint() initPos = self.current[0] minX = initPos.x() minY = initPos.y() targetPos = self.line[1] maxX = targetPos.x() maxY = targetPos.y() self.current.addPoint(QPointF(minX, maxY)) self.current.addPoint(targetPos) self.current.addPoint(QPointF(maxX, minY)) self.current.addPoint(initPos) self.line[0] = self.current[-1] if self.current.isClosed(): self.finalise() elif not self.outOfPixmap(pos): self.current = Shape(shape_type=self.shape_type) self.current.addPoint(pos) self.line.points = [pos, pos] self.setHiding() self.drawingPolygon.emit(True) self.update() elif self.task_mode == 4: self.point_changed = True if self.point_modified: self.point_point_list[self.point_modified - 1] = pos self.point_modified = False self.repaint() else: distances = [] self.point_point_list.append(pos) # if not len(self.point_point_list)>self.point_num : if Qt.LeftButton & ev.buttons(): # 左鼠标点击 if self.outOfPixmap(pos): # 超出图像范围 return elif len(self.point_point_list) > 1: if self.point_point_list[ -1] and self.point_point_list[-2]: if distance(self.point_point_list[-1] - self.point_point_list[-2]) <= 5: self.point_move = True del self.point_point_list[-1] for i, p in enumerate(self.point_point_list[:-2]): if p: distances.append(distance(p - pos)) distances.sort() print('distances') if len(distances) >= 1: if distances[0] <= 5: #注意 一次只能删除一个点 if distances[0] <= 5: self.point_move = True #这里给出可移动的指令 del self.point_point_list[-1] if self.point_move: self.point_point = pos self.overrideCursor(Qt.CrossCursor) self.repaint() return else: self.selectShapePoint(pos) self.prevPoint = pos self.repaint() elif ev.button() == Qt.RightButton and self.editing(): self.selectShapePoint(pos) self.prevPoint = pos self.repaint() #这里只是传点吧
def __init__(self, *args, **kwargs): super(Canvas, self).__init__(*args, **kwargs) #*args将输入的参数存放为元组,**kwargs将输入的参数存放为字典 # Initialise local state. self.shape_type = self.POLYGON_SHAPE self.brush_point = None self.task_mode = 3 self.erase_mode = False self.current_brush_path = None self.mask_Image = None self.brush_color = QColor(255, 0, 0, 255) self.brush_size = 10 self.brush = QPainter() self.mode = self.EDIT self.shapes = [] self.current = None self.selectedShape = None # save the selected shape here self.selectedShapeCopy = None self.lineColor = QColor(0, 0, 255) self.line = Shape(line_color=self.lineColor) self.prevPoint = QPointF() self.offsets = QPointF(), QPointF() self.scale = 1.0 self.bg_image = QImage() self.visible = {} self._hideBackround = False self.hideBackround = False self.hShape = None self.hVertex = None self._painter = QPainter(self) self.font_size = 50 self._cursor = CURSOR_DEFAULT # Menus: self.menus = (QMenu(), QMenu()) # Set widget options. self.setMouseTracking(True) self.setFocusPolicy(Qt.WheelFocus) ##point self.point_point = None self.point_point_list = [] self.point_point_list_tmp = [] self.point_dex = None self.point_color = [ QColor(r, g, b) for r in [0, 255, 120, 30] for g in [0, 255, 120, 30] for b in [0, 255, 120, 30] ] self.point_move = None self.point_path = None self.point_selecteditem = None self.point_delete = False self.point_modified = False self.point_shape = {} self.point_link = [[1, 2], [1, 3], [2, 3], [2, 4], [3, 5], [4, 6], [5, 7], [6, 7], [6, 8], [6, 12], [7, 9], [7, 13], [8, 10], [9, 11], [12, 13], [12, 14], [13, 15], [14, 16], [15, 17]] self.point_num = max(np.array(self.point_link)[:, 1]) self.point_visible = {i: True for i in range(len(self.point_link))} self.point_deletedid = [] self.point_ids = [] self.point_all_deleted = False self.point_save = [] self.point_link_save = [] self.point_rect = [] self.point_rects = [] self.point_rects_index = 0 self.point_next_rect = False
def mousePressEvent(self, ev): mods = ev.modifiers() pos = self.transformPos(ev.pos()) if ev.button() == Qt.LeftButton: if self.drawing(): # if self.shape_type == self.POLYGON_SHAPE and self.current: self.current.addPoint(self.line[1]) self.line[0] = self.current[-1] if self.current.isClosed(): self.finalise() elif self.shape_type == self.RECT_SHAPE and self.current and self.current.reachMaxPoints( ) is False: initPos = self.current[0] minX = initPos.x() minY = initPos.y() targetPos = self.line[1] maxX = targetPos.x() maxY = targetPos.y() self.current.addPoint(QPointF(minX, maxY)) self.current.addPoint(targetPos) self.current.addPoint(QPointF(maxX, minY)) self.current.addPoint(initPos) self.line[0] = self.current[-1] if self.current.isClosed(): self.finalise() elif not self.outOfPixmap(pos): self.current = Shape(shape_type=self.shape_type) self.current.addPoint(pos) self.line.points = [pos, pos] self.setHiding() self.drawingPolygon.emit(True) self.update() elif self.task_mode == 4: distances = [] self.point_point_list.append(pos) if Qt.LeftButton & ev.buttons(): # 左鼠标点击 if self.outOfPixmap(pos): # 超出图像范围 return elif len(self.point_point_list) > 1: if distance(self.point_point_list[-1] - self.point_point_list[-2]) <= 5: self.point_move = True del self.point_point_list[-1] for i, p in enumerate(self.point_point_list[:-2]): distances.append(distance(p - pos)) distances.sort() print('distances', distances) if len(distances) >= 1: if distances[0] <= 5: #注意 一次只能删除一个点 print(self.point_point_list[-1]) if distances[0] <= 2: self.point_move = True #这里给出可移动的指令 del self.point_point_list[-1] if self.point_move: self.point_point = pos # elif Qt.RightButton & ev.buttons(): # print('dede') # for i, p in enumerate(self.point_point_list[:-2]): # if distance(p-pos)<=5: # print('delete point') self.overrideCursor(Qt.CrossCursor) self.repaint() return else: self.selectShapePoint(pos) self.prevPoint = pos self.repaint() elif ev.button() == Qt.RightButton and self.editing(): self.selectShapePoint(pos) self.prevPoint = pos self.repaint() #这里只是传点吧
def rotateShape(self, pos, shape, debug=True): """ Rotates a shape by dragging the shape-rotation-button to the position `pos`. Checks if the resulting shape is completely inside the image in the image. If not, rotate by an angle that is closest to the desired angle but still yielding a shape inside the image. """ # Case 1: Rotate the shape vertex_not_rotated = shape.getShapeRotationVertex(False) if vertex_not_rotated is not None: eucl_sq = lambda a: a.x()**2 + a.y()**2 # Fetch the original (=not rotated) vertex-position for movement # and the center of mass of the shape (once again according to # the coordinates that are not rotated) vertex_point = vertex_not_rotated[0] vertex_mirrored = vertex_not_rotated[2] shape_center = shape.getCenter(False) # Compute the vector and distance between both aforementioned points vec_old_center = vertex_point - shape_center # - vertex_point dist_old_center_square = eucl_sq(vec_old_center) # Compute the vector and distance between the new position and the center vec_new_center = pos - shape_center # - pos dist_new_center_square = eucl_sq(vec_new_center) # Now compute the angle between both the vector pointing to the new # position of the rotation vertex and the one pointing to its # original position. # Make completely sure that no rounding errors can cause # mathematical errors for the input value by checking bounds. val = QPointF.dotProduct(vec_new_center, vec_old_center) / \ (dist_new_center_square * dist_old_center_square) **.5 val = min(max(val, -1), 1) angle = acos(val) # The direction of movement has to be adapted depending on the # current state of the vertex. # First condition: vertex is 'mirrored': # the initially topmost line is dragged under line # at the bottom; In this case the sign must be # swapped. # Second condition: as the shape-move vertex is always # directly above or beneath the shape's center # it is succicent to check the x coordinate for # checking if the rotation is 'in the second # half'. In that case, rotate by 2pi -angle transform_angle = lambda a, posx : \ (-1 if vertex_mirrored else 1) \ * (a if (posx >= vertex_point.x()) else 2. * pi - a) angle = transform_angle(angle, pos.x()) # XXX: this checking mechanism does not work entirely (the # distinction of valid angles sometimes does not recognize the # fact that two edges are outside the valid area). # and contains debug code (that inserts vertices to some # positions for debugging) and thus should only be commented # in for finishing the implementation of that feature (in case # it is required)). # If it is not required it should be removed. performCheckOfIntervals = False if performCheckOfIntervals: # Not all angles are valid. Find out which angles are leading to # coordiantes outside the image: # Step 1) find (x,y) with \|(x,y) - c \| = \|x_1 - x_3\| # and (x,y) on image's borders # Step 2) find the associated rotation angles and store them # in a sorted way width, height = self.pixmap.width(), self.pixmap.height() # get the radius of the circle p_c = shape.pointsWithoutRotation[0] - shape_center len_p_c = eucl_sq(p_c) # list all the support vectors indicating image border alongside # with their directions support_direction = [ [QPointF(0, 0), QPointF(width - 1, 0)], [QPointF(0, 0), QPointF(0, height - 1)], [QPointF(width - 1, 0), QPointF(0, height - 1)], [QPointF(0, height - 1), QPointF(width - 1, 0)] ] forbiddenAngleIntervals = [] for s, d in support_direction: # find intersections between the circle (defined by the center # and its radius) and the currently considered image border. # # In case there is only one (or none) intersection, # no conditions are imposed in this step on the anlge as the # image borders are selected to be the last line of pixels # inside the image. # # If there are two intersections, the space in between them is # forbidden intersects = Canvas.intersectionLineCircle( s - shape_center, d, sqrt(len_p_c)) if intersects is not None: # In case debugging is enabled, add new shapes that show # the intersections with the borders in the image. # Attention: debugging cannot be used in a productive mode. # Results in a bunch of new vertices. if debug: deb = Shape() deb.addPoint(intersects[0] + shape_center) deb.addPoint(intersects[1] + shape_center) deb.close() self.shapes.append(deb) deb = Shape() deb.addPoint(p_c + shape_center) deb.close() self.shapes.append(deb) # the corresponding angle is the angle between the # intersection point and the vertex_point (shifted by # center) if len(intersects) == 2: angles = [[ transform_angle( acos( QPointF.dotProduct( spwr - shape_center, a) / (len_p_c * eucl_sq(a))**.5), spwr.x()) for a in intersects ] for spwr in shape.pointsWithoutRotation] for i, (a, b) in enumerate(angles): # find the min and max value and compute the # min and max value that are still allowed. # if the angle might be affected by them t = 0 if a < 0: a += 2 * pi if b < 0: b += 2 * pi mx, mi = max(a, b), min(a, b) if mx - mi > pi: forbiddenAngleIntervals.append( [mx, 2 * pi]) forbiddenAngleIntervals.append([0, mi]) else: forbiddenAngleIntervals.append([mi, mx]) #if a < b: # forbiddenAngleIntervals.append([a, b]) #elif b < a: # forbiddenAngleIntervals.append([a, 2*pi]) # forbiddenAngleIntervals.append([0, b]) # paint vector (forbidden area) based on the # computed angle if debug: p1 = Shape.rotatePoint( shape.pointsWithoutRotation[i], shape_center, a) p2 = Shape.rotatePoint( shape.pointsWithoutRotation[i], shape_center, b) deb = Shape() deb.addPoint(p1) deb.addPoint(p2) deb.close() self.shapes.append(deb) # XXX: There most likely is a better solution to this. # The code below is supposed to unite all forbidden intervals. # This is necessary for being able to pick the closest point # to the forbidden area. if len(forbiddenAngleIntervals): unionInterval = [forbiddenAngleIntervals[0]] uiid = 0 # starts before other.end and stops after other.start checkIntersect = lambda a, b: a[1] >= b[0] and a[0] <= b[1] checkIntersectMutual = lambda a, b: checkIntersect(a, b) \ or checkIntersect(b, a) # need to check multiple times as there might be an array that # unites two other arrays. for k in range(len(forbiddenAngleIntervals) - 1): for i in range(1, len(forbiddenAngleIntervals)): # check if there is already is an interval comprising me inters = False for ui in range(len(unionInterval)): # end union > start this if (checkIntersectMutual( unionInterval[ui], forbiddenAngleIntervals[i])): unionInterval[ui][0] = min( unionInterval[ui][0], forbiddenAngleIntervals[i][0]) unionInterval[ui][1] = max( unionInterval[ui][1], forbiddenAngleIntervals[i][1]) inters = True break if not inters: unionInterval.append( forbiddenAngleIntervals[i]) print(forbiddenAngleIntervals, unionInterval) # Check if there is some intersection and use the closest point # as corrected angle. if angle < 0: angle += 2 * pi for i in unionInterval: if i[0] < angle and angle < i[1]: angle = i[0] if angle - i[0] < i[1] - angle else i[ 1] break # Apply the rotation for the shape (computes new location of rotated # values and stores the current angle for future reference): shape.applyRotationAngle(angle, shape_center)
def capture_predict_area(self): if self.right_click_pos is None: return None #self.drawRegion = False # create detect rectangle self.current = Shape() minX = self.right_click_pos.x() minY = self.right_click_pos.y() orig_minX = minX orig_minY = minY minX = minX - Canvas.FIXED_WIDTH / 2 minY = minY - Canvas.FIXED_HEIGHT / 2 maxX = minX + Canvas.FIXED_WIDTH maxY = minY + Canvas.FIXED_HEIGHT # lef scale if minX < 25: maxX = maxX + (25 - minX) minX = 25 if maxX > 740: minX = minX - (maxX - 740) maxX = 740 # top if minY < 155: maxY = maxY + (155 - minY) minY = 155 # if maxY > 540: minY = minY - (maxY - 540) maxY = 540 if orig_minX <= 378: # left image if minY <= 200 and maxX > 310: # avoid color bar if orig_minY < 200: minX = minX - (maxX - 310) maxX = 310 else: minX = minX - (maxX - 378) maxX = 378 maxY = maxY - (minY - 200) minY = 200 elif maxX > 378: minX = minX - (maxX - 378) maxX = 378 else: # right image if minY <= 200 and maxX > 690: # avoid color bar if orig_minY < 200: minX = minX - (maxX - 690) maxX = 690 else: minX = minX - (maxX - 740) maxX = 740 maxY = maxY - (minY - 200) minY = 200 else: if maxX > 740: minX = minX - (maxX - 740) maxX = 740 if minX < 378: maxX = maxX + (378 - minX) minX = 378 if minY < 170: maxY = maxY + (170 - minY) minY = 170 self.current.addPoint(QPointF(minX, minY)) targetPos = QPointF(maxX, maxY) # self.line[1] = targetPos self.current.addPoint(QPointF(maxX, minY)) self.current.addPoint(targetPos) self.current.addPoint(QPointF(minX, maxY)) self.current.close() self.repaint() self.keeptissue = self.current.copy() rect = self.covert2Rectangle(self.current.points) split_img = self.pixmap.copy(rect[0], rect[1], rect[2], rect[3]).toImage() split_img = split_img.convertToFormat(QImage.Format_Grayscale8) split_img = qp.qimageview(split_img) split_img = np.stack((split_img, ) * 3, axis=-1) return split_img