labelme.py 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270
  1. #!/usr/bin/env python
  2. # -*- coding: utf8 -*-
  3. import os.path
  4. import re
  5. import sys
  6. from functools import partial
  7. from collections import defaultdict
  8. from PyQt4.QtGui import *
  9. from PyQt4.QtCore import *
  10. from shape import shape
  11. __appname__ = 'labelme'
  12. ### Utility functions and classes.
  13. def action(parent, text, slot=None, shortcut=None, icon=None,
  14. tip=None, checkable=False):
  15. """Create a new action and assign callbacks, shortcuts, etc."""
  16. a = QAction(text, parent)
  17. if icon is not None:
  18. a.setIcon(QIcon(u':/%s' % icon))
  19. if shortcut is not None:
  20. a.setShortcut(shortcut)
  21. if tip is not None:
  22. a.setToolTip(tip)
  23. a.setStatusTip(tip)
  24. if slot is not None:
  25. a.triggered.connect(slot)
  26. if checkable:
  27. a.setCheckable(True)
  28. return a
  29. def add_actions(widget, actions):
  30. for action in actions:
  31. if action is None:
  32. widget.addSeparator()
  33. else:
  34. widget.addAction(action)
  35. class WindowMixin(object):
  36. def menu(self, title, actions=None):
  37. menu = self.menuBar().addMenu(title)
  38. if actions:
  39. add_actions(menu, actions)
  40. return menu
  41. def toolbar(self, title, actions=None):
  42. toolbar = QToolBar(title)
  43. toolbar.setObjectName(u'%sToolBar' % title)
  44. #toolbar.setOrientation(Qt.Vertical)
  45. toolbar.setContentsMargins(0,0,0,0)
  46. toolbar.setToolButtonStyle(Qt.ToolButtonTextUnderIcon)
  47. toolbar.layout().setContentsMargins(0,0,0,0)
  48. if actions:
  49. add_actions(toolbar, actions)
  50. self.addToolBar(Qt.LeftToolBarArea, toolbar)
  51. return toolbar
  52. class MainWindow(QMainWindow, WindowMixin):
  53. def __init__(self, filename=None):
  54. super(MainWindow, self).__init__()
  55. self.setWindowTitle(__appname__)
  56. self.setContentsMargins(0, 0, 0, 0)
  57. # Main widgets.
  58. self.label = QLineEdit(u'Hello world, مرحبا ، العالم, Γεια σου κόσμε!')
  59. self.dock = QDockWidget(u'Label', parent=self)
  60. self.dock.setObjectName(u'Label')
  61. self.dock.setWidget(self.label)
  62. #self.dock.setFeatures(QDockWidget.DockWidgetMovable|QDockWidget.DockWidgetFloatable)
  63. self.imageWidget = Label()
  64. self.imageWidget.setAlignment(Qt.AlignCenter)
  65. self.imageWidget.setContextMenuPolicy(Qt.ActionsContextMenu)
  66. self.addDockWidget(Qt.BottomDockWidgetArea, self.dock)
  67. self.setCentralWidget(self.imageWidget)
  68. # Actions
  69. quit = action(self, '&Quit', self.close, 'Ctrl+Q', u'Exit application')
  70. open = action(self, '&Open', self.openFile, 'Ctrl+O', u'Open file')
  71. labl = self.dock.toggleViewAction()
  72. labl.setShortcut('Ctrl+L')
  73. add_actions(self.menu('&File'), (open, None, labl, None, quit))
  74. add_actions(self.toolbar('Tools'), (open, None, labl, None, quit))
  75. self.statusBar().showMessage('%s started.' % __appname__)
  76. self.statusBar().show()
  77. # Application state.
  78. self.image = QImage()
  79. self.filename = filename
  80. self.recent_files = []
  81. # TODO: Could be completely declarative.
  82. # Restore application settings.
  83. types = {
  84. 'filename': QString,
  85. 'recent-files': QStringList,
  86. 'window/size': QSize,
  87. 'window/position': QPoint,
  88. 'window/geometry': QByteArray,
  89. # Docks and toolbars:
  90. 'window/state': QByteArray,
  91. }
  92. self.settings = settings = Settings(types)
  93. self.recent_files = settings['recent-files']
  94. size = settings.get('window/size', QSize(600, 500))
  95. position = settings.get('window/position', QPoint(0, 0))
  96. self.resize(size)
  97. self.move(position)
  98. # or simply:
  99. #self.restoreGeometry(settings['window/geometry']
  100. self.restoreState(settings['window/state'])
  101. # The file menu has default dynamically generated entries.
  102. self.updateFileMenu()
  103. # Since loading the file may take some time, make sure it runs in the background.
  104. self.queueEvent(partial(self.loadFile, self.filename))
  105. def queueEvent(self, function):
  106. QTimer.singleShot(0, function)
  107. def loadFile(self, filename=None):
  108. """Load the specified file, or the last opened file if None."""
  109. if filename is None:
  110. filename = self.settings['filename']
  111. # FIXME: Load the actual file here.
  112. if QFile.exists(filename):
  113. # Load image
  114. image = QImage(filename)
  115. if image.isNull():
  116. message = "Failed to read %s" % filename
  117. else:
  118. message = "Loaded %s" % os.path.basename(unicode(filename))
  119. self.image = image
  120. self.filename = filename
  121. self.showImage()
  122. self.statusBar().showMessage(message)
  123. def showImage(self):
  124. if self.image.isNull():
  125. return
  126. self.imageWidget.setPixmap(self.scaled(QPixmap.fromImage(self.image)))
  127. self.imageWidget.show()
  128. def resizeEvent(self, event):
  129. if self.imageWidget and self.imageWidget.pixmap():
  130. self.imageWidget.setPixmap(self.scaled(self.imageWidget.pixmap()))
  131. super(MainWindow, self).resizeEvent(event)
  132. def scaled(self, pixmap):
  133. width = self.centralWidget().width()
  134. height = self.centralWidget().height()
  135. return pixmap.scaled(width, height,
  136. Qt.KeepAspectRatio, Qt.SmoothTransformation)
  137. def closeEvent(self, event):
  138. # TODO: Make sure changes are saved.
  139. s = self.settings
  140. s['filename'] = self.filename if self.filename else QString()
  141. s['window/size'] = self.size()
  142. s['window/position'] = self.pos()
  143. s['window/state'] = self.saveState()
  144. #s['window/geometry'] = self.saveGeometry()
  145. def updateFileMenu(self):
  146. """Populate menu with recent files."""
  147. ## Dialogs.
  148. def openFile(self):
  149. if not self.check():
  150. return
  151. path = os.path.dirname(unicode(self.filename))\
  152. if self.filename else '.'
  153. formats = ['*.%s' % unicode(fmt).lower()\
  154. for fmt in QImageReader.supportedImageFormats()]
  155. filename = unicode(QFileDialog.getOpenFileName(self,
  156. '%s - Choose Image', path, 'Image files (%s)' % ' '.join(formats)))
  157. if filename:
  158. self.loadFile(filename)
  159. def check(self):
  160. # TODO: Prompt user to save labels etc.
  161. return True
  162. class Settings(object):
  163. """Convenience dict-like wrapper around QSettings."""
  164. def __init__(self, types=None):
  165. self.data = QSettings()
  166. self.types = defaultdict(lambda: QVariant, types if types else {})
  167. def __setitem__(self, key, value):
  168. t = self.types[key]
  169. self.data.setValue(key,
  170. t(value) if not isinstance(value, t) else value)
  171. def __getitem__(self, key):
  172. return self._cast(key, self.data.value(key))
  173. def get(self, key, default=None):
  174. return self._cast(key, self.data.value(key, default))
  175. def _cast(self, key, value):
  176. # XXX: Very nasty way of converting types to QVariant methods :P
  177. t = self.types[key]
  178. if t != QVariant:
  179. method = getattr(QVariant, re.sub('^Q', 'to', t.__name__, count=1))
  180. return method(value)
  181. return value
  182. class Label(QLabel):
  183. done = pyqtSignal()
  184. epsilon = 7**2 # TODO: Tune value
  185. def __init__(self, *args, **kwargs):
  186. super(Label, self).__init__(*args, **kwargs)
  187. self.points = []
  188. self.shapes = [shape('one', QColor(0, 255, 0))]
  189. def mousePressEvent(self, ev):
  190. self.points.append(ev.pos())
  191. self.shapes[0].addPoint(ev.pos())
  192. if self.isClosed():
  193. self.done.emit()
  194. print "Points:", self.points
  195. self.points = []
  196. self.shapes[0].setFill(True)
  197. self.repaint()
  198. def isClosed(self):
  199. return len(self.points) > 1 and self.closeEnough(self.points[0], self.points[-1])
  200. def closeEnough(self, p1, p2):
  201. def dist(p):
  202. return p.x() * p.x() + p.y() * p.y()
  203. print p1, p2
  204. print abs(dist(p1) - dist(p2)), self.epsilon
  205. return abs(dist(p1) - dist(p2)) < self.epsilon
  206. def paintEvent(self, event):
  207. for shape in self.shapes:
  208. qp = QPainter()
  209. qp.begin(self)
  210. shape.drawShape(qp)
  211. qp.end()
  212. def main(argv):
  213. """Standard boilerplate Qt application code."""
  214. app = QApplication(argv)
  215. app.setApplicationName(__appname__)
  216. win = MainWindow(argv[1] if len(argv) == 2 else None)
  217. win.show()
  218. return app.exec_()
  219. if __name__ == '__main__':
  220. sys.exit(main(sys.argv))