-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathshapes.py
More file actions
793 lines (579 loc) · 21.6 KB
/
shapes.py
File metadata and controls
793 lines (579 loc) · 21.6 KB
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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
import math
import string
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
from copy import *
import random
class Point(object):
#TODO Add color to Point
"""
Class that represents an X/Y coordinate pair.
Args:
X (int or float): X-coorinate.
Y (int or float): Y-coordinate.
"""
def __init__(self, x, y):
self.x = x
self.y = y
def get_x(self):
"""
Getter method for a Coordinate object's x coordinate.
"""
return self.x
def get_y(self):
# Getter method for a Coordinate object's y coordinate
return self.y
def get_rounded_x(self):
"""
:return:(int) x coordinate rounded to nearest whole number.
"""
return int(round(self.x))
def get_rounded_y(self):
"""
:return: (int) y coordinate rounded to nearest whole number.
"""
return int(round(self.y))
def get_constrained_x(self, max_x = 255):
"""
:return: (int) X-coodinate constrained to max_x, defaults to 8-bit
range 0-255
"""
return max(min(self.get_rounded_x(), max_x), 0)
def get_constrained_y(self, max_y = 255):
"""
:return: (int) Y-coodinate constrained to max_x, defaults to 8-bit
range 0-255
"""
return max(min(self.get_rounded_y(), max_y), 0)
def calculate_distance(self, other):
"""
Calculates the distance between the point and another point or the
centerpoint of a shape.
Args:
other: Point object or Shape
Returns:
float
"""
return math.sqrt(abs(self.x-other.x) ** 2 + abs(self.y - other.y) ** 2)
def get_binary_x(self, nbits=8):
"""
Returns a string with the n-bits binary representation of the (int) X
coordinate, defaults to 8-bit.
Args:
nbits: number of bits in representation, defaults to 8
Returns:
(str) binary representation of X
"""
return bin(self.get_constrained_x(2**nbits))[2:].zfill(nbits)
def get_binary_y(self, nbits=8):
"""
Returns a string with the n-bits binary representation of the (int) X
coordinate, defaults to 8-bit.
Args:
nbits: number of bits in representation, defaults to 8
Returns:
(str) binary representation of X
"""
return bin(self.get_constrained_y(2 ** nbits))[2:].zfill(nbits)
def __str__(self):
return '<' + str(self.get_x()) + ',' + str(self.get_y()) + '>'
def __eq__(self, other):
if (self.get_x() == other.get_x()) and (self.get_y() == other.get_y()):
return True
return False
def __repr__(self):
return 'Point(' + str(self.x) + ', ' + str(self.y) + ')'
class Shape(Point):
"""
A Shape Object is a subclass of Point and may contain an arbritrary number
of points in any configuration. A Shape has several methods to manipulate
and display it, which include overloaded addition and multiplocation
operators.
"""
def __init__(self, center_Point=Point(0,0), npoints=0, shape_type='NA'):
Point.__init__(self, center_Point.get_x(), center_Point.get_y())
self.shape_type = shape_type
self.points = []
self.npoints = npoints
self.max_x = None
self.min_x = None
self.max_y = None
self.min_y = None
self.centerPoint = center_Point #Center of the bounding rectangle
# Pivot point for translations separate object from centerpoint
self.originPoint = Point(center_Point.x, center_Point.y)
def __repr__(self):
return 'Shape centered at(' + str(self.x) + ', ' + str(self.y) + ')'
def __add__(self, other):
#Combines two shapes in to one by concatenating their points
outPoints = self.points + other.points
try:
outMaxX = max(self.max_x, other.max_x)
outMinX = min(self.min_x, other.min_x)
outMaxY = max(self.max_y, other.max_y)
outMinY = min(self.min_y, other.min_y)
#In case you add to an empty Shape
finally:
outMaxX = other.max_x
outMinX = other.min_x
outMaxY = other.max_y
outMinY = other.min_y
outCenter = Point(outMaxX-outMinX, outMaxY-outMinY)
outShape = Shape(outCenter, len(outPoints), 'composite')
outShape.max_x = outMaxX
outShape.min_x = outMinX
outShape.max_y = outMaxY
outShape.min_y = outMinY
outShape.points = outPoints
return outShape
def __mul__(self, other):
"""
Each point in term_1 Shape becomes a copy of term_2 Shape
Args:
other: (Shape)
Returns: (Shape) of type composite, original shapes are retained
"""
self.shape_type = 'composite'
out = deepcopy(self)
for point in self.points:
cop = deepcopy(other)
cop.translate(point)
out += cop
out._recalculate_centerPoint()
return out
def _recalculate_centerPoint(self):
self.centerPoint = Point(
(self.max_x-self.min_x)/2.0+self.min_x, (self.max_y-self.min_y)/2.0+self.min_y)
self.x = self.centerPoint.get_x()
self.y = self.centerPoint.get_y()
def get_n_points(self):
return len(self.points)
def add_point(self, point, recalculateCenterPoint=True):
"""
Args:
point: Point object to add to the shape
recalculateCenterPoint: (Bool) if the centerpoint should be
recalculated after each addition, some _coordgen functions break if
True.
Returns: None, modifies shape in place
"""
self.points.append(point)
x_in = point.get_x()
y_in = point.get_y()
if self.max_x == None:
self.max_x, self.min_x = x_in, x_in
self.max_y, self.min_y = y_in, y_in
if x_in > self.max_x:
self.max_x = x_in
if y_in > self.max_y:
self.max_y = y_in
if x_in < self.min_x:
self.min_x = x_in
if y_in < self.min_y:
self.min_y = y_in
self.npoints = len(self.points)
if recalculateCenterPoint:
self._recalculate_centerPoint()
def add_points(self, pointlist, recalculateCenterPoint=True):
"""
:param pointlist: (list) list of Point objects to add to the shape
:return: None
"""
for point in pointlist:
self.add_point(point, recalculateCenterPoint)
def get_center_point(self):
"""
Returns: (Point) Centerpoint of Shape
"""
return self.centerPoint
def get_shape_type(self):
"""
:return: (str) Type of shape
"""
return self.shape_type
def get_points(self):
"""
:return: (list) pointlist
"""
return self.points
def get_unique_points(self):
# Order preserving
seen = set()
return [x for x in self.points if x not in seen and not seen.add(x)]
def get_origin_point(self):
"""
Returns: (Point) Origin point of Shape, used as pivot for
transformations
"""
return self.originPoint
def get_sorted_points(self):
#TODO add arbritrary point to sort from
"""
:return:
(list) Points sorted on distance from Origo (0,0)
"""
return sorted(self.points,
key=lambda point: math.sqrt(point.x ** 2 + point.y ** 2))
def get_points_as_C_array(self, variablename):
"""
This method is good in case you want to generate some shapes for
an Arduino.
:return: (str) Points as a C-array consisting of 16-bit words
with x coordinate as MSB, and y as LSB ends with newline.
Args:
variablename: (str) Name of resulting C array
"""
out = "uint16_t %s[] = {" %variablename
for point in self.get_sorted_points():
#Constrains values to 8-bit
x = point.get_constrained_x()
y = point.get_constrained_y()
out += str((x << 8) + y) + ', '
out = string.rstrip(out,', ')
return out + '};\n'
def get_points_as_numpy_array(self, height=256, width=256):
"""
Returns: (numpy array) a width x height array with binary numbers
representing the shape on screen, xy coordinates are cropped
to fit within the array, defaults to 8-bit range (0-255).
"""
outArray = np.zeros((height,width),dtype = bool)
for p in self.get_points():
outArray[p.get_constrained_y(height-1), p.get_constrained_x(width-1)] = True
return outArray
def get_random_point(self):
"""
Returns: random Point from the shape
"""
return random.choice(self.points)
def draw(self, height=256, width=256):
"""
shows the shape as a pyplot
Returns: (Pyplot)
Args:
width: (int) Canvas width in pixels
height: (int) Canvas height in pixels
"""
npArray = self.get_points_as_numpy_array(height, width)
RGB = np.zeros(npArray.shape+(3,))
RGB[npArray>0.5] = [0,1,0]
RGB[npArray<0.5] = [0,0,0]
plt.imshow(RGB)
plt.gca().invert_yaxis()
plt.show()
return plt
def rotate(self, angle):
#TODO fix bug where rotate shrinks shape
"""
Rotates Shape around its origin Point.
Positive angles give counter clockwise rotations.
Returns: Nothing, modifies Shape in place
Args:
(float) or (int) angle: rotational angle in radians
"""
origin = self.originPoint
x0 = origin.get_x()
y0 = origin.get_y()
cos = math.cos(angle)
sin = math.sin(angle)
for i in xrange(len(self.points)):
p = self.points[i]
x1 = p.get_x()
y1 = p.get_y()
#translate to origin
dx = x1 - x0
dy = y1 - y0
#rotate
dx = dx * cos - dy * sin
dy = dx * sin + dy * cos
#translate back
new_x = dx + x0
new_y = dy + y0
self.points[i] = Point(new_x, new_y)
if new_x > self.max_x:
self.max_x = new_x
if new_y > self.max_y:
self.max_y = new_y
if new_x < self.min_x:
self.min_x = new_x
if new_y < self.min_y:
self.min_y = new_y
self._recalculate_centerPoint()
def rotate2(self, angle):
# TODO fix bug where rotate shrinks shape
"""
Rotates Shape around its origin Point.
Positive angles give counter clockwise rotations.
The rotation is done by translating the point to from its
centerpoint to origin, rotating, and translating back to the
centerpoint. This is accomplished by creating matrixes for each of the
operations and then multiplying them together into one transformation
matrix.
Translation cannot be represented as a 2D matrix, therefore we need to
utilize hyperspace (N+1 dimensions).
Returns: Nothing, modifies Shape in place
Args:
(float) or (int) angle: rotational angle in radians
"""
origin = self.originPoint
center = self.centerPoint
cos_alpha = math.cos(angle)
sin_alpha = math.sin(angle)
rotation_matrix = np.array([[cos_alpha, sin_alpha, 0],
[-sin_alpha, cos_alpha, 0],
[0, 0, 1]])
tx = center.get_x() - origin.get_x()
ty = center.get_y() - origin.get_y()
translation_matrix_1 = np.array([[1, 0, 0],
[0, 1, 0],
[-tx, -ty, 1]])
translation_matrix_2 = np.array([[1, 0, 0],
[0, 1, 0],
[tx, ty, 1]])
#transformation_matrix = rotation_matrix
transformation_matrix = np.matmul(translation_matrix_1,
rotation_matrix)
transformation_matrix = np.matmul(transformation_matrix,
translation_matrix_2)
transformation_matrix = translation_matrix_1
for i in xrange(len(self.points)):
p = self.points[i]
pV = np.array([p.get_x(), p.get_y(), 1])
pT = np.matmul(pV, transformation_matrix)
#pT = np.matmul(pV, translation_matrix_1)
new_x, new_y = pT[0], pT[1]
self.points[i] = Point(new_x, new_y)
if new_x > self.max_x:
self.max_x = new_x
if new_y > self.max_y:
self.max_y = new_y
if new_x < self.min_x:
self.min_x = new_x
if new_y < self.min_y:
self.min_y = new_y
self._recalculate_centerPoint()
def set_origin_point(self, point):
"""
Sets the point which all object translations, rotations, scalings,
and shearings are relative to.
Args:
point: Point object to relate all Shape transformations to.
Returns:
None
"""
self.originPoint = point
#TODO shear transformation
def scale(self, xScale, yScale):
#TODO make this work
for i in range(len(self.points)):
p = self.points.pop(0)
new_x = p.get_x() * xScale
new_y = p.get_y() * yScale
self.add_point(Point(new_x, new_y))
def sort_points(self, sortPoint=Point(0,0)):
""" Sorts the pointlist in place on euclidian distance from sortPoint,
defaults to sorting from Origo (0,0).
Args:
sortPoint, Point Object
:return:
None
"""
assert type(sortPoint) is Point, "Not a Point!"
sort_x = sortPoint.get_x()
sort_y = sortPoint.get_y()
self.points.sort(
key=lambda point: math.sqrt((point.get_x()-sort_x) ** 2
+ (point.get_y()-sort_y) ** 2))
def shuffle_points(self):
"""
Randomly shuffles self.points
Returns: None, modifies pointslist in place
"""
random.shuffle(self.points)
def translate(self, translateToPoint):
"""
Translates all points around a new centerpoint.
Args:
translateToPoint: (Point) move Shape center to this point
Returns: (None)
"""
dx = translateToPoint.x - self.originPoint.x
dy = translateToPoint.y - self.originPoint.y
self.originPoint = translateToPoint
self.x += dx
self.y += dy
self.max_x += dx
self.min_x += dx
self.max_y += dy
self.min_y += dy
self.centerPoint = self._recalculate_centerPoint()
for point in self.points:
point.x += dx
point.y += dy
def remove_random_point(self):
"""
Deletes a random point from the shape, updates npoints, and
recalculates bounding rectangel.
Returns: None, modifies Shape in place
"""
self.points.pop(random.randrange(len(self.points)))
self.npoints -= 1
self._recalculate_centerPoint()
class Circle(Shape):
def __init__(self, origo_Point, radius, npoints):
Shape.__init__(self, origo_Point, npoints, 'Circle')
self.radius = radius
self._coordgen()
def _coordgen(self):
"""
Adds equally spaced points along the perimeter of the to the circle
counterclockwise.
"""
alpha = 2 * math.pi / self.npoints
for i in xrange(self.npoints):
x = self.radius * math.cos(alpha*i) + self.x
y = self.radius * math.sin(alpha*i) + self.y
self.add_point(Point(x, y), False)
class Square(Shape):
def __init__(self, center_Point, width, heigth, npoints):
Shape.__init__(self, center_Point, npoints, 'Square')
self.width = width
self.height = heigth
self._coordgen()
def _coordgen(self):
"""
Adds equally spaced points in a clockwise fashion starting from the
bottom left corner.
"""
#TODO Make fix upper left corner point skip bug
npoints=int(self.npoints)
#Calculate corner point coordinates
x0, x1 = self.x-self.width*0.5, self.x+self.width*0.5
y0, y1 = self.y-self.height*0.5, self.y+self.height*0.5
#Calculate perimeter length
perimeter = 2.0*self.width + 2.0*self.height
#Calculate distance between points
dp = float(perimeter)/npoints
#Calculate horizontal and vertical points per side
nHpoints = self.width/dp
nVpoints = self.height/dp
#Start drawing at <x0,y0>
x = x0
y = y0
for i in xrange(npoints):
if i < int(nVpoints):
self.add_point(Point(x,y))
y += dp
elif i == int(nVpoints):
self.add_point(Point(x,y))
remainder = y1 - y
y = y1
x = x0
x += remainder
elif i < int(nVpoints + nHpoints):
self.add_point(Point(x,y))
x += dp
elif i == int(nVpoints + nHpoints):
self.add_point(Point(x,y))
remainder = x1 - x
x=x1
y = y1 - remainder
elif i < int(2 * nVpoints + nHpoints):
self.add_point(Point(x,y))
y -= dp
elif i == int(2 * nVpoints + nHpoints):
self.add_point(Point(x,y))
remainder = y - y0
y = y0
x = x1
x -= remainder
else:
self.add_point(Point(x,y))
x -= dp
class Line(Shape):
"""
A line between two Point objects, containing npoints number of points
"""
def __init__(self, Point0, Point1, npoints):
assert npoints >= 2, "A Line needs at least two points!"
self.x0 = Point0.get_x()
self.y0 = Point0.get_y()
self.x1 = Point1.get_x()
self.y1 = Point1.get_y()
self.length = math.sqrt((self.x1-self.x0)**2+(self.y1-self.y0)**2)
Shape.__init__(self, Point((self.x1-self.x0)/2.0,(self.y1-self.y0)/2.0)
, npoints, 'Line')
self._coordgen()
def _coordgen(self):
"""
Adds npoints equally spaced points along the line.
"""
npoints = int(self.npoints)
#First we add the endpoints
#self.add_point(Point(self.x0, self.y0))
#self.add_point(Point(self.x1, self.y1))
dx = float(self.x1-self.x0)/(self.npoints-1)
dy = float(self.y1-self.y0)/(self.npoints-1)
for i in xrange(npoints):
x = self.x0 + i * dx
y = self.y0 + i * dy
self.add_point(Point(x, y), False)
self._recalculate_centerPoint()
class Bezier(Shape):
"""
A quadratic bezier curve between p0 and p3 with p1 & p2 as control points
"""
def __init__(self, p0, p1, p2, p3, npoints):
self.p0 = p0
self.p1 = p1
self.p2 = p2
self.p3 = p3
Shape.__init__(self, Point((p3.get_x()-p0.get_x())/2.0,
(p3.get_y()-p0.get_y())/2.0),
npoints, 'Bezier')
self._coordgen()
def _coordgen(self):
"""
Adds npoints equally spaced points along the Bezier curve.
Implementation is based on Matrix representation of quadratic Bezier
curves, where x(t) = [1, t, t**2, t**3] x M x P
M: 4x4 matrix with bernstein polynomial coefficients
P: 4x1 matrix with x/y coordinates of control points
"""
#Generates a list of equally spaced t:s between 0 and 1 using linspace
tlist = list(np.linspace(0,1, self.npoints))
#A matrix containing the coefficients of the bernstein polynmials for a
# quadratic Bezier curve
bernsteinPolynomials = np.array([[1, 0, 0, 0],
[-3, 3, 0, 0],
[3, -6, 3, 0],
[-1, 3, -3, 1]])
#Control point x/y values as 1x4 column matrixes
controlX = np.array([[self.p0.get_x()],
[self.p1.get_x()],
[self.p2.get_x()],
[self.p3.get_x()]])
controlY = np.array([[self.p0.get_y()],
[self.p1.get_y()],
[self.p2.get_y()],
[self.p3.get_y()]])
for t in tlist:
tarray = np.array([1, t, t**2, t**3])
x = tarray.dot(bernsteinPolynomials).dot(controlX)
y = tarray.dot(bernsteinPolynomials).dot(controlY)
self.add_point(Point(float(x), float(y)))
def binaryNumpyArrayToPoints(array):
nrows, ncols = array.shape
out = []
for r in xrange(nrows):
for c in xrange(ncols):
if array[r,c]:
out.append(Point(r,c))
return out
def imageToShape(image_filename):
arr = mpimg.imread(image_filename)
points = binaryNumpyArrayToPoints(arr)
outShape=Shape(Point(127,127))
outShape.add_points(points)
return outShape