Merge pull request #80 from ChrisDal/master

Add Difficult checkbox
This commit is contained in:
darrenl 2017-05-03 02:07:52 -05:00 committed by GitHub
commit 4ee8287e51
4 changed files with 112 additions and 57 deletions

View File

@ -139,11 +139,20 @@ class MainWindow(QMainWindow, WindowMixin):
listLayout.addWidget(self.labelList) listLayout.addWidget(self.labelList)
self.editButton = QToolButton() self.editButton = QToolButton()
self.editButton.setToolButtonStyle(Qt.ToolButtonTextBesideIcon) self.editButton.setToolButtonStyle(Qt.ToolButtonTextBesideIcon)
# Add chris
self.diffcButton = QCheckBox("Difficult")
self.diffcButton.setChecked(False)
self.diffcButton.stateChanged.connect(self.btnstate)
self.labelListContainer = QWidget() self.labelListContainer = QWidget()
self.labelListContainer.setLayout(listLayout) self.labelListContainer.setLayout(listLayout)
listLayout.addWidget(self.editButton) # , 0, Qt.AlignCenter) listLayout.addWidget(self.editButton) # , 0, Qt.AlignCenter)
# Add chris
listLayout.addWidget(self.diffcButton)
listLayout.addWidget(self.labelList) listLayout.addWidget(self.labelList)
self.dock = QDockWidget(u'Box Labels', self) self.dock = QDockWidget(u'Box Labels', self)
self.dock.setObjectName(u'Labels') self.dock.setObjectName(u'Labels')
self.dock.setWidget(self.labelListContainer) self.dock.setWidget(self.labelListContainer)
@ -376,6 +385,8 @@ class MainWindow(QMainWindow, WindowMixin):
self.fillColor = None self.fillColor = None
self.zoom_level = 100 self.zoom_level = 100
self.fit_window = False self.fit_window = False
# Add Chris
self.difficult = False
# XXX: Could be completely declarative. # XXX: Could be completely declarative.
# Restore application settings. # Restore application settings.
@ -431,6 +442,8 @@ class MainWindow(QMainWindow, WindowMixin):
self.fillColor = QColor(settings.get('fill/color', Shape.fill_color)) self.fillColor = QColor(settings.get('fill/color', Shape.fill_color))
Shape.line_color = self.lineColor Shape.line_color = self.lineColor
Shape.fill_color = self.fillColor Shape.fill_color = self.fillColor
# Add chris
Shape.Difficult = self.difficult
def xbool(x): def xbool(x):
if isinstance(x, QVariant): if isinstance(x, QVariant):
@ -609,6 +622,33 @@ class MainWindow(QMainWindow, WindowMixin):
if filename: if filename:
self.loadFile(filename) self.loadFile(filename)
# Add chris
def btnstate(self, item= None):
""" Function to handle difficult examples
Update on each object """
if not self.canvas.editing():
return
item = self.currentItem()
if not item: # If not selected Item, take the first one
item = self.labelList.item(self.labelList.count()-1)
difficult = self.diffcButton.isChecked()
try:
shape = self.itemsToShapes[item]
except:
pass
# Checked and Update
try:
if difficult != shape.difficult:
shape.difficult = difficult
self.setDirty()
else: # User probably changed item visibility
self.canvas.setShapeVisible(shape, item.checkState() == Qt.Checked)
except:
pass
# React to canvas signals. # React to canvas signals.
def shapeSelectionChanged(self, selected=False): def shapeSelectionChanged(self, selected=False):
if self._noSelectionSlot: if self._noSelectionSlot:
@ -646,17 +686,20 @@ class MainWindow(QMainWindow, WindowMixin):
def loadLabels(self, shapes): def loadLabels(self, shapes):
s = [] s = []
for label, points, line_color, fill_color in shapes: for label, points, line_color, fill_color, difficult in shapes:
shape = Shape(label=label) shape = Shape(label=label)
for x, y in points: for x, y in points:
shape.addPoint(QPointF(x, y)) shape.addPoint(QPointF(x, y))
shape.difficult = difficult
shape.close() shape.close()
s.append(shape) s.append(shape)
self.addLabel(shape) self.addLabel(shape)
if line_color: if line_color:
shape.line_color = QColor(*line_color) shape.line_color = QColor(*line_color)
if fill_color: if fill_color:
shape.fill_color = QColor(*fill_color) shape.fill_color = QColor(*fill_color)
self.canvas.loadShapes(s) self.canvas.loadShapes(s)
def saveLabels(self, annotationFilePath): def saveLabels(self, annotationFilePath):
@ -671,7 +714,9 @@ class MainWindow(QMainWindow, WindowMixin):
if s.line_color != self.lineColor else None, if s.line_color != self.lineColor else None,
fill_color=s.fill_color.getRgb() fill_color=s.fill_color.getRgb()
if s.fill_color != self.fillColor else None, if s.fill_color != self.fillColor else None,
points=[(p.x(), p.y()) for p in s.points]) points=[(p.x(), p.y()) for p in s.points],
# add chris
difficult = s.difficult)
shapes = [format_shape(shape) for shape in self.canvas.shapes] shapes = [format_shape(shape) for shape in self.canvas.shapes]
# Can add differrent annotation formats here # Can add differrent annotation formats here
@ -700,6 +745,9 @@ class MainWindow(QMainWindow, WindowMixin):
if item and self.canvas.editing(): if item and self.canvas.editing():
self._noSelectionSlot = True self._noSelectionSlot = True
self.canvas.selectShape(self.itemsToShapes[item]) self.canvas.selectShape(self.itemsToShapes[item])
shape = self.itemsToShapes[item]
# Add Chris
self.diffcButton.setChecked(shape.difficult)
def labelItemChanged(self, item): def labelItemChanged(self, item):
shape = self.itemsToShapes[item] shape = self.itemsToShapes[item]
@ -721,6 +769,8 @@ class MainWindow(QMainWindow, WindowMixin):
parent=self, listItem=self.labelHist) parent=self, listItem=self.labelHist)
text = self.labelDialog.popUp(text=self.prevLabelText) text = self.labelDialog.popUp(text=self.prevLabelText)
# Add Chris
self.diffcButton.setChecked(False)
if text is not None: if text is not None:
self.prevLabelText = text self.prevLabelText = text
self.addLabel(self.canvas.setLastLabel(text)) self.addLabel(self.canvas.setLastLabel(text))
@ -839,6 +889,11 @@ class MainWindow(QMainWindow, WindowMixin):
self.setWindowTitle(__appname__ + ' ' + filePath) self.setWindowTitle(__appname__ + ' ' + filePath)
# Default : select last item if there is at least one item
if self.labelList.count():
self.labelList.setCurrentItem(self.labelList.item(self.labelList.count()-1))
self.labelList.setItemSelected(self.labelList.item(self.labelList.count()-1), True)
self.canvas.setFocus(True) self.canvas.setFocus(True)
return True return True
return False return False

