-
Notifications
You must be signed in to change notification settings - Fork 0
/
stroke.py
59 lines (45 loc) · 1.75 KB
/
stroke.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
# This file is part of Optosketch. It is released under the GPL v2 licence.
from PyQt4 import QtGui, QtCore
import numpy as np
import time
from frontend import GenericLine
class StrokeItem(QtGui.QGraphicsPathItem, GenericLine):
def __init__(self, pos=QtCore.QPointF(0.,0.),
color=QtGui.QColor('black'), width = 1, *args, **kwargs):
"""pos is initial position. """
super(StrokeItem, self).__init__(*args, **kwargs)
self.path = QtGui.QPainterPath()
self.path.moveTo(pos)
self.setPath(self.path)
pen = QtGui.QPen(color)
pen.setWidth(width)
self.setPen(pen)
self._time = time.time()
def lineTo(self, *pos):
"""Add a new point to the line."""
self.path.lineTo(*pos)
_time = time.time()
if _time - self._time > 0.1: # Avoid updating every time
self.setPath(self.path)
self._time = _time
def clear(self):
"""Remove every points from the path."""
self.path = QtGui.QPainterPath()
def tonumpy(self):
"""Get current path as a numpy array."""
coords = []
for n in xrange(self.path.elementCount()):
elem = self.path.elementAt(n)
coords.append([elem.x, elem.y])
return np.asarray(coords)
def fromnumpy(self,coords):
"""Set current path with a numpy array.
This method does an append. Use clear()
to remove every point before appending."""
self.path.moveTo(coords[0,0], coords[0,1])
for l in coords[1:]:
self.path.lineTo(l[0], l[1])
self.setPath(self.path)
def save(self, filename):
"""Save the stroke in a file (for debugging)."""
np.savetxt(filename, self.tonumpy())