* rename local variables in main file

* additional renaming of functions and variables

* Rename main file functions

* Rename functions and variables in canvas.py

* Rename functions and locals for remaining files

* Rename non-Qt derived class' members

* Rename members of Qt-derived classes

* Fix paint label issue
This commit is contained in:
Cerno_b 2021-03-15 00:56:14 +01:00 committed by GitHub
parent ef05452f7c
commit c35f09747a
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
16 changed files with 1433 additions and 1433 deletions

File diff suppressed because it is too large Load Diff

View File

@ -7,7 +7,7 @@ except ImportError:
from PyQt4.QtGui import *
from PyQt4.QtCore import *
#from PyQt4.QtOpenGL import *
# from PyQt4.QtOpenGL import *
from libs.shape import Shape
from libs.utils import distance
@ -39,21 +39,21 @@ class Canvas(QWidget):
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.selected_shape = None # save the selected shape here
self.selected_shape_copy = None
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.labelFontSize = 8
self.label_font_size = 8
self.pixmap = QPixmap()
self.visible = {}
self._hideBackround = False
self.hideBackround = False
self.hShape = None
self.hVertex = None
self._hide_background = False
self.hide_background = False
self.h_shape = None
self.h_vertex = None
self._painter = QPainter()
self._cursor = CURSOR_DEFAULT
# Menus:
@ -62,23 +62,23 @@ class Canvas(QWidget):
self.setMouseTracking(True)
self.setFocusPolicy(Qt.WheelFocus)
self.verified = False
self.drawSquare = False
self.draw_square = False
#initialisation for panning
# initialisation for panning
self.pan_initial_pos = QPoint()
def setDrawingColor(self, qColor):
self.drawingLineColor = qColor
self.drawingRectColor = qColor
def set_drawing_color(self, qcolor):
self.drawing_line_color = qcolor
self.drawing_rect_color = qcolor
def enterEvent(self, ev):
self.overrideCursor(self._cursor)
self.override_cursor(self._cursor)
def leaveEvent(self, ev):
self.restoreCursor()
self.restore_cursor()
def focusOutEvent(self, ev):
self.restoreCursor()
self.restore_cursor()
def isVisible(self, shape):
return self.visible.get(shape, True)
@ -89,44 +89,44 @@ class Canvas(QWidget):
def editing(self):
return self.mode == self.EDIT
def setEditing(self, value=True):
def set_editing(self, value=True):
self.mode = self.EDIT if value else self.CREATE
if not value: # Create
self.unHighlight()
self.deSelectShape()
self.prevPoint = QPointF()
self.un_highlight()
self.de_select_shape()
self.prev_point = QPointF()
self.repaint()
def unHighlight(self):
if self.hShape:
self.hShape.highlightClear()
self.hVertex = self.hShape = None
def un_highlight(self):
if self.h_shape:
self.h_shape.highlight_clear()
self.h_vertex = self.h_shape = None
def selectedVertex(self):
return self.hVertex is not None
def selected_vertex(self):
return self.h_vertex is not None
def mouseMoveEvent(self, ev):
"""Update line with last point and current coordinates."""
pos = self.transformPos(ev.pos())
pos = self.transform_pos(ev.pos())
# Update coordinates in status bar if image is opened
window = self.parent().window()
if window.filePath is not None:
self.parent().window().labelCoordinates.setText(
if window.file_path is not None:
self.parent().window().label_coordinates.setText(
'X: %d; Y: %d' % (pos.x(), pos.y()))
# Polygon drawing.
if self.drawing():
self.overrideCursor(CURSOR_DRAW)
self.override_cursor(CURSOR_DRAW)
if self.current:
# Display annotation width and height while drawing
currentWidth = abs(self.current[0].x() - pos.x())
currentHeight = abs(self.current[0].y() - pos.y())
self.parent().window().labelCoordinates.setText(
'Width: %d, Height: %d / X: %d; Y: %d' % (currentWidth, currentHeight, pos.x(), pos.y()))
current_width = abs(self.current[0].x() - pos.x())
current_height = abs(self.current[0].y() - pos.y())
self.parent().window().label_coordinates.setText(
'Width: %d, Height: %d / X: %d; Y: %d' % (current_width, current_height, pos.x(), pos.y()))
color = self.drawingLineColor
if self.outOfPixmap(pos):
color = self.drawing_line_color
if self.out_of_pixmap(pos):
# Don't allow the user to draw outside the pixmap.
# Clip the coordinates to 0 or max,
# if they are outside the range [0, max]
@ -134,57 +134,57 @@ class Canvas(QWidget):
clipped_x = min(max(0, pos.x()), size.width())
clipped_y = min(max(0, pos.y()), size.height())
pos = QPointF(clipped_x, clipped_y)
elif len(self.current) > 1 and self.closeEnough(pos, self.current[0]):
elif len(self.current) > 1 and self.close_enough(pos, self.current[0]):
# Attract line to starting point and colorise to alert the
# user:
pos = self.current[0]
color = self.current.line_color
self.overrideCursor(CURSOR_POINT)
self.current.highlightVertex(0, Shape.NEAR_VERTEX)
self.override_cursor(CURSOR_POINT)
self.current.highlight_vertex(0, Shape.NEAR_VERTEX)
if self.drawSquare:
initPos = self.current[0]
minX = initPos.x()
minY = initPos.y()
min_size = min(abs(pos.x() - minX), abs(pos.y() - minY))
directionX = -1 if pos.x() - minX < 0 else 1
directionY = -1 if pos.y() - minY < 0 else 1
self.line[1] = QPointF(minX + directionX * min_size, minY + directionY * min_size)
if self.draw_square:
init_pos = self.current[0]
min_x = init_pos.x()
min_y = init_pos.y()
min_size = min(abs(pos.x() - min_x), abs(pos.y() - min_y))
direction_x = -1 if pos.x() - min_x < 0 else 1
direction_y = -1 if pos.y() - min_y < 0 else 1
self.line[1] = QPointF(min_x + direction_x * min_size, min_y + direction_y * min_size)
else:
self.line[1] = pos
self.line.line_color = color
self.prevPoint = QPointF()
self.current.highlightClear()
self.prev_point = QPointF()
self.current.highlight_clear()
else:
self.prevPoint = pos
self.prev_point = pos
self.repaint()
return
# Polygon copy moving.
if Qt.RightButton & ev.buttons():
if self.selectedShapeCopy and self.prevPoint:
self.overrideCursor(CURSOR_MOVE)
self.boundedMoveShape(self.selectedShapeCopy, pos)
if self.selected_shape_copy and self.prev_point:
self.override_cursor(CURSOR_MOVE)
self.bounded_move_shape(self.selected_shape_copy, pos)
self.repaint()
elif self.selectedShape:
self.selectedShapeCopy = self.selectedShape.copy()
elif self.selected_shape:
self.selected_shape_copy = self.selected_shape.copy()
self.repaint()
return
# Polygon/Vertex moving.
if Qt.LeftButton & ev.buttons():
if self.selectedVertex():
self.boundedMoveVertex(pos)
if self.selected_vertex():
self.bounded_move_vertex(pos)
self.shapeMoved.emit()
self.repaint()
elif self.selectedShape and self.prevPoint:
self.overrideCursor(CURSOR_MOVE)
self.boundedMoveShape(self.selectedShape, pos)
elif self.selected_shape and self.prev_point:
self.override_cursor(CURSOR_MOVE)
self.bounded_move_shape(self.selected_shape, pos)
self.shapeMoved.emit()
self.repaint()
else:
#pan
# pan
delta_x = pos.x() - self.pan_initial_pos.x()
delta_y = pos.y() - self.pan_initial_pos.y()
self.scrollRequest.emit(delta_x, Qt.Horizontal)
@ -192,7 +192,7 @@ class Canvas(QWidget):
self.update()
return
# Just hovering over the canvas, 2 posibilities:
# Just hovering over the canvas, 2 possibilities:
# - Highlight shapes
# - Highlight vertex
# Update shape/vertex fill and tooltip value accordingly.
@ -200,163 +200,163 @@ class Canvas(QWidget):
for shape in reversed([s for s in self.shapes if self.isVisible(s)]):
# Look for a nearby vertex to highlight. If that fails,
# check if we happen to be inside a shape.
index = shape.nearestVertex(pos, self.epsilon)
index = shape.nearest_vertex(pos, self.epsilon)
if index is not None:
if self.selectedVertex():
self.hShape.highlightClear()
self.hVertex, self.hShape = index, shape
shape.highlightVertex(index, shape.MOVE_VERTEX)
self.overrideCursor(CURSOR_POINT)
if self.selected_vertex():
self.h_shape.highlight_clear()
self.h_vertex, self.h_shape = index, shape
shape.highlight_vertex(index, shape.MOVE_VERTEX)
self.override_cursor(CURSOR_POINT)
self.setToolTip("Click & drag to move point")
self.setStatusTip(self.toolTip())
self.update()
break
elif shape.containsPoint(pos):
if self.selectedVertex():
self.hShape.highlightClear()
self.hVertex, self.hShape = None, shape
elif shape.contains_point(pos):
if self.selected_vertex():
self.h_shape.highlight_clear()
self.h_vertex, self.h_shape = None, shape
self.setToolTip(
"Click & drag to move shape '%s'" % shape.label)
self.setStatusTip(self.toolTip())
self.overrideCursor(CURSOR_GRAB)
self.override_cursor(CURSOR_GRAB)
self.update()
break
else: # Nothing found, clear highlights, reset state.
if self.hShape:
self.hShape.highlightClear()
if self.h_shape:
self.h_shape.highlight_clear()
self.update()
self.hVertex, self.hShape = None, None
self.overrideCursor(CURSOR_DEFAULT)
self.h_vertex, self.h_shape = None, None
self.override_cursor(CURSOR_DEFAULT)
def mousePressEvent(self, ev):
pos = self.transformPos(ev.pos())
pos = self.transform_pos(ev.pos())
if ev.button() == Qt.LeftButton:
if self.drawing():
self.handleDrawing(pos)
self.handle_drawing(pos)
else:
selection = self.selectShapePoint(pos)
self.prevPoint = pos
selection = self.select_shape_point(pos)
self.prev_point = pos
if selection is None:
#pan
# 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.select_shape_point(pos)
self.prev_point = pos
self.update()
def mouseReleaseEvent(self, ev):
if ev.button() == Qt.RightButton:
menu = self.menus[bool(self.selectedShapeCopy)]
self.restoreCursor()
menu = self.menus[bool(self.selected_shape_copy)]
self.restore_cursor()
if not menu.exec_(self.mapToGlobal(ev.pos()))\
and self.selectedShapeCopy:
and self.selected_shape_copy:
# Cancel the move by deleting the shadow copy.
self.selectedShapeCopy = None
self.selected_shape_copy = None
self.repaint()
elif ev.button() == Qt.LeftButton and self.selectedShape:
if self.selectedVertex():
self.overrideCursor(CURSOR_POINT)
elif ev.button() == Qt.LeftButton and self.selected_shape:
if self.selected_vertex():
self.override_cursor(CURSOR_POINT)
else:
self.overrideCursor(CURSOR_GRAB)
self.override_cursor(CURSOR_GRAB)
elif ev.button() == Qt.LeftButton:
pos = self.transformPos(ev.pos())
pos = self.transform_pos(ev.pos())
if self.drawing():
self.handleDrawing(pos)
self.handle_drawing(pos)
else:
#pan
# pan
QApplication.restoreOverrideCursor()
def endMove(self, copy=False):
assert self.selectedShape and self.selectedShapeCopy
shape = self.selectedShapeCopy
#del shape.fill_color
#del shape.line_color
def end_move(self, copy=False):
assert self.selected_shape and self.selected_shape_copy
shape = self.selected_shape_copy
# del shape.fill_color
# del shape.line_color
if copy:
self.shapes.append(shape)
self.selectedShape.selected = False
self.selectedShape = shape
self.selected_shape.selected = False
self.selected_shape = shape
self.repaint()
else:
self.selectedShape.points = [p for p in shape.points]
self.selectedShapeCopy = None
self.selected_shape.points = [p for p in shape.points]
self.selected_shape_copy = None
def hideBackroundShapes(self, value):
self.hideBackround = value
if self.selectedShape:
def hide_background_shapes(self, value):
self.hide_background = value
if self.selected_shape:
# Only hide other shapes if there is a current selection.
# Otherwise the user will not be able to select a shape.
self.setHiding(True)
self.set_hiding(True)
self.repaint()
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))
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.outOfPixmap(pos):
elif not self.out_of_pixmap(pos):
self.current = Shape()
self.current.addPoint(pos)
self.current.add_point(pos)
self.line.points = [pos, pos]
self.setHiding()
self.set_hiding()
self.drawingPolygon.emit(True)
self.update()
def setHiding(self, enable=True):
self._hideBackround = self.hideBackround if enable else False
def set_hiding(self, enable=True):
self._hide_background = self.hide_background if enable else False
def canCloseShape(self):
def can_close_shape(self):
return self.drawing() and self.current and len(self.current) > 2
def mouseDoubleClickEvent(self, ev):
# We need at least 4 points here, since the mousePress handler
# adds an extra one before this handler is called.
if self.canCloseShape() and len(self.current) > 3:
self.current.popPoint()
if self.can_close_shape() and len(self.current) > 3:
self.current.pop_point()
self.finalise()
def selectShape(self, shape):
self.deSelectShape()
def select_shape(self, shape):
self.de_select_shape()
shape.selected = True
self.selectedShape = shape
self.setHiding()
self.selected_shape = shape
self.set_hiding()
self.selectionChanged.emit(True)
self.update()
def selectShapePoint(self, point):
def select_shape_point(self, point):
"""Select the first shape created which contains this point."""
self.deSelectShape()
if self.selectedVertex(): # A vertex is marked for selection.
index, shape = self.hVertex, self.hShape
shape.highlightVertex(index, shape.MOVE_VERTEX)
self.selectShape(shape)
return self.hVertex
self.de_select_shape()
if self.selected_vertex(): # A vertex is marked for selection.
index, shape = self.h_vertex, self.h_shape
shape.highlight_vertex(index, shape.MOVE_VERTEX)
self.select_shape(shape)
return self.h_vertex
for shape in reversed(self.shapes):
if self.isVisible(shape) and shape.containsPoint(point):
self.selectShape(shape)
self.calculateOffsets(shape, point)
return self.selectedShape
if self.isVisible(shape) and shape.contains_point(point):
self.select_shape(shape)
self.calculate_offsets(shape, point)
return self.selected_shape
return None
def calculateOffsets(self, shape, point):
rect = shape.boundingRect()
def calculate_offsets(self, shape, point):
rect = shape.bounding_rect()
x1 = rect.x() - point.x()
y1 = rect.y() - point.y()
x2 = (rect.x() + rect.width()) - point.x()
y2 = (rect.y() + rect.height()) - point.y()
self.offsets = QPointF(x1, y1), QPointF(x2, y2)
def snapPointToCanvas(self, x, y):
def snap_point_to_canvas(self, x, y):
"""
Moves a point x,y to within the boundaries of the canvas.
:return: (x,y,snapped) where snapped is True if x or y were changed, False if not.
@ -370,99 +370,99 @@ class Canvas(QWidget):
return x, y, False
def boundedMoveVertex(self, pos):
index, shape = self.hVertex, self.hShape
def bounded_move_vertex(self, pos):
index, shape = self.h_vertex, self.h_shape
point = shape[index]
if self.outOfPixmap(pos):
if self.out_of_pixmap(pos):
size = self.pixmap.size()
clipped_x = min(max(0, pos.x()), size.width())
clipped_y = min(max(0, pos.y()), size.height())
pos = QPointF(clipped_x, clipped_y)
if self.drawSquare:
if self.draw_square:
opposite_point_index = (index + 2) % 4
opposite_point = shape[opposite_point_index]
min_size = min(abs(pos.x() - opposite_point.x()), abs(pos.y() - opposite_point.y()))
directionX = -1 if pos.x() - opposite_point.x() < 0 else 1
directionY = -1 if pos.y() - opposite_point.y() < 0 else 1
shiftPos = QPointF(opposite_point.x() + directionX * min_size - point.x(),
opposite_point.y() + directionY * min_size - point.y())
direction_x = -1 if pos.x() - opposite_point.x() < 0 else 1
direction_y = -1 if pos.y() - opposite_point.y() < 0 else 1
shift_pos = QPointF(opposite_point.x() + direction_x * min_size - point.x(),
opposite_point.y() + direction_y * min_size - point.y())
else:
shiftPos = pos - point
shift_pos = pos - point
shape.moveVertexBy(index, shiftPos)
shape.move_vertex_by(index, shift_pos)
lindex = (index + 1) % 4
rindex = (index + 3) % 4
lshift = None
rshift = None
left_index = (index + 1) % 4
right_index = (index + 3) % 4
left_shift = None
right_shift = None
if index % 2 == 0:
rshift = QPointF(shiftPos.x(), 0)
lshift = QPointF(0, shiftPos.y())
right_shift = QPointF(shift_pos.x(), 0)
left_shift = QPointF(0, shift_pos.y())
else:
lshift = QPointF(shiftPos.x(), 0)
rshift = QPointF(0, shiftPos.y())
shape.moveVertexBy(rindex, rshift)
shape.moveVertexBy(lindex, lshift)
left_shift = QPointF(shift_pos.x(), 0)
right_shift = QPointF(0, shift_pos.y())
shape.move_vertex_by(right_index, right_shift)
shape.move_vertex_by(left_index, left_shift)
def boundedMoveShape(self, shape, pos):
if self.outOfPixmap(pos):
def bounded_move_shape(self, shape, pos):
if self.out_of_pixmap(pos):
return False # No need to move
o1 = pos + self.offsets[0]
if self.outOfPixmap(o1):
if self.out_of_pixmap(o1):
pos -= QPointF(min(0, o1.x()), min(0, o1.y()))
o2 = pos + self.offsets[1]
if self.outOfPixmap(o2):
if self.out_of_pixmap(o2):
pos += QPointF(min(0, self.pixmap.width() - o2.x()),
min(0, self.pixmap.height() - o2.y()))
# The next line tracks the new position of the cursor
# relative to the shape, but also results in making it
# a bit "shaky" when nearing the border and allows it to
# go outside of the shape's area for some reason. XXX
#self.calculateOffsets(self.selectedShape, pos)
dp = pos - self.prevPoint
# self.calculateOffsets(self.selectedShape, pos)
dp = pos - self.prev_point
if dp:
shape.moveBy(dp)
self.prevPoint = pos
shape.move_by(dp)
self.prev_point = pos
return True
return False
def deSelectShape(self):
if self.selectedShape:
self.selectedShape.selected = False
self.selectedShape = None
self.setHiding(False)
def de_select_shape(self):
if self.selected_shape:
self.selected_shape.selected = False
self.selected_shape = None
self.set_hiding(False)
self.selectionChanged.emit(False)
self.update()
def deleteSelected(self):
if self.selectedShape:
shape = self.selectedShape
self.shapes.remove(self.selectedShape)
self.selectedShape = None
def delete_selected(self):
if self.selected_shape:
shape = self.selected_shape
self.shapes.remove(self.selected_shape)
self.selected_shape = None
self.update()
return shape
def copySelectedShape(self):
if self.selectedShape:
shape = self.selectedShape.copy()
self.deSelectShape()
def copy_selected_shape(self):
if self.selected_shape:
shape = self.selected_shape.copy()
self.de_select_shape()
self.shapes.append(shape)
shape.selected = True
self.selectedShape = shape
self.boundedShiftShape(shape)
self.selected_shape = shape
self.bounded_shift_shape(shape)
return shape
def boundedShiftShape(self, shape):
def bounded_shift_shape(self, shape):
# Try to move in one direction, and if it fails in another.
# Give up if both fail.
point = shape[0]
offset = QPointF(2.0, 2.0)
self.calculateOffsets(shape, point)
self.prevPoint = point
if not self.boundedMoveShape(shape, point - offset):
self.boundedMoveShape(shape, point + offset)
self.calculate_offsets(shape, point)
self.prev_point = point
if not self.bounded_move_shape(shape, point - offset):
self.bounded_move_shape(shape, point + offset)
def paintEvent(self, event):
if not self.pixmap:
@ -475,36 +475,36 @@ class Canvas(QWidget):
p.setRenderHint(QPainter.SmoothPixmapTransform)
p.scale(self.scale, self.scale)
p.translate(self.offsetToCenter())
p.translate(self.offset_to_center())
p.drawPixmap(0, 0, self.pixmap)
Shape.scale = self.scale
Shape.labelFontSize = self.labelFontSize
Shape.label_font_size = self.label_font_size
for shape in self.shapes:
if (shape.selected or not self._hideBackround) and self.isVisible(shape):
shape.fill = shape.selected or shape == self.hShape
if (shape.selected or not self._hide_background) and self.isVisible(shape):
shape.fill = shape.selected or shape == self.h_shape
shape.paint(p)
if self.current:
self.current.paint(p)
self.line.paint(p)
if self.selectedShapeCopy:
self.selectedShapeCopy.paint(p)
if self.selected_shape_copy:
self.selected_shape_copy.paint(p)
# Paint rect
if self.current is not None and len(self.line) == 2:
leftTop = self.line[0]
rightBottom = self.line[1]
rectWidth = rightBottom.x() - leftTop.x()
rectHeight = rightBottom.y() - leftTop.y()
p.setPen(self.drawingRectColor)
left_top = self.line[0]
right_bottom = self.line[1]
rect_width = right_bottom.x() - left_top.x()
rect_height = right_bottom.y() - left_top.y()
p.setPen(self.drawing_rect_color)
brush = QBrush(Qt.BDiagPattern)
p.setBrush(brush)
p.drawRect(leftTop.x(), leftTop.y(), rectWidth, rectHeight)
p.drawRect(left_top.x(), left_top.y(), rect_width, rect_height)
if self.drawing() and not self.prevPoint.isNull() and not self.outOfPixmap(self.prevPoint):
if self.drawing() and not self.prev_point.isNull() and not self.out_of_pixmap(self.prev_point):
p.setPen(QColor(0, 0, 0))
p.drawLine(self.prevPoint.x(), 0, self.prevPoint.x(), self.pixmap.height())
p.drawLine(0, self.prevPoint.y(), self.pixmap.width(), self.prevPoint.y())
p.drawLine(self.prev_point.x(), 0, self.prev_point.x(), self.pixmap.height())
p.drawLine(0, self.prev_point.y(), self.pixmap.width(), self.prev_point.y())
self.setAutoFillBackground(True)
if self.verified:
@ -518,11 +518,11 @@ class Canvas(QWidget):
p.end()
def transformPos(self, point):
def transform_pos(self, point):
"""Convert from widget-logical coordinates to painter-logical coordinates."""
return point / self.scale - self.offsetToCenter()
return point / self.scale - self.offset_to_center()
def offsetToCenter(self):
def offset_to_center(self):
s = self.scale
area = super(Canvas, self).size()
w, h = self.pixmap.width() * s, self.pixmap.height() * s
@ -531,7 +531,7 @@ class Canvas(QWidget):
y = (ah - h) / (2 * s) if ah > h else 0
return QPointF(x, y)
def outOfPixmap(self, p):
def out_of_pixmap(self, p):
w, h = self.pixmap.width(), self.pixmap.height()
return not (0 <= p.x() <= w and 0 <= p.y() <= h)
@ -546,13 +546,13 @@ class Canvas(QWidget):
self.current.close()
self.shapes.append(self.current)
self.current = None
self.setHiding(False)
self.set_hiding(False)
self.newShape.emit()
self.update()
def closeEnough(self, p1, p2):
#d = distance(p1 - p2)
#m = (p1-p2).manhattanLength()
def close_enough(self, p1, p2):
# d = distance(p1 - p2)
# m = (p1-p2).manhattanLength()
# print "d %.2f, m %d, %.2f" % (d, m, d - m)
return distance(p1 - p2) < self.epsilon
@ -595,51 +595,51 @@ class Canvas(QWidget):
self.current = None
self.drawingPolygon.emit(False)
self.update()
elif key == Qt.Key_Return and self.canCloseShape():
elif key == Qt.Key_Return and self.can_close_shape():
self.finalise()
elif key == Qt.Key_Left and self.selectedShape:
self.moveOnePixel('Left')
elif key == Qt.Key_Right and self.selectedShape:
self.moveOnePixel('Right')
elif key == Qt.Key_Up and self.selectedShape:
self.moveOnePixel('Up')
elif key == Qt.Key_Down and self.selectedShape:
self.moveOnePixel('Down')
elif key == Qt.Key_Left and self.selected_shape:
self.move_one_pixel('Left')
elif key == Qt.Key_Right and self.selected_shape:
self.move_one_pixel('Right')
elif key == Qt.Key_Up and self.selected_shape:
self.move_one_pixel('Up')
elif key == Qt.Key_Down and self.selected_shape:
self.move_one_pixel('Down')
def moveOnePixel(self, direction):
def move_one_pixel(self, direction):
# print(self.selectedShape.points)
if direction == 'Left' and not self.moveOutOfBound(QPointF(-1.0, 0)):
if direction == 'Left' and not self.move_out_of_bound(QPointF(-1.0, 0)):
# print("move Left one pixel")
self.selectedShape.points[0] += QPointF(-1.0, 0)
self.selectedShape.points[1] += QPointF(-1.0, 0)
self.selectedShape.points[2] += QPointF(-1.0, 0)
self.selectedShape.points[3] += QPointF(-1.0, 0)
elif direction == 'Right' and not self.moveOutOfBound(QPointF(1.0, 0)):
self.selected_shape.points[0] += QPointF(-1.0, 0)
self.selected_shape.points[1] += QPointF(-1.0, 0)
self.selected_shape.points[2] += QPointF(-1.0, 0)
self.selected_shape.points[3] += QPointF(-1.0, 0)
elif direction == 'Right' and not self.move_out_of_bound(QPointF(1.0, 0)):
# print("move Right one pixel")
self.selectedShape.points[0] += QPointF(1.0, 0)
self.selectedShape.points[1] += QPointF(1.0, 0)
self.selectedShape.points[2] += QPointF(1.0, 0)
self.selectedShape.points[3] += QPointF(1.0, 0)
elif direction == 'Up' and not self.moveOutOfBound(QPointF(0, -1.0)):
self.selected_shape.points[0] += QPointF(1.0, 0)
self.selected_shape.points[1] += QPointF(1.0, 0)
self.selected_shape.points[2] += QPointF(1.0, 0)
self.selected_shape.points[3] += QPointF(1.0, 0)
elif direction == 'Up' and not self.move_out_of_bound(QPointF(0, -1.0)):
# print("move Up one pixel")
self.selectedShape.points[0] += QPointF(0, -1.0)
self.selectedShape.points[1] += QPointF(0, -1.0)
self.selectedShape.points[2] += QPointF(0, -1.0)
self.selectedShape.points[3] += QPointF(0, -1.0)
elif direction == 'Down' and not self.moveOutOfBound(QPointF(0, 1.0)):
self.selected_shape.points[0] += QPointF(0, -1.0)
self.selected_shape.points[1] += QPointF(0, -1.0)
self.selected_shape.points[2] += QPointF(0, -1.0)
self.selected_shape.points[3] += QPointF(0, -1.0)
elif direction == 'Down' and not self.move_out_of_bound(QPointF(0, 1.0)):
# print("move Down one pixel")
self.selectedShape.points[0] += QPointF(0, 1.0)
self.selectedShape.points[1] += QPointF(0, 1.0)
self.selectedShape.points[2] += QPointF(0, 1.0)
self.selectedShape.points[3] += QPointF(0, 1.0)
self.selected_shape.points[0] += QPointF(0, 1.0)
self.selected_shape.points[1] += QPointF(0, 1.0)
self.selected_shape.points[2] += QPointF(0, 1.0)
self.selected_shape.points[3] += QPointF(0, 1.0)
self.shapeMoved.emit()
self.repaint()
def moveOutOfBound(self, step):
points = [p1+p2 for p1, p2 in zip(self.selectedShape.points, [step]*4)]
return True in map(self.outOfPixmap, points)
def move_out_of_bound(self, step):
points = [p1 + p2 for p1, p2 in zip(self.selected_shape.points, [step] * 4)]
return True in map(self.out_of_pixmap, points)
def setLastLabel(self, text, line_color = None, fill_color = None):
def set_last_label(self, text, line_color=None, fill_color=None):
assert text
self.shapes[-1].label = text
if line_color:
@ -650,57 +650,57 @@ class Canvas(QWidget):
return self.shapes[-1]
def undoLastLine(self):
def undo_last_line(self):
assert self.shapes
self.current = self.shapes.pop()
self.current.setOpen()
self.current.set_open()
self.line.points = [self.current[-1], self.current[0]]
self.drawingPolygon.emit(True)
def resetAllLines(self):
def reset_all_lines(self):
assert self.shapes
self.current = self.shapes.pop()
self.current.setOpen()
self.current.set_open()
self.line.points = [self.current[-1], self.current[0]]
self.drawingPolygon.emit(True)
self.current = None
self.drawingPolygon.emit(False)
self.update()
def loadPixmap(self, pixmap):
def load_pixmap(self, pixmap):
self.pixmap = pixmap
self.shapes = []
self.repaint()
def loadShapes(self, shapes):
def load_shapes(self, shapes):
self.shapes = list(shapes)
self.current = None
self.repaint()
def setShapeVisible(self, shape, value):
def set_shape_visible(self, shape, value):
self.visible[shape] = value
self.repaint()
def currentCursor(self):
def current_cursor(self):
cursor = QApplication.overrideCursor()
if cursor is not None:
cursor = cursor.shape()
return cursor
def overrideCursor(self, cursor):
def override_cursor(self, cursor):
self._cursor = cursor
if self.currentCursor() is None:
if self.current_cursor() is None:
QApplication.setOverrideCursor(cursor)
else:
QApplication.changeOverrideCursor(cursor)
def restoreCursor(self):
def restore_cursor(self):
QApplication.restoreOverrideCursor()
def resetState(self):
self.restoreCursor()
def reset_state(self):
self.restore_cursor()
self.pixmap = None
self.update()
def setDrawingShapeToSquare(self, status):
self.drawSquare = status
def set_drawing_shape_to_square(self, status):
self.draw_square = status

View File

@ -22,7 +22,7 @@ class ColorDialog(QColorDialog):
self.default = None
self.bb = self.layout().itemAt(1).widget()
self.bb.addButton(BB.RestoreDefaults)
self.bb.clicked.connect(self.checkRestore)
self.bb.clicked.connect(self.check_restore)
def getColor(self, value=None, title=None, default=None):
self.default = default
@ -32,6 +32,6 @@ class ColorDialog(QColorDialog):
self.setCurrentColor(value)
return self.currentColor() if self.exec_() else None
def checkRestore(self, button):
def check_restore(self, button):
if self.bb.buttonRole(button) & BB.ResetRole and self.default:
self.setCurrentColor(self.default)

View File

@ -21,7 +21,7 @@ class ComboBox(QWidget):
self.items = items
self.cb.addItems(self.items)
self.cb.currentIndexChanged.connect(parent.comboSelectionChanged)
self.cb.currentIndexChanged.connect(parent.combo_selection_changed)
layout.addWidget(self.cb)
self.setLayout(layout)

View File

@ -11,26 +11,26 @@ ENCODE_METHOD = DEFAULT_ENCODING
class CreateMLWriter:
def __init__(self, foldername, filename, imgsize, shapes, outputfile, databasesrc='Unknown', localimgpath=None):
self.foldername = foldername
def __init__(self, folder_name, filename, img_size, shapes, output_file, database_src='Unknown', local_img_path=None):
self.folder_name = folder_name
self.filename = filename
self.databasesrc = databasesrc
self.imgsize = imgsize
self.boxlist = []
self.localimgpath = localimgpath
self.database_src = database_src
self.img_size = img_size
self.box_list = []
self.local_img_path = local_img_path
self.verified = False
self.shapes = shapes
self.outputfile = outputfile
self.output_file = output_file
def write(self):
if os.path.isfile(self.outputfile):
with open(self.outputfile, "r") as file:
if os.path.isfile(self.output_file):
with open(self.output_file, "r") as file:
input_data = file.read()
outputdict = json.loads(input_data)
output_dict = json.loads(input_data)
else:
outputdict = []
output_dict = []
outputimagedict = {
output_image_dict = {
"image": self.filename,
"annotations": []
}
@ -45,7 +45,7 @@ class CreateMLWriter:
height, width, x, y = self.calculate_coordinates(x1, x2, y1, y2)
shapedict = {
shape_dict = {
"label": shape["label"],
"coordinates": {
"x": x,
@ -54,77 +54,77 @@ class CreateMLWriter:
"height": height
}
}
outputimagedict["annotations"].append(shapedict)
output_image_dict["annotations"].append(shape_dict)
# check if image already in output
exists = False
for i in range(0, len(outputdict)):
if outputdict[i]["image"] == outputimagedict["image"]:
for i in range(0, len(output_dict)):
if output_dict[i]["image"] == output_image_dict["image"]:
exists = True
outputdict[i] = outputimagedict
output_dict[i] = output_image_dict
break
if not exists:
outputdict.append(outputimagedict)
output_dict.append(output_image_dict)
Path(self.outputfile).write_text(json.dumps(outputdict), ENCODE_METHOD)
Path(self.output_file).write_text(json.dumps(output_dict), ENCODE_METHOD)
def calculate_coordinates(self, x1, x2, y1, y2):
if x1 < x2:
xmin = x1
xmax = x2
x_min = x1
x_max = x2
else:
xmin = x2
xmax = x1
x_min = x2
x_max = x1
if y1 < y2:
ymin = y1
ymax = y2
y_min = y1
y_max = y2
else:
ymin = y2
ymax = y1
width = xmax - xmin
y_min = y2
y_max = y1
width = x_max - x_min
if width < 0:
width = width * -1
height = ymax - ymin
height = y_max - y_min
# x and y from center of rect
x = xmin + width / 2
y = ymin + height / 2
x = x_min + width / 2
y = y_min + height / 2
return height, width, x, y
class CreateMLReader:
def __init__(self, jsonpath, filepath):
self.jsonpath = jsonpath
def __init__(self, json_path, file_path):
self.json_path = json_path
self.shapes = []
self.verified = False
self.filename = filepath.split("/")[-1:][0]
self.filename = file_path.split("/")[-1:][0]
try:
self.parse_json()
except ValueError:
print("JSON decoding failed")
def parse_json(self):
with open(self.jsonpath, "r") as file:
inputdata = file.read()
with open(self.json_path, "r") as file:
input_data = file.read()
outputdict = json.loads(inputdata)
output_dict = json.loads(input_data)
self.verified = True
if len(self.shapes) > 0:
self.shapes = []
for image in outputdict:
for image in output_dict:
if image["image"] == self.filename:
for shape in image["annotations"]:
self.add_shape(shape["label"], shape["coordinates"])
def add_shape(self, label, bndbox):
xmin = bndbox["x"] - (bndbox["width"] / 2)
ymin = bndbox["y"] - (bndbox["height"] / 2)
def add_shape(self, label, bnd_box):
x_min = bnd_box["x"] - (bnd_box["width"] / 2)
y_min = bnd_box["y"] - (bnd_box["height"] / 2)
xmax = bndbox["x"] + (bndbox["width"] / 2)
ymax = bndbox["y"] + (bndbox["height"] / 2)
x_max = bnd_box["x"] + (bnd_box["width"] / 2)
y_max = bnd_box["y"] + (bnd_box["height"] / 2)
points = [(xmin, ymin), (xmax, ymin), (xmax, ymax), (xmin, ymax)]
points = [(x_min, y_min), (x_max, y_min), (x_max, y_max), (x_min, y_max)]
self.shapes.append((label, points, None, None, True))
def get_shapes(self):

View File

@ -6,43 +6,43 @@ except ImportError:
from PyQt4.QtGui import *
from PyQt4.QtCore import *
from libs.utils import newIcon, labelValidator
from libs.utils import new_icon, label_validator
BB = QDialogButtonBox
class LabelDialog(QDialog):
def __init__(self, text="Enter object label", parent=None, listItem=None):
def __init__(self, text="Enter object label", parent=None, list_item=None):
super(LabelDialog, self).__init__(parent)
self.edit = QLineEdit()
self.edit.setText(text)
self.edit.setValidator(labelValidator())
self.edit.editingFinished.connect(self.postProcess)
self.edit.setValidator(label_validator())
self.edit.editingFinished.connect(self.post_process)
model = QStringListModel()
model.setStringList(listItem)
model.setStringList(list_item)
completer = QCompleter()
completer.setModel(model)
self.edit.setCompleter(completer)
layout = QVBoxLayout()
layout.addWidget(self.edit)
self.buttonBox = bb = BB(BB.Ok | BB.Cancel, Qt.Horizontal, self)
bb.button(BB.Ok).setIcon(newIcon('done'))
bb.button(BB.Cancel).setIcon(newIcon('undo'))
self.button_box = bb = BB(BB.Ok | BB.Cancel, Qt.Horizontal, self)
bb.button(BB.Ok).setIcon(new_icon('done'))
bb.button(BB.Cancel).setIcon(new_icon('undo'))
bb.accepted.connect(self.validate)
bb.rejected.connect(self.reject)
layout.addWidget(bb)
if listItem is not None and len(listItem) > 0:
self.listWidget = QListWidget(self)
for item in listItem:
self.listWidget.addItem(item)
self.listWidget.itemClicked.connect(self.listItemClick)
self.listWidget.itemDoubleClicked.connect(self.listItemDoubleClick)
layout.addWidget(self.listWidget)
if list_item is not None and len(list_item) > 0:
self.list_widget = QListWidget(self)
for item in list_item:
self.list_widget.addItem(item)
self.list_widget.itemClicked.connect(self.list_item_click)
self.list_widget.itemDoubleClicked.connect(self.list_item_double_click)
layout.addWidget(self.list_widget)
self.setLayout(layout)
@ -55,22 +55,22 @@ class LabelDialog(QDialog):
if self.edit.text().strip():
self.accept()
def postProcess(self):
def post_process(self):
try:
self.edit.setText(self.edit.text().trimmed())
except AttributeError:
# PyQt5: AttributeError: 'str' object has no attribute 'trimmed'
self.edit.setText(self.edit.text())
def popUp(self, text='', move=True):
def pop_up(self, text='', move=True):
self.edit.setText(text)
self.edit.setSelection(0, len(text))
self.edit.setFocus(Qt.PopupFocusReason)
if move:
cursor_pos = QCursor.pos()
parent_bottomRight = self.parentWidget().geometry()
max_x = parent_bottomRight.x() + parent_bottomRight.width() - self.sizeHint().width()
max_y = parent_bottomRight.y() + parent_bottomRight.height() - self.sizeHint().height()
parent_bottom_right = self.parentWidget().geometry()
max_x = parent_bottom_right.x() + parent_bottom_right.width() - self.sizeHint().width()
max_y = parent_bottom_right.y() + parent_bottom_right.height() - self.sizeHint().height()
max_global = self.parentWidget().mapToGlobal(QPoint(max_x, max_y))
if cursor_pos.x() > max_global.x():
cursor_pos.setX(max_global.x())
@ -79,14 +79,14 @@ class LabelDialog(QDialog):
self.move(cursor_pos)
return self.edit.text() if self.exec_() else None
def listItemClick(self, tQListWidgetItem):
def list_item_click(self, t_qlist_widget_item):
try:
text = tQListWidgetItem.text().trimmed()
text = t_qlist_widget_item.text().trimmed()
except AttributeError:
# PyQt5: AttributeError: 'str' object has no attribute 'trimmed'
text = tQListWidgetItem.text().strip()
text = t_qlist_widget_item.text().strip()
self.edit.setText(text)
def listItemDoubleClick(self, tQListWidgetItem):
self.listItemClick(tQListWidgetItem)
def list_item_double_click(self, t_qlist_widget_item):
self.list_item_click(t_qlist_widget_item)
self.validate()

View File

@ -18,7 +18,7 @@ import sys
class LabelFileFormat(Enum):
PASCAL_VOC= 1
PASCAL_VOC = 1
YOLO = 2
CREATE_ML = 3
@ -34,44 +34,44 @@ class LabelFile(object):
def __init__(self, filename=None):
self.shapes = ()
self.imagePath = None
self.imageData = None
self.image_path = None
self.image_data = None
self.verified = False
def saveCreateMLFormat(self, filename, shapes, imagePath, imageData, classList, lineColor=None, fillColor=None, databaseSrc=None):
imgFolderPath = os.path.dirname(imagePath)
imgFolderName = os.path.split(imgFolderPath)[-1]
imgFileName = os.path.basename(imagePath)
outputFilePath = "/".join(filename.split("/")[:-1])
outputFile = outputFilePath + "/" + imgFolderName + JSON_EXT
def save_create_ml_format(self, filename, shapes, image_path, image_data, class_list, line_color=None, fill_color=None, database_src=None):
img_folder_path = os.path.dirname(image_path)
img_folder_name = os.path.split(img_folder_path)[-1]
img_file_name = os.path.basename(image_path)
output_file_path = "/".join(filename.split("/")[:-1])
output_file = output_file_path + "/" + img_folder_name + JSON_EXT
image = QImage()
image.load(imagePath)
imageShape = [image.height(), image.width(),
image.load(image_path)
image_shape = [image.height(), image.width(),
1 if image.isGrayscale() else 3]
writer = CreateMLWriter(imgFolderName, imgFileName,
imageShape, shapes, outputFile, localimgpath=imagePath)
writer = CreateMLWriter(img_folder_name, img_file_name,
image_shape, shapes, output_file, local_img_path=image_path)
writer.verified = self.verified
writer.write()
def savePascalVocFormat(self, filename, shapes, imagePath, imageData,
lineColor=None, fillColor=None, databaseSrc=None):
imgFolderPath = os.path.dirname(imagePath)
imgFolderName = os.path.split(imgFolderPath)[-1]
imgFileName = os.path.basename(imagePath)
#imgFileNameWithoutExt = os.path.splitext(imgFileName)[0]
def save_pascal_voc_format(self, filename, shapes, image_path, image_data,
line_color=None, fill_color=None, database_src=None):
img_folder_path = os.path.dirname(image_path)
img_folder_name = os.path.split(img_folder_path)[-1]
img_file_name = os.path.basename(image_path)
# imgFileNameWithoutExt = os.path.splitext(img_file_name)[0]
# Read from file path because self.imageData might be empty if saving to
# Pascal format
if isinstance(imageData, QImage):
image = imageData
if isinstance(image_data, QImage):
image = image_data
else:
image = QImage()
image.load(imagePath)
imageShape = [image.height(), image.width(),
image.load(image_path)
image_shape = [image.height(), image.width(),
1 if image.isGrayscale() else 3]
writer = PascalVocWriter(imgFolderName, imgFileName,
imageShape, localImgPath=imagePath)
writer = PascalVocWriter(img_folder_name, img_file_name,
image_shape, local_img_path=image_path)
writer.verified = self.verified
for shape in shapes:
@ -79,29 +79,29 @@ class LabelFile(object):
label = shape['label']
# Add Chris
difficult = int(shape['difficult'])
bndbox = LabelFile.convertPoints2BndBox(points)
writer.addBndBox(bndbox[0], bndbox[1], bndbox[2], bndbox[3], label, difficult)
bnd_box = LabelFile.convert_points_to_bnd_box(points)
writer.add_bnd_box(bnd_box[0], bnd_box[1], bnd_box[2], bnd_box[3], label, difficult)
writer.save(targetFile=filename)
writer.save(target_file=filename)
return
def saveYoloFormat(self, filename, shapes, imagePath, imageData, classList,
lineColor=None, fillColor=None, databaseSrc=None):
imgFolderPath = os.path.dirname(imagePath)
imgFolderName = os.path.split(imgFolderPath)[-1]
imgFileName = os.path.basename(imagePath)
#imgFileNameWithoutExt = os.path.splitext(imgFileName)[0]
def save_yolo_format(self, filename, shapes, image_path, image_data, class_list,
line_color=None, fill_color=None, database_src=None):
img_folder_path = os.path.dirname(image_path)
img_folder_name = os.path.split(img_folder_path)[-1]
img_file_name = os.path.basename(image_path)
# imgFileNameWithoutExt = os.path.splitext(img_file_name)[0]
# Read from file path because self.imageData might be empty if saving to
# Pascal format
if isinstance(imageData, QImage):
image = imageData
if isinstance(image_data, QImage):
image = image_data
else:
image = QImage()
image.load(imagePath)
imageShape = [image.height(), image.width(),
image.load(image_path)
image_shape = [image.height(), image.width(),
1 if image.isGrayscale() else 3]
writer = YOLOWriter(imgFolderName, imgFileName,
imageShape, localImgPath=imagePath)
writer = YOLOWriter(img_folder_name, img_file_name,
image_shape, local_img_path=image_path)
writer.verified = self.verified
for shape in shapes:
@ -109,13 +109,13 @@ class LabelFile(object):
label = shape['label']
# Add Chris
difficult = int(shape['difficult'])
bndbox = LabelFile.convertPoints2BndBox(points)
writer.addBndBox(bndbox[0], bndbox[1], bndbox[2], bndbox[3], label, difficult)
bnd_box = LabelFile.convert_points_to_bnd_box(points)
writer.add_bnd_box(bnd_box[0], bnd_box[1], bnd_box[2], bnd_box[3], label, difficult)
writer.save(targetFile=filename, classList=classList)
writer.save(target_file=filename, class_list=class_list)
return
def toggleVerify(self):
def toggle_verify(self):
self.verified = not self.verified
''' ttf is disable
@ -148,31 +148,31 @@ class LabelFile(object):
'''
@staticmethod
def isLabelFile(filename):
fileSuffix = os.path.splitext(filename)[1].lower()
return fileSuffix == LabelFile.suffix
def is_label_file(filename):
file_suffix = os.path.splitext(filename)[1].lower()
return file_suffix == LabelFile.suffix
@staticmethod
def convertPoints2BndBox(points):
xmin = float('inf')
ymin = float('inf')
xmax = float('-inf')
ymax = float('-inf')
def convert_points_to_bnd_box(points):
x_min = float('inf')
y_min = float('inf')
x_max = float('-inf')
y_max = float('-inf')
for p in points:
x = p[0]
y = p[1]
xmin = min(x, xmin)
ymin = min(y, ymin)
xmax = max(x, xmax)
ymax = max(y, ymax)
x_min = min(x, x_min)
y_min = min(y, y_min)
x_max = max(x, x_max)
y_max = max(y, y_max)
# Martin Kersner, 2015/11/12
# 0-valued coordinates of BB caused an error while
# training faster-rcnn object detector.
if xmin < 1:
xmin = 1
if x_min < 1:
x_min = 1
if ymin < 1:
ymin = 1
if y_min < 1:
y_min = 1
return (int(xmin), int(ymin), int(xmax), int(ymax))
return int(x_min), int(y_min), int(x_max), int(y_max)

View File

@ -14,13 +14,13 @@ ENCODE_METHOD = DEFAULT_ENCODING
class PascalVocWriter:
def __init__(self, foldername, filename, imgSize,databaseSrc='Unknown', localImgPath=None):
self.foldername = foldername
def __init__(self, folder_name, filename, img_size, database_src='Unknown', local_img_path=None):
self.folder_name = folder_name
self.filename = filename
self.databaseSrc = databaseSrc
self.imgSize = imgSize
self.boxlist = []
self.localImgPath = localImgPath
self.database_src = database_src
self.img_size = img_size
self.box_list = []
self.local_img_path = local_img_path
self.verified = False
def prettify(self, elem):
@ -31,17 +31,17 @@ class PascalVocWriter:
root = etree.fromstring(rough_string)
return etree.tostring(root, pretty_print=True, encoding=ENCODE_METHOD).replace(" ".encode(), "\t".encode())
# minidom does not support UTF-8
'''reparsed = minidom.parseString(rough_string)
return reparsed.toprettyxml(indent="\t", encoding=ENCODE_METHOD)'''
# reparsed = minidom.parseString(rough_string)
# return reparsed.toprettyxml(indent="\t", encoding=ENCODE_METHOD)
def genXML(self):
def gen_xml(self):
"""
Return XML root
"""
# Check conditions
if self.filename is None or \
self.foldername is None or \
self.imgSize is None:
self.folder_name is None or \
self.img_size is None:
return None
top = Element('annotation')
@ -49,27 +49,27 @@ class PascalVocWriter:
top.set('verified', 'yes')
folder = SubElement(top, 'folder')
folder.text = self.foldername
folder.text = self.folder_name
filename = SubElement(top, 'filename')
filename.text = self.filename
if self.localImgPath is not None:
localImgPath = SubElement(top, 'path')
localImgPath.text = self.localImgPath
if self.local_img_path is not None:
local_img_path = SubElement(top, 'path')
local_img_path.text = self.local_img_path
source = SubElement(top, 'source')
database = SubElement(source, 'database')
database.text = self.databaseSrc
database.text = self.database_src
size_part = SubElement(top, 'size')
width = SubElement(size_part, 'width')
height = SubElement(size_part, 'height')
depth = SubElement(size_part, 'depth')
width.text = str(self.imgSize[1])
height.text = str(self.imgSize[0])
if len(self.imgSize) == 3:
depth.text = str(self.imgSize[2])
width.text = str(self.img_size[1])
height.text = str(self.img_size[0])
if len(self.img_size) == 3:
depth.text = str(self.img_size[2])
else:
depth.text = '1'
@ -77,95 +77,95 @@ class PascalVocWriter:
segmented.text = '0'
return top
def addBndBox(self, xmin, ymin, xmax, ymax, name, difficult):
bndbox = {'xmin': xmin, 'ymin': ymin, 'xmax': xmax, 'ymax': ymax}
bndbox['name'] = name
bndbox['difficult'] = difficult
self.boxlist.append(bndbox)
def add_bnd_box(self, x_min, y_min, x_max, y_max, name, difficult):
bnd_box = {'xmin': x_min, 'ymin': y_min, 'xmax': x_max, 'ymax': y_max}
bnd_box['name'] = name
bnd_box['difficult'] = difficult
self.box_list.append(bnd_box)
def appendObjects(self, top):
for each_object in self.boxlist:
def append_objects(self, top):
for each_object in self.box_list:
object_item = SubElement(top, 'object')
name = SubElement(object_item, 'name')
name.text = ustr(each_object['name'])
pose = SubElement(object_item, 'pose')
pose.text = "Unspecified"
truncated = SubElement(object_item, 'truncated')
if int(float(each_object['ymax'])) == int(float(self.imgSize[0])) or (int(float(each_object['ymin']))== 1):
if int(float(each_object['ymax'])) == int(float(self.img_size[0])) or (int(float(each_object['ymin'])) == 1):
truncated.text = "1" # max == height or min
elif (int(float(each_object['xmax']))==int(float(self.imgSize[1]))) or (int(float(each_object['xmin']))== 1):
elif (int(float(each_object['xmax'])) == int(float(self.img_size[1]))) or (int(float(each_object['xmin'])) == 1):
truncated.text = "1" # max == width or min
else:
truncated.text = "0"
difficult = SubElement(object_item, 'difficult')
difficult.text = str( bool(each_object['difficult']) & 1 )
bndbox = SubElement(object_item, 'bndbox')
xmin = SubElement(bndbox, 'xmin')
xmin.text = str(each_object['xmin'])
ymin = SubElement(bndbox, 'ymin')
ymin.text = str(each_object['ymin'])
xmax = SubElement(bndbox, 'xmax')
xmax.text = str(each_object['xmax'])
ymax = SubElement(bndbox, 'ymax')
ymax.text = str(each_object['ymax'])
difficult.text = str(bool(each_object['difficult']) & 1)
bnd_box = SubElement(object_item, 'bndbox')
x_min = SubElement(bnd_box, 'xmin')
x_min.text = str(each_object['xmin'])
y_min = SubElement(bnd_box, 'ymin')
y_min.text = str(each_object['ymin'])
x_max = SubElement(bnd_box, 'xmax')
x_max.text = str(each_object['xmax'])
y_max = SubElement(bnd_box, 'ymax')
y_max.text = str(each_object['ymax'])
def save(self, targetFile=None):
root = self.genXML()
self.appendObjects(root)
def save(self, target_file=None):
root = self.gen_xml()
self.append_objects(root)
out_file = None
if targetFile is None:
if target_file is None:
out_file = codecs.open(
self.filename + XML_EXT, 'w', encoding=ENCODE_METHOD)
else:
out_file = codecs.open(targetFile, 'w', encoding=ENCODE_METHOD)
out_file = codecs.open(target_file, 'w', encoding=ENCODE_METHOD)
prettifyResult = self.prettify(root)
out_file.write(prettifyResult.decode('utf8'))
prettify_result = self.prettify(root)
out_file.write(prettify_result.decode('utf8'))
out_file.close()
class PascalVocReader:
def __init__(self, filepath):
def __init__(self, file_path):
# shapes type:
# [labbel, [(x1,y1), (x2,y2), (x3,y3), (x4,y4)], color, color, difficult]
self.shapes = []
self.filepath = filepath
self.file_path = file_path
self.verified = False
try:
self.parseXML()
self.parse_xml()
except:
pass
def getShapes(self):
def get_shapes(self):
return self.shapes
def addShape(self, label, bndbox, difficult):
xmin = int(float(bndbox.find('xmin').text))
ymin = int(float(bndbox.find('ymin').text))
xmax = int(float(bndbox.find('xmax').text))
ymax = int(float(bndbox.find('ymax').text))
points = [(xmin, ymin), (xmax, ymin), (xmax, ymax), (xmin, ymax)]
def add_shape(self, label, bnd_box, difficult):
x_min = int(float(bnd_box.find('xmin').text))
y_min = int(float(bnd_box.find('ymin').text))
x_max = int(float(bnd_box.find('xmax').text))
y_max = int(float(bnd_box.find('ymax').text))
points = [(x_min, y_min), (x_max, y_min), (x_max, y_max), (x_min, y_max)]
self.shapes.append((label, points, None, None, difficult))
def parseXML(self):
assert self.filepath.endswith(XML_EXT), "Unsupport file format"
def parse_xml(self):
assert self.file_path.endswith(XML_EXT), "Unsupported file format"
parser = etree.XMLParser(encoding=ENCODE_METHOD)
xmltree = ElementTree.parse(self.filepath, parser=parser).getroot()
filename = xmltree.find('filename').text
xml_tree = ElementTree.parse(self.file_path, parser=parser).getroot()
filename = xml_tree.find('filename').text
try:
verified = xmltree.attrib['verified']
verified = xml_tree.attrib['verified']
if verified == 'yes':
self.verified = True
except KeyError:
self.verified = False
for object_iter in xmltree.findall('object'):
bndbox = object_iter.find("bndbox")
for object_iter in xml_tree.findall('object'):
bnd_box = object_iter.find("bndbox")
label = object_iter.find('name').text
# Add chris
difficult = False
if object_iter.find('difficult') is not None:
difficult = bool(int(object_iter.find('difficult').text))
self.addShape(label, bndbox, difficult)
self.add_shape(label, bnd_box, difficult)
return True

View File

@ -32,23 +32,23 @@ class Shape(object):
select_line_color = DEFAULT_SELECT_LINE_COLOR
select_fill_color = DEFAULT_SELECT_FILL_COLOR
vertex_fill_color = DEFAULT_VERTEX_FILL_COLOR
hvertex_fill_color = DEFAULT_HVERTEX_FILL_COLOR
h_vertex_fill_color = DEFAULT_HVERTEX_FILL_COLOR
point_type = P_ROUND
point_size = 8
scale = 1.0
labelFontSize = 8
label_font_size = 8
def __init__(self, label=None, line_color=None, difficult=False, paintLabel=False):
def __init__(self, label=None, line_color=None, difficult=False, paint_label=False):
self.label = label
self.points = []
self.fill = False
self.selected = False
self.difficult = difficult
self.paintLabel = paintLabel
self.paint_label = paint_label
self._highlightIndex = None
self._highlightMode = self.NEAR_VERTEX
self._highlightSettings = {
self._highlight_index = None
self._highlight_mode = self.NEAR_VERTEX
self._highlight_settings = {
self.NEAR_VERTEX: (4, self.P_ROUND),
self.MOVE_VERTEX: (1.5, self.P_SQUARE),
}
@ -64,24 +64,24 @@ class Shape(object):
def close(self):
self._closed = True
def reachMaxPoints(self):
def reach_max_points(self):
if len(self.points) >= 4:
return True
return False
def addPoint(self, point):
if not self.reachMaxPoints():
def add_point(self, point):
if not self.reach_max_points():
self.points.append(point)
def popPoint(self):
def pop_point(self):
if self.points:
return self.points.pop()
return None
def isClosed(self):
def is_closed(self):
return self._closed
def setOpen(self):
def set_open(self):
self._closed = False
def paint(self, painter):
@ -93,40 +93,40 @@ class Shape(object):
painter.setPen(pen)
line_path = QPainterPath()
vrtx_path = QPainterPath()
vertex_path = QPainterPath()
line_path.moveTo(self.points[0])
# Uncommenting the following line will draw 2 paths
# for the 1st vertex, and make it non-filled, which
# may be desirable.
#self.drawVertex(vrtx_path, 0)
# self.drawVertex(vertex_path, 0)
for i, p in enumerate(self.points):
line_path.lineTo(p)
self.drawVertex(vrtx_path, i)
if self.isClosed():
self.draw_vertex(vertex_path, i)
if self.is_closed():
line_path.lineTo(self.points[0])
painter.drawPath(line_path)
painter.drawPath(vrtx_path)
painter.fillPath(vrtx_path, self.vertex_fill_color)
painter.drawPath(vertex_path)
painter.fillPath(vertex_path, self.vertex_fill_color)
# Draw text at the top-left
if self.paintLabel:
if self.paint_label:
min_x = sys.maxsize
min_y = sys.maxsize
min_y_label = int(1.25 * self.labelFontSize)
min_y_label = int(1.25 * self.label_font_size)
for point in self.points:
min_x = min(min_x, point.x())
min_y = min(min_y, point.y())
if min_x != sys.maxsize and min_y != sys.maxsize:
font = QFont()
font.setPointSize(self.labelFontSize)
font.setPointSize(self.label_font_size)
font.setBold(True)
painter.setFont(font)
if(self.label == None):
if self.label is None:
self.label = ""
if(min_y < min_y_label):
if min_y < min_y_label:
min_y += min_y_label
painter.drawText(min_x, min_y, self.label)
@ -134,15 +134,15 @@ class Shape(object):
color = self.select_fill_color if self.selected else self.fill_color
painter.fillPath(line_path, color)
def drawVertex(self, path, i):
def draw_vertex(self, path, i):
d = self.point_size / self.scale
shape = self.point_type
point = self.points[i]
if i == self._highlightIndex:
size, shape = self._highlightSettings[self._highlightMode]
if i == self._highlight_index:
size, shape = self._highlight_settings[self._highlight_mode]
d *= size
if self._highlightIndex is not None:
self.vertex_fill_color = self.hvertex_fill_color
if self._highlight_index is not None:
self.vertex_fill_color = self.h_vertex_fill_color
else:
self.vertex_fill_color = Shape.vertex_fill_color
if shape == self.P_SQUARE:
@ -152,36 +152,36 @@ class Shape(object):
else:
assert False, "unsupported vertex shape"
def nearestVertex(self, point, epsilon):
def nearest_vertex(self, point, epsilon):
for i, p in enumerate(self.points):
if distance(p - point) <= epsilon:
return i
return None
def containsPoint(self, point):
return self.makePath().contains(point)
def contains_point(self, point):
return self.make_path().contains(point)
def makePath(self):
def make_path(self):
path = QPainterPath(self.points[0])
for p in self.points[1:]:
path.lineTo(p)
return path
def boundingRect(self):
return self.makePath().boundingRect()
def bounding_rect(self):
return self.make_path().boundingRect()
def moveBy(self, offset):
def move_by(self, offset):
self.points = [p + offset for p in self.points]
def moveVertexBy(self, i, offset):
def move_vertex_by(self, i, offset):
self.points[i] = self.points[i] + offset
def highlightVertex(self, i, action):
self._highlightIndex = i
self._highlightMode = action
def highlight_vertex(self, i, action):
self._highlight_index = i
self._highlight_mode = action
def highlightClear(self):
self._highlightIndex = None
def highlight_clear(self):
self._highlight_index = None
def copy(self):
shape = Shape("%s" % self.label)

View File

@ -19,43 +19,43 @@ class StringBundle:
__create_key = object()
def __init__(self, create_key, localeStr):
def __init__(self, create_key, locale_str):
assert(create_key == StringBundle.__create_key), "StringBundle must be created using StringBundle.getBundle"
self.idToMessage = {}
paths = self.__createLookupFallbackList(localeStr)
self.id_to_message = {}
paths = self.__create_lookup_fallback_list(locale_str)
for path in paths:
self.__loadBundle(path)
self.__load_bundle(path)
@classmethod
def getBundle(cls, localeStr=None):
if localeStr is None:
def get_bundle(cls, locale_str=None):
if locale_str is None:
try:
localeStr = locale.getlocale()[0] if locale.getlocale() and len(
locale_str = locale.getlocale()[0] if locale.getlocale() and len(
locale.getlocale()) > 0 else os.getenv('LANG')
except:
print('Invalid locale')
localeStr = 'en'
locale_str = 'en'
return StringBundle(cls.__create_key, localeStr)
return StringBundle(cls.__create_key, locale_str)
def getString(self, stringId):
assert(stringId in self.idToMessage), "Missing string id : " + stringId
return self.idToMessage[stringId]
def get_string(self, string_id):
assert(string_id in self.id_to_message), "Missing string id : " + string_id
return self.id_to_message[string_id]
def __createLookupFallbackList(self, localeStr):
resultPaths = []
basePath = ":/strings"
resultPaths.append(basePath)
if localeStr is not None:
def __create_lookup_fallback_list(self, locale_str):
result_paths = []
base_path = ":/strings"
result_paths.append(base_path)
if locale_str is not None:
# Don't follow standard BCP47. Simple fallback
tags = re.split('[^a-zA-Z]', localeStr)
tags = re.split('[^a-zA-Z]', locale_str)
for tag in tags:
lastPath = resultPaths[-1]
resultPaths.append(lastPath + '-' + tag)
last_path = result_paths[-1]
result_paths.append(last_path + '-' + tag)
return resultPaths
return result_paths
def __loadBundle(self, path):
def __load_bundle(self, path):
PROP_SEPERATOR = '='
f = QFile(path)
if f.exists():
@ -68,6 +68,6 @@ class StringBundle:
key_value = line.split(PROP_SEPERATOR)
key = key_value[0].strip()
value = PROP_SEPERATOR.join(key_value[1:]).strip().strip('"')
self.idToMessage[key] = value
self.id_to_message[key] = value
f.close()

View File

@ -2,15 +2,15 @@ import sys
from libs.constants import DEFAULT_ENCODING
def ustr(x):
'''py2/py3 unicode helper'''
"""py2/py3 unicode helper"""
if sys.version_info < (3, 0, 0):
from PyQt4.QtCore import QString
if type(x) == str:
return x.decode(DEFAULT_ENCODING)
if type(x) == QString:
#https://blog.csdn.net/friendan/article/details/51088476
#https://blog.csdn.net/xxm524/article/details/74937308
# https://blog.csdn.net/friendan/article/details/51088476
# https://blog.csdn.net/xxm524/article/details/74937308
return unicode(x.toUtf8(), DEFAULT_ENCODING, 'ignore')
return x
else:

View File

@ -13,25 +13,25 @@ except ImportError:
from PyQt4.QtCore import *
def newIcon(icon):
def new_icon(icon):
return QIcon(':/' + icon)
def newButton(text, icon=None, slot=None):
def new_button(text, icon=None, slot=None):
b = QPushButton(text)
if icon is not None:
b.setIcon(newIcon(icon))
b.setIcon(new_icon(icon))
if slot is not None:
b.clicked.connect(slot)
return b
def newAction(parent, text, slot=None, shortcut=None, icon=None,
def new_action(parent, text, slot=None, shortcut=None, icon=None,
tip=None, checkable=False, enabled=True):
"""Create a new action and assign callbacks, shortcuts, etc."""
a = QAction(text, parent)
if icon is not None:
a.setIcon(newIcon(icon))
a.setIcon(new_icon(icon))
if shortcut is not None:
if isinstance(shortcut, (list, tuple)):
a.setShortcuts(shortcut)
@ -48,7 +48,7 @@ def newAction(parent, text, slot=None, shortcut=None, icon=None,
return a
def addActions(widget, actions):
def add_actions(widget, actions):
for action in actions:
if action is None:
widget.addSeparator()
@ -58,11 +58,11 @@ def addActions(widget, actions):
widget.addAction(action)
def labelValidator():
def label_validator():
return QRegExpValidator(QRegExp(r'^[^ \t].+'), None)
class struct(object):
class Struct(object):
def __init__(self, **kwargs):
self.__dict__.update(kwargs)
@ -72,21 +72,21 @@ def distance(p):
return sqrt(p.x() * p.x() + p.y() * p.y())
def fmtShortcut(text):
def format_shortcut(text):
mod, key = text.split('+', 1)
return '<b>%s</b>+<b>%s</b>' % (mod, key)
def generateColorByText(text):
def generate_color_by_text(text):
s = ustr(text)
hashCode = int(hashlib.sha256(s.encode('utf-8')).hexdigest(), 16)
r = int((hashCode / 255) % 255)
g = int((hashCode / 65025) % 255)
b = int((hashCode / 16581375) % 255)
hash_code = int(hashlib.sha256(s.encode('utf-8')).hexdigest(), 16)
r = int((hash_code / 255) % 255)
g = int((hash_code / 65025) % 255)
b = int((hash_code / 16581375) % 255)
return QColor(r, g, b, 100)
def have_qstring():
'''p3/qt5 get rid of QString wrapper as py3 has native unicode str type'''
"""p3/qt5 get rid of QString wrapper as py3 has native unicode str type"""
return not (sys.version_info.major >= 3 or QT_VERSION_STR.startswith('5.'))
def util_qt_strlistclass():

View File

@ -13,67 +13,67 @@ ENCODE_METHOD = DEFAULT_ENCODING
class YOLOWriter:
def __init__(self, foldername, filename, imgSize, databaseSrc='Unknown', localImgPath=None):
self.foldername = foldername
def __init__(self, folder_name, filename, img_size, database_src='Unknown', local_img_path=None):
self.folder_name = folder_name
self.filename = filename
self.databaseSrc = databaseSrc
self.imgSize = imgSize
self.boxlist = []
self.localImgPath = localImgPath
self.database_src = database_src
self.img_size = img_size
self.box_list = []
self.local_img_path = local_img_path
self.verified = False
def addBndBox(self, xmin, ymin, xmax, ymax, name, difficult):
bndbox = {'xmin': xmin, 'ymin': ymin, 'xmax': xmax, 'ymax': ymax}
bndbox['name'] = name
bndbox['difficult'] = difficult
self.boxlist.append(bndbox)
def add_bnd_box(self, x_min, y_min, x_max, y_max, name, difficult):
bnd_box = {'xmin': x_min, 'ymin': y_min, 'xmax': x_max, 'ymax': y_max}
bnd_box['name'] = name
bnd_box['difficult'] = difficult
self.box_list.append(bnd_box)
def BndBox2YoloLine(self, box, classList=[]):
xmin = box['xmin']
xmax = box['xmax']
ymin = box['ymin']
ymax = box['ymax']
def bnd_box_to_yolo_line(self, box, class_list=[]):
x_min = box['xmin']
x_max = box['xmax']
y_min = box['ymin']
y_max = box['ymax']
xcen = float((xmin + xmax)) / 2 / self.imgSize[1]
ycen = float((ymin + ymax)) / 2 / self.imgSize[0]
x_center = float((x_min + x_max)) / 2 / self.img_size[1]
y_center = float((y_min + y_max)) / 2 / self.img_size[0]
w = float((xmax - xmin)) / self.imgSize[1]
h = float((ymax - ymin)) / self.imgSize[0]
w = float((x_max - x_min)) / self.img_size[1]
h = float((y_max - y_min)) / self.img_size[0]
# PR387
boxName = box['name']
if boxName not in classList:
classList.append(boxName)
box_name = box['name']
if box_name not in class_list:
class_list.append(box_name)
classIndex = classList.index(boxName)
class_index = class_list.index(box_name)
return classIndex, xcen, ycen, w, h
return class_index, x_center, y_center, w, h
def save(self, classList=[], targetFile=None):
def save(self, class_list=[], target_file=None):
out_file = None #Update yolo .txt
out_class_file = None #Update class list .txt
out_file = None # Update yolo .txt
out_class_file = None # Update class list .txt
if targetFile is None:
if target_file is None:
out_file = open(
self.filename + TXT_EXT, 'w', encoding=ENCODE_METHOD)
classesFile = os.path.join(os.path.dirname(os.path.abspath(self.filename)), "classes.txt")
out_class_file = open(classesFile, 'w')
classes_file = os.path.join(os.path.dirname(os.path.abspath(self.filename)), "classes.txt")
out_class_file = open(classes_file, 'w')
else:
out_file = codecs.open(targetFile, 'w', encoding=ENCODE_METHOD)
classesFile = os.path.join(os.path.dirname(os.path.abspath(targetFile)), "classes.txt")
out_class_file = open(classesFile, 'w')
out_file = codecs.open(target_file, 'w', encoding=ENCODE_METHOD)
classes_file = os.path.join(os.path.dirname(os.path.abspath(target_file)), "classes.txt")
out_class_file = open(classes_file, 'w')
for box in self.boxlist:
classIndex, xcen, ycen, w, h = self.BndBox2YoloLine(box, classList)
# print (classIndex, xcen, ycen, w, h)
out_file.write("%d %.6f %.6f %.6f %.6f\n" % (classIndex, xcen, ycen, w, h))
for box in self.box_list:
class_index, x_center, y_center, w, h = self.bnd_box_to_yolo_line(box, class_list)
# print (classIndex, x_center, y_center, w, h)
out_file.write("%d %.6f %.6f %.6f %.6f\n" % (class_index, x_center, y_center, w, h))
# print (classList)
# print (out_class_file)
for c in classList:
for c in class_list:
out_class_file.write(c+'\n')
out_class_file.close()
@ -83,64 +83,64 @@ class YOLOWriter:
class YoloReader:
def __init__(self, filepath, image, classListPath=None):
def __init__(self, file_path, image, class_list_path=None):
# shapes type:
# [labbel, [(x1,y1), (x2,y2), (x3,y3), (x4,y4)], color, color, difficult]
self.shapes = []
self.filepath = filepath
self.file_path = file_path
if classListPath is None:
dir_path = os.path.dirname(os.path.realpath(self.filepath))
self.classListPath = os.path.join(dir_path, "classes.txt")
if class_list_path is None:
dir_path = os.path.dirname(os.path.realpath(self.file_path))
self.class_list_path = os.path.join(dir_path, "classes.txt")
else:
self.classListPath = classListPath
self.class_list_path = class_list_path
# print (filepath, self.classListPath)
# print (file_path, self.class_list_path)
classesFile = open(self.classListPath, 'r')
self.classes = classesFile.read().strip('\n').split('\n')
classes_file = open(self.class_list_path, 'r')
self.classes = classes_file.read().strip('\n').split('\n')
# print (self.classes)
imgSize = [image.height(), image.width(),
img_size = [image.height(), image.width(),
1 if image.isGrayscale() else 3]
self.imgSize = imgSize
self.img_size = img_size
self.verified = False
# try:
self.parseYoloFormat()
self.parse_yolo_format()
# except:
# pass
def getShapes(self):
def get_shapes(self):
return self.shapes
def addShape(self, label, xmin, ymin, xmax, ymax, difficult):
def add_shape(self, label, x_min, y_min, x_max, y_max, difficult):
points = [(xmin, ymin), (xmax, ymin), (xmax, ymax), (xmin, ymax)]
points = [(x_min, y_min), (x_max, y_min), (x_max, y_max), (x_min, y_max)]
self.shapes.append((label, points, None, None, difficult))
def yoloLine2Shape(self, classIndex, xcen, ycen, w, h):
label = self.classes[int(classIndex)]
def yolo_line_to_shape(self, class_index, x_center, y_center, w, h):
label = self.classes[int(class_index)]
xmin = max(float(xcen) - float(w) / 2, 0)
xmax = min(float(xcen) + float(w) / 2, 1)
ymin = max(float(ycen) - float(h) / 2, 0)
ymax = min(float(ycen) + float(h) / 2, 1)
x_min = max(float(x_center) - float(w) / 2, 0)
x_max = min(float(x_center) + float(w) / 2, 1)
y_min = max(float(y_center) - float(h) / 2, 0)
y_max = min(float(y_center) + float(h) / 2, 1)
xmin = int(self.imgSize[1] * xmin)
xmax = int(self.imgSize[1] * xmax)
ymin = int(self.imgSize[0] * ymin)
ymax = int(self.imgSize[0] * ymax)
x_min = int(self.img_size[1] * x_min)
x_max = int(self.img_size[1] * x_max)
y_min = int(self.img_size[0] * y_min)
y_max = int(self.img_size[0] * y_max)
return label, xmin, ymin, xmax, ymax
return label, x_min, y_min, x_max, y_max
def parseYoloFormat(self):
bndBoxFile = open(self.filepath, 'r')
for bndBox in bndBoxFile:
classIndex, xcen, ycen, w, h = bndBox.strip().split(' ')
label, xmin, ymin, xmax, ymax = self.yoloLine2Shape(classIndex, xcen, ycen, w, h)
def parse_yolo_format(self):
bnd_box_file = open(self.file_path, 'r')
for bndBox in bnd_box_file:
class_index, x_center, y_center, w, h = bndBox.strip().split(' ')
label, x_min, y_min, x_max, y_max = self.yolo_line_to_shape(class_index, x_center, y_center, w, h)
# Caveat: difficult flag is discarded when saved as yolo format.
self.addShape(label, xmin, ymin, xmax, ymax, False)
self.add_shape(label, x_min, y_min, x_max, y_max, False)

View File

@ -14,17 +14,17 @@ class TestPascalVocRW(unittest.TestCase):
# Test Write/Read
writer = PascalVocWriter('tests', 'test', (512, 512, 1), localImgPath='tests/test.512.512.bmp')
difficult = 1
writer.addBndBox(60, 40, 430, 504, 'person', difficult)
writer.addBndBox(113, 40, 450, 403, 'face', difficult)
writer.add_bnd_box(60, 40, 430, 504, 'person', difficult)
writer.add_bnd_box(113, 40, 450, 403, 'face', difficult)
writer.save('tests/test.xml')
reader = PascalVocReader('tests/test.xml')
shapes = reader.getShapes()
shapes = reader.get_shapes()
personBndBox = shapes[0]
person_bnd_box = shapes[0]
face = shapes[1]
self.assertEqual(personBndBox[0], 'person')
self.assertEqual(personBndBox[1], [(60, 40), (430, 40), (430, 504), (60, 504)])
self.assertEqual(person_bnd_box[0], 'person')
self.assertEqual(person_bnd_box[1], [(60, 40), (430, 40), (430, 504), (60, 504)])
self.assertEqual(face[0], 'face')
self.assertEqual(face[1], [(113, 40), (450, 40), (450, 403), (113, 403)])
@ -54,15 +54,15 @@ class TestCreateMLRW(unittest.TestCase):
# check written json
with open(output_file, "r") as file:
inputdata = file.read()
input_data = file.read()
import json
data_dict = json.loads(inputdata)[0]
data_dict = json.loads(input_data)[0]
self.assertEqual('test.512.512.bmp', data_dict['image'], 'filename not correct in .json')
self.assertEqual(2, len(data_dict['annotations']), 'outputfile contains to less annotations')
self.assertEqual(2, len(data_dict['annotations']), 'output file contains to less annotations')
face = data_dict['annotations'][1]
self.assertEqual('face', face['label'], 'labelname is wrong')
self.assertEqual('face', face['label'], 'label name is wrong')
face_coords = face['coordinates']
self.assertEqual(expected_width, face_coords['width'], 'calculated width is wrong')
self.assertEqual(expected_height, face_coords['height'], 'calculated height is wrong')
@ -84,15 +84,15 @@ class TestCreateMLRW(unittest.TestCase):
self.assertEqual('face', face[0], 'label is wrong')
face_coords = face[1]
xmin = face_coords[0][0]
xmax = face_coords[1][0]
ymin = face_coords[0][1]
ymax = face_coords[2][1]
x_min = face_coords[0][0]
x_max = face_coords[1][0]
y_min = face_coords[0][1]
y_max = face_coords[2][1]
self.assertEqual(245, xmin, 'xmin is wrong')
self.assertEqual(350, xmax, 'xmax is wrong')
self.assertEqual(250, ymin, 'ymin is wrong')
self.assertEqual(365, ymax, 'ymax is wrong')
self.assertEqual(245, x_min, 'xmin is wrong')
self.assertEqual(350, x_max, 'xmax is wrong')
self.assertEqual(250, y_min, 'ymin is wrong')
self.assertEqual(365, y_max, 'ymax is wrong')
if __name__ == '__main__':

View File

@ -7,20 +7,20 @@ from stringBundle import StringBundle
class TestStringBundle(unittest.TestCase):
def test_loadDefaultBundle_withoutError(self):
strBundle = StringBundle.getBundle('en')
self.assertEqual(strBundle.getString("openDir"), 'Open Dir', 'Fail to load the default bundle')
str_bundle = StringBundle.get_bundle('en')
self.assertEqual(str_bundle.get_string("openDir"), 'Open Dir', 'Fail to load the default bundle')
def test_fallback_withoutError(self):
strBundle = StringBundle.getBundle('zh-TW')
self.assertEqual(strBundle.getString("openDir"), u'\u958B\u555F\u76EE\u9304', 'Fail to load the zh-TW bundle')
str_bundle = StringBundle.get_bundle('zh-TW')
self.assertEqual(str_bundle.get_string("openDir"), u'\u958B\u555F\u76EE\u9304', 'Fail to load the zh-TW bundle')
def test_setInvaleLocaleToEnv_printErrorMsg(self):
prev_lc = os.environ['LC_ALL']
prev_lang = os.environ['LANG']
os.environ['LC_ALL'] = 'UTF-8'
os.environ['LANG'] = 'UTF-8'
strBundle = StringBundle.getBundle()
self.assertEqual(strBundle.getString("openDir"), 'Open Dir', 'Fail to load the default bundle')
str_bundle = StringBundle.get_bundle()
self.assertEqual(str_bundle.get_string("openDir"), 'Open Dir', 'Fail to load the default bundle')
os.environ['LC_ALL'] = prev_lc
os.environ['LANG'] = prev_lang

View File

@ -1,22 +1,22 @@
import os
import sys
import unittest
from libs.utils import struct, newAction, newIcon, addActions, fmtShortcut, generateColorByText, natural_sort
from libs.utils import Struct, new_action, new_icon, add_actions, format_shortcut, generate_color_by_text, natural_sort
class TestUtils(unittest.TestCase):
def test_generateColorByGivingUniceText_noError(self):
res = generateColorByText(u'\u958B\u555F\u76EE\u9304')
res = generate_color_by_text(u'\u958B\u555F\u76EE\u9304')
self.assertTrue(res.green() >= 0)
self.assertTrue(res.red() >= 0)
self.assertTrue(res.blue() >= 0)
def test_nautalSort_noError(self):
l1 = ['f1', 'f11', 'f3' ]
exptected_l1 = ['f1', 'f3', 'f11']
l1 = ['f1', 'f11', 'f3']
expected_l1 = ['f1', 'f3', 'f11']
natural_sort(l1)
for idx, val in enumerate(l1):
self.assertTrue(val == exptected_l1[idx])
self.assertTrue(val == expected_l1[idx])
if __name__ == '__main__':
unittest.main()