View File

@ -45,8 +45,10 @@ class LabelFile(object):
for shape in shapes: for shape in shapes:
points = shape['points'] points = shape['points']
label = shape['label'] label = shape['label']
# Add Chris
difficult = int(shape['difficult'])
bndbox = LabelFile.convertPoints2BndBox(points) bndbox = LabelFile.convertPoints2BndBox(points)
writer.addBndBox(bndbox[0], bndbox[1], bndbox[2], bndbox[3], label) writer.addBndBox(bndbox[0], bndbox[1], bndbox[2], bndbox[3], label, difficult)
writer.save(targetFile=filename) writer.save(targetFile=filename)
return return

View File

@ -2,6 +2,8 @@
# -*- coding: utf8 -*- # -*- coding: utf8 -*-
import _init_path import _init_path
import sys import sys
from xml.etree import ElementTree
from xml.etree.ElementTree import Element, SubElement
from lxml import etree from lxml import etree
import codecs import codecs
@ -10,7 +12,7 @@ XML_EXT = '.xml'
class PascalVocWriter: class PascalVocWriter:
def __init__(self, foldername, filename, imgSize, databaseSrc='Unknown', localImgPath=None): def __init__(self, foldername, filename, imgSize,databaseSrc='Unknown', localImgPath=None):
self.foldername = foldername self.foldername = foldername
self.filename = filename self.filename = filename
self.databaseSrc = databaseSrc self.databaseSrc = databaseSrc
@ -19,14 +21,14 @@ class PascalVocWriter:
self.localImgPath = localImgPath self.localImgPath = localImgPath
self.verified = False self.verified = False
def prettify(self, elem): def prettify(self, elem):
""" """
Return a pretty-printed XML string for the Element. Return a pretty-printed XML string for the Element.
""" """
rough_string = etree.tostring(elem, encoding='UTF-8') rough_string = ElementTree.tostring(elem, 'utf8')
rough_string = str(rough_string, encoding="UTF-8") root = etree.fromstring(rough_string)
root = etree.XML(rough_string) return etree.tostring(root, pretty_print=True)
return etree.tostring(root, encoding='UTF-8', pretty_print=True)
def genXML(self): def genXML(self):
""" """
@ -38,26 +40,26 @@ class PascalVocWriter:
self.imgSize is None: self.imgSize is None:
return None return None
top = etree.Element('annotation') top = Element('annotation')
top.set('verified', 'yes' if self.verified else 'no') top.set('verified', 'yes' if self.verified else 'no')
folder = etree.SubElement(top, 'folder') folder = SubElement(top, 'folder')
folder.text = self.foldername folder.text = self.foldername
filename = etree.SubElement(top, 'filename') filename = SubElement(top, 'filename')
filename.text = self.filename filename.text = self.filename
localImgPath = etree.SubElement(top, 'path') localImgPath = SubElement(top, 'path')
localImgPath.text = self.localImgPath localImgPath.text = self.localImgPath
source = etree.SubElement(top, 'source') source = SubElement(top, 'source')
database = etree.SubElement(source, 'database') database = SubElement(source, 'database')
database.text = self.databaseSrc database.text = self.databaseSrc
size_part = etree.SubElement(top, 'size') size_part = SubElement(top, 'size')
width = etree.SubElement(size_part, 'width') width = SubElement(size_part, 'width')
height = etree.SubElement(size_part, 'height') height = SubElement(size_part, 'height')
depth = etree.SubElement(size_part, 'depth') depth = SubElement(size_part, 'depth')
width.text = str(self.imgSize[1]) width.text = str(self.imgSize[1])
height.text = str(self.imgSize[0]) height.text = str(self.imgSize[0])
if len(self.imgSize) == 3: if len(self.imgSize) == 3:
@ -65,38 +67,46 @@ class PascalVocWriter:
else: else:
depth.text = '1' depth.text = '1'
segmented = etree.SubElement(top, 'segmented') segmented = SubElement(top, 'segmented')
segmented.text = '0' segmented.text = '0'
return top return top
def addBndBox(self, xmin, ymin, xmax, ymax, name): def addBndBox(self, xmin, ymin, xmax, ymax, name, difficult):
bndbox = {'xmin': xmin, 'ymin': ymin, 'xmax': xmax, 'ymax': ymax} bndbox = {'xmin': xmin, 'ymin': ymin, 'xmax': xmax, 'ymax': ymax}
bndbox['name'] = name bndbox['name'] = name
bndbox['difficult'] = difficult
self.boxlist.append(bndbox) self.boxlist.append(bndbox)
def appendObjects(self, top): def appendObjects(self, top):
for each_object in self.boxlist: for each_object in self.boxlist:
object_item = etree.SubElement(top, 'object') object_item = SubElement(top, 'object')
name = etree.SubElement(object_item, 'name') name = SubElement(object_item, 'name')
try: try:
name.text = unicode(each_object['name']) name.text = unicode(each_object['name'])
except NameError: except NameError:
# Py3: NameError: name 'unicode' is not defined # Py3: NameError: name 'unicode' is not defined
name.text = each_object['name'] name.text = each_object['name']
pose = etree.SubElement(object_item, 'pose') pose = SubElement(object_item, 'pose')
pose.text = "Unspecified" pose.text = "Unspecified"
truncated = etree.SubElement(object_item, 'truncated') truncated = SubElement(object_item, 'truncated')
# max == height or min
if int(each_object['ymax']) == int(self.imgSize[0]) or (int(each_object['ymin'])== 1):
truncated.text = "1"
# max == width or min
elif (int(each_object['xmax'])==int(self.imgSize[1])) or (int(each_object['xmin'])== 1):
truncated.text = "1"
else:
truncated.text = "0" truncated.text = "0"
difficult = etree.SubElement(object_item, 'difficult') difficult = SubElement(object_item, 'Difficult')
difficult.text = "0" difficult.text = str( bool(each_object['difficult']) & 1 )
bndbox = etree.SubElement(object_item, 'bndbox') bndbox = SubElement(object_item, 'bndbox')
xmin = etree.SubElement(bndbox, 'xmin') xmin = SubElement(bndbox, 'xmin')
xmin.text = str(each_object['xmin']) xmin.text = str(each_object['xmin'])
ymin = etree.SubElement(bndbox, 'ymin') ymin = SubElement(bndbox, 'ymin')
ymin.text = str(each_object['ymin']) ymin.text = str(each_object['ymin'])
xmax = etree.SubElement(bndbox, 'xmax') xmax = SubElement(bndbox, 'xmax')
xmax.text = str(each_object['xmax']) xmax.text = str(each_object['xmax'])
ymax = etree.SubElement(bndbox, 'ymax') ymax = SubElement(bndbox, 'ymax')
ymax.text = str(each_object['ymax']) ymax.text = str(each_object['ymax'])
def save(self, targetFile=None): def save(self, targetFile=None):
@ -118,7 +128,7 @@ class PascalVocReader:
def __init__(self, filepath): def __init__(self, filepath):
# shapes type: # shapes type:
# [labbel, [(x1,y1), (x2,y2), (x3,y3), (x4,y4)], color, color] # [labbel, [(x1,y1), (x2,y2), (x3,y3), (x4,y4)], color, color, difficult]
self.shapes = [] self.shapes = []
self.filepath = filepath self.filepath = filepath
self.verified = False self.verified = False
@ -127,24 +137,19 @@ class PascalVocReader:
def getShapes(self): def getShapes(self):
return self.shapes return self.shapes
def addShape(self, label, bndbox): def addShape(self, label, bndbox, difficult):
xmin = int(bndbox.find('xmin').text) xmin = int(bndbox.find('xmin').text)
ymin = int(bndbox.find('ymin').text) ymin = int(bndbox.find('ymin').text)
xmax = int(bndbox.find('xmax').text) xmax = int(bndbox.find('xmax').text)
ymax = int(bndbox.find('ymax').text) ymax = int(bndbox.find('ymax').text)
points = [(xmin, ymin), (xmax, ymin), (xmax, ymax), (xmin, ymax)] points = [(xmin, ymin), (xmax, ymin), (xmax, ymax), (xmin, ymax)]
self.shapes.append((label, points, None, None))
self.shapes.append((label, points, None, None, difficult))
def parseXML(self): def parseXML(self):
assert self.filepath.endswith('.xml'), "Unsupport file format" assert self.filepath.endswith('.xml'), "Unsupport file format"
content = None parser = etree.XMLParser(encoding='utf-8')
with open(self.filepath, 'r') as xmlFile: xmltree = ElementTree.parse(self.filepath, parser=parser).getroot()
content = xmlFile.read()
if content is None:
return False
xmltree = etree.XML(content)
filename = xmltree.find('filename').text filename = xmltree.find('filename').text
try: try:
verified = xmltree.attrib['verified'] verified = xmltree.attrib['verified']
@ -156,16 +161,7 @@ class PascalVocReader:
for object_iter in xmltree.findall('object'): for object_iter in xmltree.findall('object'):
bndbox = object_iter.find("bndbox") bndbox = object_iter.find("bndbox")
label = object_iter.find('name').text label = object_iter.find('name').text
self.addShape(label, bndbox) # Add chris
difficult = bool(int(object_iter.find('Difficult').text))
self.addShape(label, bndbox, difficult)
return True return True
# tempParseReader = PascalVocReader('test.xml')
# print tempParseReader.getShapes()
"""
# Test
tmp = PascalVocWriter('temp','test', (10,20,3))
tmp.addBndBox(10,10,20,30,'chair')
tmp.addBndBox(1,1,600,600,'car')
tmp.save()
"""

View File

@ -36,11 +36,12 @@ class Shape(object):
point_size = 8 point_size = 8
scale = 1.0 scale = 1.0
def __init__(self, label=None, line_color=None): def __init__(self, label=None, line_color=None,difficult = False):
self.label = label self.label = label
self.points = [] self.points = []
self.fill = False self.fill = False
self.selected = False self.selected = False
self.difficult = difficult
self._highlightIndex = None self._highlightIndex = None
self._highlightMode = self.NEAR_VERTEX self._highlightMode = self.NEAR_VERTEX
@ -171,6 +172,7 @@ class Shape(object):
shape.line_color = self.line_color shape.line_color = self.line_color
if self.fill_color != Shape.fill_color: if self.fill_color != Shape.fill_color:
shape.fill_color = self.fill_color shape.fill_color = self.fill_color
shape.difficult = self.difficult
return shape return shape
def __len__(self): def __len__(self):