Last active
August 2, 2021 18:45
-
-
Save cibomahto/2eb823a2ccbddda616048d2c17c6bbf8 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import re | |
import numpy | |
import matplotlib.pyplot as plt | |
from PIL import Image, ImageDraw, ImageFont | |
#### Import gcode ########################################### | |
# Assume perfectly formatted gcode: 'g1x100.0y12.2' | |
def decode_command(val): | |
return [float(i) for i in re.split(r'[gxy]\s*', val)[1:]] | |
with open('sample.gcode') as f: | |
codes = [decode_command(line.rstrip()) for line in f] | |
#### Movement histogram ########################################### | |
# Create deltas | |
deltas = [] | |
for a,b in zip(codes[0:-1], codes[1:]): | |
dist = pow(pow(b[1] - a[1],2) + pow(b[2] - a[2],2),.5) | |
deltas.append(dist) | |
#print(a,b,dist) | |
#print(deltas) | |
plt.rcParams['figure.figsize'] = [12, 8] | |
plt.hist(deltas, 100, range=(0, 1)) | |
plt.xlabel('Distance (units)') | |
plt.ylabel('Count') | |
plt.title('Histogram of movement sizes in sample gcode') | |
plt.show() | |
#### Remove any motions smaller than a threshold ########################################### | |
threshold = 1.5 | |
new_pts = [] | |
last_pt = codes[0] | |
for pt in codes[1:]: | |
dist = pow(pow(pt[1] - last_pt[1],2) + pow(pt[2] - last_pt[2],2),.5) | |
if(dist > threshold): | |
new_pts.append(pt) | |
last_pt = pt | |
print("Original length:{:}, reduced length:{:}".format(len(codes),len(new_pts))) | |
#### Draw the original and reduced images ########################################### | |
xmin = 0 | |
xmax = 0 | |
ymin = 0 | |
ymax = 0 | |
for code in codes: | |
xmin = min(xmin, code[1]) | |
xmax = max(xmax, code[1]) | |
ymin = min(ymin, code[2]) | |
ymax = max(ymax, code[2]) | |
scale = 5 | |
im = Image.new('RGB', (scale*int(xmax)*2, scale*int(ymax)), (0, 0, 0, 0)) | |
draw = ImageDraw.Draw(im) | |
# Plot original | |
draw.text((10,10), "Original ({:} points)".format(len(codes)), fill=(255,255,255,128)) | |
c = 0 | |
for a,b in zip(codes[0:-1], codes[1:]): | |
if c == 0: | |
fill=(255,0,0) | |
else: | |
fill=(0,255,0) | |
c = (c+1) %2 | |
draw.line((scale*a[1],scale*a[2], scale*b[1],scale*b[2]), fill=fill) | |
# And reduced | |
draw.text((scale*int(xmax)+10,10), "Reduced ({:} points)".format(len(new_pts)), fill=(255,255,255,128)) | |
for a,b in zip(new_pts[0:-1], new_pts[1:]): | |
if c == 0: | |
fill=(255,0,0) | |
else: | |
fill=(0,255,0) | |
c = (c+1) %2 | |
draw.line((scale*int(xmax)+scale*a[1],scale*a[2], scale*int(xmax)+scale*b[1],scale*b[2]), fill=fill) | |
im.save('test.png') | |
display(im) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment