Repository navigation
Expand file tree
/
Copy pathimage-to-gcode.py
More file actions
3361 lines (2751 loc) · 134 KB
/
Copy pathimage-to-gcode.py
File metadata and controls
3361 lines (2751 loc) · 134 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
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/python
## image-to-gcode is free software; you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by the
## Free Software Foundation; either version 2 of the License, or (at your
## option) any later version. image-to-gcode is distributed in the hope
## that it will be useful, but WITHOUT ANY WARRANTY; without even the implied
## warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See
## the GNU General Public License for more details. You should have
## received a copy of the GNU General Public License along with image-to-gcode;
## if not, write to the Free Software Foundation, Inc., 59 Temple Place,
## Suite 330, Boston, MA 02111-1307 USA
##
## image-to-gcode.py is Copyright (C) 2005 Chris Radek
## chris@timeguy.com
## image-to-gcode.py is Copyright (C) 2006 Jeff Epler
## jepler@unpy.net
## image-to-gcode.py is Copyright (C) 2013 Harmonist
## cnc-club.ru
## image-to-gcode.py is Copyright (C) 2018 Yaroslav Vlasov
## ysvlasov@yandex.ru
VersionI2G = "3.8.9"
printToFile = True
generateGcode = True #for debug
platformWin = True
importingTkError = False
importingError = False
importErrStr = ""
import sys, os
BASE = os.path.abspath(os.path.join(os.path.dirname(sys.argv[0]), ".."))
sys.path.insert(0, os.path.join(BASE, "lib", "python"))
originalStdout = sys.stdout
if (os.name != "nt"):
platformWin = False
import gettext;
gettext.install("linuxcnc", localedir=os.path.join(BASE, "share", "locale"), unicode=True)
try:
from PIL import Image
except ImportError:
importingError = True
importErrStr += "Pillow\n"
try:
import numpy as numarray
import numpy.core
olderr = numpy.core.seterr(divide='ignore')
plus_inf = (numarray.array((1.,))/0.)[0]
numpy.core.seterr(**olderr)
except ImportError:
importingError = True
importErrStr += "numpy\n"
from author import Gcode
from math import *
import operator
import datetime
try:
import Tkinter
except ImportError:
print 'Tkinter are not installed! for linux use: "sudo apt-get install python-tk"'
raw_input ("Press enter to exit ")
importingTkError = True
importingError = True
if ((importingError) and not(importingTkError)):
window = Tkinter.Tk()
window.title("Missing modules")
window.geometry('400x200')
lbl = Tkinter.Label(window, text="The following modules are not installed:\n"+importErrStr, justify="left")
lbl.grid(column=0, row=0)
window.mainloop()
epsilon = 1e-5
epsilon16 = 1e-16
is_ddd1 = True
roughing_depth_delta = 0.2 # ~20%
prn_detail = 1 #Print detail (10)
def ball_tool(r,rad):
if r == rad: return rad
#s = -sqrt(rad**2-r**2)
s = rad-sqrt(rad**2-r**2)
return s
def endmill(r,dia):
return 0
def vee_common(angle):
#slope = tan(angle * pi / 180)
slope = tan(radians((180-angle)/2) )
def f(r, dia):
return r * slope
return f
#def vee_common_new():
# slope = 0
# def f(r, dia):
# return r * slope
# return f
#
# def init(angle):
# slope = tan(((180-angle)/2) * pi / 180)
tool_makers = [ ball_tool, endmill, vee_common(30), vee_common(45), vee_common(60), vee_common(90)]
def tool_info(tool_type=0, wdia=0, wdia2=-9999, degr=60, units=0):
toolTypeStr = ("Ball End","Flat End","30 Degree","45 Degree","60 Degree","90 Degree","?")
if units == 0:
unitsStr = "inch"
else:
unitsStr = "mm"
print "( Tool info: )"
if wdia2 > wdia and degr > 0 and degr < 180:
print "( Tool type: Cone {0} )".format(toolTypeStr[tool_type])
print "( Tool diameter: {0}{1} )".format(wdia2,unitsStr)
print "( Tool tip diameter: {0}{1} )".format(wdia,unitsStr)
print "( Tool angle: {0}degree )".format(degr)
print "( Tool conical segment approx length: {0:.2f}{1} )".format(((wdia2/2)/tan(radians(degr/2)))-((wdia/2)/tan(radians(degr/2))),unitsStr)
else:
print "( Tool type: {0} )".format(toolTypeStr[tool_type])
print "( Tool diameter: {0}{1} )".format(wdia,unitsStr)
def make_tool_shape(f, wdia, resp, is_offset= False, tool_type=0, wdia2=-9999, degr=60, units=0):
res = 1. / resp
# if cell_center: =-> 'smooth terrain, but can cut the edge';
# elif 'cell_contact' in other words 'Touch a cell at the nearest point': =-> 'more accurate'
#
# if cell_coeff == 0 - 0% - the same as 'cell contact';
# if cell_coeff ==2/3 - 33% - this is '33% from cell contact';
# if cell_coeff == 1 - 50% - this is 'cell center';
# if cell_coeff == 2 - 100% - this is 'the far corner of the cell'; This is MAX of cell_coeff.
cell_coeff = 2./3.
# that there - dia - is always an odd
# because that more accurately
always_an_odd = True
dia = int(wdia*res)
if dia/res < wdia: dia = dia +1
if dia < 1: dia = 1
if is_offset:
if dia == 1:
dia = 2
if prn_detail > 0: print "(Warning: offset[{0}] <= pixel size[{1}]! Use function correct_offset!)".format((wdia/2),resp)
#this not enaf! Use function correct_offset - for correct offset!
wdia = resp*2
if always_an_odd and not dia % 2: dia = dia +1
if is_offset and prn_detail > 0: print "(Real offset = {0} dia: {1} pixels)".format((dia*resp/2),dia)
wrad = wdia/2.
wrad0= wrad
if wdia2 > wdia and degr > 0 and degr < 180:
degr2 = (180-degr)/2
f2 = vee_common(degr)
if tool_type == 0:
wrad0 = cos(radians(90-degr2))*wrad
if wrad0 > wrad or wrad0 == 0 and prn_detail > -1: print "( Error tool2(2): ",wrad0, " )"
if prn_detail > 1: print "( Radius of Ball End: {0:.2f} )".format(wrad0)
if tool_type == 0: h0 = (wrad - sin(radians(90-degr2))*wrad) / sin(radians(90-degr2))
elif tool_type == 1: h0 = wrad/tan(radians(degr/2))
elif tool_type == 2: h0 = f2(wrad, wrad) - f(wrad, wrad)
elif tool_type == 3: h0 = f2(wrad, wrad) - f(wrad, wrad)
elif tool_type == 4: h0 = f2(wrad, wrad) - f(wrad, wrad)
elif tool_type == 5: h0 = f2(wrad, wrad) - f(wrad, wrad)
wrad2 = wdia2/2.
dia2= int(wdia2*res+.5)
if dia2/res < wdia2: dia2 = dia2 +1
if always_an_odd and not dia2 % 2: dia2 = dia2 +1
dia = max(dia,dia2)
else:
wrad2 = -plus_inf
#n = numarray.array([[plus_inf] * dia] * dia, type="Float32")
n = numarray.array([[plus_inf] * dia] * dia, "Float32")
hdia = dia / 2.
#hdia = int(hdia)
l = []
for x in range(dia):
for y in range(dia):
if dia % 2 and x == dia/2 and y == dia/2:
z = f(0, wrad)
l.append(z)
if z != 0.:
if prn_detail > -1: print "( Error(0) tool center mast be = 0, bat z=",z, " )"
z = 0
n[x,y] = z # z = 0 - mast be
else:
x1 = x-hdia
y1 = y-hdia
dopx2 = 0.
dopy2 = 0.
if x1 <= 0. and y1 < 0.:
if x1 == 0.: dopx = 0.
elif x1 >= -.5: dopx = 0.5
else:
dopx = 1
dopx2 = -0.5
if y1 == 0.: dopy = 0.
elif y1 >= -.5: dopy = 0.5
else:
dopy = 1
dopy2 = -0.5
elif x1 <= 0.:
if x1 == 0.: dopx = 0.
elif x1 >= -.5: dopx = 0.5
else:
dopx = 1
dopx2 = -0.5
dopy = 0
dopy2 = 0.5
elif y1 < 0.:
dopx = 0
dopx2 = 0.5
if y1 == 0.: dopy = 0.
elif y1 >= -.5: dopy = 0.5
else:
dopy = 1
dopy2 = -0.5
else:
dopx = 0
dopy = 0
dopx2 = 0.5
dopy2 = 0.5
dopx2 *= cell_coeff
dopy2 *= cell_coeff
r = hypot(x1+dopx+dopx2, y1+dopy+dopy2) * resp
if r < wrad0:
z = f(r, wrad)
l.append(z)
n[x,y] = z
if z < 0. and prn_detail > -1: print "( tool error 1: r=",r," x=",x," y=",y," hight<0 hight= ",z,", mast be >= 0 )"
#if z > 300: print(" error 1: tool hight1: r=",r," x=",x," y=",y," hight= ",z," is too big!")
elif r < wrad2:
z = f2(r,wrad2) - h0
l.append(z)
n[x,y] = z
if z < 0. and prn_detail > -1: print "( tool error 2: r=",r," x=",x," y=",y," z<0 z= ",z,", mast be >= 0 )"
#if z > 300: print(" error 2: tool hight1: r=",r," x=",x," y=",y," hight= ",z," is too big!")
if n.min() != 0. and prn_detail > -1: print "( error(0): tool.minimum = ",n.min(),", mast be == 0 )"
return n
def correct_offset(offset, resp):
if offset > epsilon and offset < resp:
if prn_detail > -1: print "(Warning: offset[{0}] <= pixel size[{1}]. New offset = {1} units)".format(offset,resp)
offset = resp
return offset
def optim_tool_shape(n,hig,offset,tolerance):
#return n
lineLF = -1
minH = hig+offset+tolerance+.5
P = True
dia = len(n)
while P and lineLF < (dia-1):
lineLF = lineLF + 1
#left
for x in range(dia):
if n[lineLF,x] < minH:
P = False
break
if P:
#up
for y in range(dia):
if n[y,lineLF] < minH:
P = False
break
#@ dia = 3, lineLF = 1
#lineLF = lineLF - 1
if lineLF > 0:
P = True
line2 = dia
while P and line2 >= lineLF:
line2 = line2 - 1
#right
for x in range(dia):
if n[line2,x] < minH:
P = False
break
if P:
#down
for y in range(dia):
if n[y,line2] < minH:
P = False
break
#@ dia = 3, line2 = 1
line2 = line2 + 1
if prn_detail > 1: print "( tool opitimize - dia = ",dia," lines:)"
if prn_detail > 1: print "( cut lines[left and up ]: ",lineLF,")"
if prn_detail > 1: print "( cut lines[right and down]: ",(dia-line2),")"
if line2 < dia:
dia2 = line2 - lineLF
n2 = numarray.array([[plus_inf] * dia2] * dia2, "Float32")
d2range = range(lineLF,line2)
for x in d2range:
for y in d2range:
n2[x-lineLF,y-lineLF] = n[x,y]
else:
dia2 = dia - lineLF
n2 = numarray.array([[plus_inf] * dia2] * dia2, "Float32")
d2range = range(lineLF,dia)
for x in d2range:
for y in d2range:
n2[x-lineLF,y-lineLF] = n[x,y]
if len(n2) == 0 and prn_detail > -1: print "( Error(): ",dia,lineLF,line2," )"
if n2.min() <> 0 and prn_detail > -1: print "( Error(): n2=",n2," )"
return n2
else:
return n
def amax(seq):
res = 0
for i in seq:
if abs(i) > abs(res): res = i
return res
def group_by_sign(seq, slop=sin(pi/18), key=lambda x:x):
sign = None
subseq = []
for i in seq:
ki = key(i)
if sign is None:
subseq.append(i)
if ki != 0:
sign = ki / abs(ki)
else:
subseq.append(i)
if sign * ki < -slop:
sign = ki / abs(ki)
yield subseq
subseq = [i]
if subseq: yield subseq
class Convert_Scan_Alternating:
def __init__(self):
self.st = 0
def __call__(self, primary, items):
st = self.st = self.st + 1
if st % 2: items.reverse()
if st == 1: yield True, items
else: yield False, items
def reset(self):
self.st = 0
class Convert_Scan_Increasing:
def __call__(self, primary, items):
yield True, items
def reset(self):
pass
class Convert_Scan_Decreasing:
def __call__(self, primary, items):
items.reverse()
yield True, items
def reset(self):
pass
class Convert_Scan_Upmill:
def __init__(self, slop = sin(pi / 18)):
self.slop = slop
def __call__(self, primary, items):
for span in group_by_sign(items, self.slop, operator.itemgetter(2)):
if amax([it[2] for it in span]) < 0:
span.reverse()
yield True, span
def reset(self):
pass
class Convert_Scan_Downmill:
def __init__(self, slop = sin(pi / 18)):
self.slop = slop
def __call__(self, primary, items):
for span in group_by_sign(items, self.slop, operator.itemgetter(2)):
if amax([it[2] for it in span]) > 0:
span.reverse()
yield True, span
def reset(self):
pass
class Reduce_Scan_Lace:
def __init__(self, converter, slope, keep):
self.converter = converter
self.slope = slope
self.keep = keep
def __call__(self, primary, items):
slope = self.slope
keep = self.keep
if primary:
idx = 3
test = operator.le
else:
idx = 2
test = operator.ge
def bos(j):
return j - j % keep
def eos(j):
if j % keep == 0: return j
return j + keep - j%keep
for i, (flag, span) in enumerate(self.converter(primary, items)):
subspan = []
a = None
for i, si in enumerate(span):
ki = si[idx]
if a is None:
if test(abs(ki), slope):
a = b = i
else:
if test(abs(ki), slope):
b = i
else:
if i - b < keep: continue
yield True, span[bos(a):eos(b+1)]
a = None
if a is not None:
yield True, span[a:]
def reset(self):
self.converter.reset()
unitcodes = ['G20', 'G21']
convert_makers = [ Convert_Scan_Increasing, Convert_Scan_Decreasing, Convert_Scan_Alternating, Convert_Scan_Upmill, Convert_Scan_Downmill ]
def progress(a, b, cstr="FILTER_PROGRESS=%d"):
print >> originalStdout, "\rProgress: {0:6.2f}%".format((a*100./b+.5)),
#originalStdout.flush()
if os.environ.has_key("AXIS_PROGRESS_BAR"):
print >>sys.stderr, cstr % int(a*100./b+.5)
sys.stderr.flush()
class Converter:
def __init__(self,
image, units, tool_shape, pixelsize, pixelstep, safetyheight, \
tolerance, feed, convert_rows, convert_cols, cols_first_flag,
entry_cut, spindle_speed, roughing_offset, roughing_depth,
roughing_feed,background_border,cut_top_jumper,
optimize_path,layer_by_layer,
max_bg_len,pattern_objectiv,
roughing_minus_finishing,pixelstep_roughing,tool_roughing,min_delta_rmf,
previous_offset):
self.image = image
self.units = units
self.tool = tool_shape
self.pixelsize = pixelsize
self.pixelstep = pixelstep
self.safetyheight = safetyheight
self.tolerance = tolerance
self.base_feed = feed
self.convert_rows = convert_rows
self.convert_cols = convert_cols
self.cols_first_flag = cols_first_flag
self.entry_cut = entry_cut
self.spindle_speed = spindle_speed
self.roughing_offset = roughing_offset
self.previous_offset = previous_offset
self.roughing_depth = roughing_depth
self.roughing_feed = roughing_feed
self.background_border = background_border
self.cut_top_jumper = cut_top_jumper
self.optimize_path = optimize_path
self.layer_by_layer = layer_by_layer
self.max_bg_len = max_bg_len
self.pattern_objectiv = pattern_objectiv
self.row_mill = (self.convert_rows != None)
self.start_moment = datetime.datetime.now()
self.roughing_offset = correct_offset(self.roughing_offset, self.pixelsize)
self.previous_offset = correct_offset(self.previous_offset, self.pixelsize)
self.layer = 0
self.MaxBackground_down = (self.image.min()+self.background_border);
self.MaxBackground_up = (self.image.max()-self.background_border);
if prn_detail > 0 and self.background_border > .0:
if self.cut_top_jumper:
print "(Background border = {0} units, Background down = {1} units, Background up = {2} units)".format(self.background_border,\
self.MaxBackground_down,self.MaxBackground_up)
else:
print "(Background border = {0} units, Background down = {1} units)".format(self.background_border,self.MaxBackground_down)
w, h = self.w, self.h = image.shape
self.roughing_minus_finishing = roughing_minus_finishing
if self.roughing_minus_finishing:
self.pixelstep_roughing = pixelstep_roughing
self.tool_roughing = tool_roughing
self.min_delta_rmf = min_delta_rmf
#I did not use the function 'get_RowCol' to quickly work out.
if self.row_mill:
self.map_tool2 = numarray.zeros((w, h), 'Float32') - plus_inf
# map_rmf>=0 - True; map_rmf<0 - False
self.map_rmf = numarray.zeros((w, h), 'Float32') - plus_inf
else:
self.map_tool2 = numarray.zeros((h, w), 'Float32') - plus_inf
# map_rmf>=0 - True; map_rmf<0 - False
self.map_rmf = numarray.zeros((h, w), 'Float32') - plus_inf
self.map_tool2 = numarray.zeros((w, h), 'Float32') - plus_inf
# map_rmf>=0 - True; map_rmf<0 - False
#self.map_rmf = numarray.zeros((w, h), 'Float32') - plus_inf
self.cache = {}
self.cache_abs = {}
ts = self.ts = tool_shape.shape[0]
if prn_detail > 0: print "(Tool shape = {0} pixels)".format(ts)
# "-1" - for functions get_dz_dy and get_dz_dx - code "+1"
self.h1 = h - ts -1
self.w1 = w - ts -1
self.ts2 = self.ts/2
#self.tool_shape = tool_shape * self.pixelsize * ts / 2;
def one_pass(self):
g = self.g
g.set_feed(self.feed)
self.layer = self.layer + 1
if prn_detail > 0:
print "(Layer {0} layer depth {1})".format(self.layer,self.layer_depth)
if printToFile:
print >> originalStdout, "Layer {0} layer depth {1} is started, pleas wait...".format(self.layer,self.layer_depth)
if self.convert_cols and self.cols_first_flag:
self.row_mill = False
self.g.set_plane(19)
if self.roughing_minus_finishing:
if prn_detail > 0: print "(Error(!) This function is not implemented!)"
elif self.pattern_objectiv:
self.mill_objectiv(self.convert_cols, True)
else:
self.mill_cols(self.convert_cols, True)
if self.convert_rows: g.safety()
if self.convert_rows:
self.row_mill = True
self.g.set_plane(18)
if self.pattern_objectiv:
self.mill_objectiv(self.convert_rows, not self.cols_first_flag)
else:
self.mill_rows(self.convert_rows, not self.cols_first_flag)
if self.convert_cols and not self.cols_first_flag:
self.row_mill = False
self.g.set_plane(19)
if self.convert_rows: g.safety()
if self.pattern_objectiv:
self.mill_objectiv(self.convert_cols, not self.convert_rows)
else:
self.mill_cols(self.convert_cols, not self.convert_rows)
if self.convert_cols:
self.convert_cols.reset()
if self.convert_rows:
self.convert_rows.reset()
g.safety()
def get_rmf_map_tool_next(self,base_image,map_tool1,roughing_offset,tool_diameter,tool_type,pixelstep,roughing_depth,min_delta_rmf):
# delta_map_tool_next = min(map_tool_previous,map_tool_next)
#testing only for "Rows"!!! "Cols" - not testing!!!
jrange = range(self.w1)
irange = range(self.h1)
trange = range(0,self.ts)
for y in jrange: #lines image
for x in irange: #pixels image
for i in trange: #lines tool
for j in trange: #pixels tool
ty = i+y
tx = j+x
map_tool1[ty,tx] = self.map_tool2[ty,tx]
#clear caches
self.map_rmf[:] = -plus_inf
self.map_tool2[:] = -plus_inf
self.cache.clear()
self.cache_abs.clear()
# new params and tool
if self.roughing_offset != roughing_offset:
self.roughing_offset = roughing_offset
self.image = base_image
self.image = self.make_offset(self.roughing_offset,self.image)
self.tool = make_tool_shape(tool_type, tool_diameter, self.pixelsize)
self.tool = optim_tool_shape(self.tool,-base_image.min(),self.roughing_offset,max(self.pixelsize,self.tolerance))
self.pixelstep = pixelstep
self.roughing_depth = roughing_depth
self.min_delta_rmf = min_delta_rmf
self.ts = self.tool.shape[0]
if prn_detail > 0: print "(Next tool shape = {0} pixels)".format(self.ts)
# "-1" - for functions get_dz_dy and get_dz_dx - code "+1"
self.h1 = self.h - self.ts -1
self.w1 = self.w - self.ts -1
self.ts2 = self.ts/2
return map_tool1
def make_offset(self,offset,image):
if offset > epsilon16:
rough = make_tool_shape(ball_tool,
2*offset, self.pixelsize, True)
rough = optim_tool_shape(rough,-image.min(),offset,max(self.pixelsize,self.tolerance))
w, h = image.shape
tw, th = rough.shape
w1 = w + tw
h1 = h + th
nim1 = numarray.zeros((w1, h1), 'Float32') + image.min()
nim1[tw/2:tw/2+w, th/2:th/2+h] = image
image = numarray.zeros((w,h), "Float32")
for j in range(0, w):
progress(j,w)
for i in range(0, h):
image[j,i] = (nim1[j:j+tw,i:i+th] - rough).max()
return image
def convert(self):
self.g = g = Gcode(safetyheight=self.safetyheight,
tolerance=self.tolerance,
spindle_speed=self.spindle_speed,
units=self.units)
g.begin()
g.continuous(self.tolerance)
g.safety()
if prn_detail > 0:
print "(Start make g-kod at {0})".format(datetime.datetime.now())
if printToFile:
print >> originalStdout, "Start make g-kod at {0}, please wait...".format(datetime.datetime.now())
if self.safetyheight == 0 and prn_detail > -1:
print "(Warning: safety height = 0! You can give error like: 'Start of arc is the same as end!')"
if prn_detail > -1 and self.MaxBackground_up <= self.MaxBackground_down:
print "Error(!): Max background border down[{0}] >= Max background border up[{1}]! G-kode can not be formed.".format(self.MaxBackground_down, self.MaxBackground_up)
print " ...check background_border and image depth!"
return
self.layer_depth_prev = 9999.0 #'layer_depth_prev' need for 'optimize_path'
if self.pattern_objectiv:
base_image = self.image
self.feed = self.roughing_feed
if not self.roughing_minus_finishing:
self.image = self.make_offset(self.roughing_offset,self.image)
else:
offset_image = self.make_offset(self.previous_offset,self.image)
self.layer_depth = self.image.min()
map_tool1 = self.get_rmf_map_tool(offset_image,self.tool_roughing,self.previous_offset,self.pixelstep_roughing)
self.image = self.make_offset(self.roughing_offset,self.image)
self.ro = self.roughing_offset
self.set_rmf(base_image,map_tool1)
#comented corth not used get_z in set_rmf and get_rmf_map_tool
#self.cache.clear()
#The following code is needed if you are using not two, but 3, 4, 5, ... cutter,
# and want to make a difference between:
# what is left clean after used cutter
# and next cutter.
'''#----------------------------------------------------------------
# delta_map_tool2 = min(map_tool1,map_tool2)
next_roughing_offset = 0.3
next_tool_diameter = 1.5
next_tool_type = ball_tool
next_pixelstep = 1
next_roughing_depth = 1.7
next_min_delta_rmf = 2.0 #0.0 #1.8 #
map_tool2 = self.get_rmf_map_tool_next(base_image,map_tool1,next_roughing_offset,next_tool_diameter,\
next_tool_type,next_pixelstep,next_roughing_depth,next_min_delta_rmf)
self.set_rmf(base_image,map_tool2)
#----------------------------------------------------------------'''
'''#----------------------------------------------------------------
# delta_map_tool3 = min(map_tool2,map_tool3)
next_roughing_offset = 0
next_tool_diameter = 0.4
next_tool_type = ball_tool
next_pixelstep = 1
next_roughing_depth = 0.4
next_min_delta_rmf = 1.2 #0.3 #
map_tool3 = self.get_rmf_map_tool_next(base_image,map_tool2,next_roughing_offset,next_tool_diameter,\
next_tool_type,next_pixelstep,next_roughing_depth,next_min_delta_rmf)
self.set_rmf(base_image,map_tool3)
#----------------------------------------------------------------'''
elif (self.roughing_depth > epsilon16 and self.roughing_offset > epsilon16) or (self.roughing_depth > epsilon16 and self.optimize_path > epsilon16):
base_image = self.image
self.image = self.make_offset(self.roughing_offset,self.image)
self.feed = self.roughing_feed
self.ro = self.roughing_offset
m = self.image.min() + self.ro
r = -self.roughing_depth
self.layer_depth = .0
while r > m:
self.layer_depth = r
self.one_pass()
self.layer_depth_prev = self.layer_depth #'layer_depth_prev' need for 'optimize_path'
r = r - self.roughing_depth
if self.layer_depth_prev > m + epsilon:
self.layer_depth = m
if prn_detail > 0: print "(Layer: {0} previous LD={1} < m[{2}]+epsilon[{3}]={4})".format(self.layer,self.layer_depth,m,epsilon,(m + epsilon))
self.one_pass()
self.layer_depth_prev = self.layer_depth #'layer_depth_prev' need for 'optimize_path'
self.optimize_path = False
self.image = base_image
self.cache.clear()
self.feed = self.base_feed
if self.roughing_minus_finishing or self.optimize_path:
self.ro = self.roughing_offset
else:
self.ro = 0.
self.layer_depth = self.image.min()
self.one_pass()
g.end()
timing = "End make at: "+str(datetime.datetime.now().strftime("%d-%m-%Y %H:%M:%S"))+" Total time: "+str((datetime.datetime.now()-self.start_moment))
if prn_detail > 0: print "( {0} )".format(timing)
print >> originalStdout, "\rProgress: 100% completed.\nSUCCESS!\n\n", timing
def get_dz_dy(self, x, y):
y1 = max(0, y-1)
y2 = min(self.image.shape[0]-1, y+1)
#y2 = min(self.image.shape[0]-1-self.ts, y+1)
dy = self.pixelsize * (y2-y1)
return ((self.get_z(x, y2)) - (self.get_z(x, y1))) / dy
def get_dz_dx(self, x, y):
x1 = max(0, x-1)
x2 = min(self.image.shape[1]-1, x+1)
#x2 = min(self.image.shape[1]-1-self.ts, x+1)
dx = self.pixelsize * (x2-x1)
return ((self.get_z(x2, y)) - (self.get_z(x1, y))) / dx
def get_z(self, x, y):
try:
return min(0, max(self.layer_depth, self.cache[x,y])) + self.ro
except KeyError:
m1 = self.image[y:y+self.ts, x:x+self.ts]
#if you get ERROR in line below - this means
# that Y or X LARGER than the size of image! Probably Y its X and X its Y...
self.cache[x,y] = d = (m1 - self.tool).max()
return min(0, max(self.layer_depth, d)) + self.ro
def get_RowCol(self, x, y):
if self.row_mill:
return x,y
else:
return y,x
def get_z_abs(self, x, y):
try:
return min(0, self.cache_abs[x,y])
except KeyError:
m1 = self.image[y:y+self.ts, x:x+self.ts]
#if you get ERROR in line below - this means
# that Y or X LARGER than the size of image! Probably Y its X and X its Y...
d = (m1 - self.tool).max()
self.cache_abs[x,y] = d
return min(0,d)
def get_rmf_map_tool(self,offset_image,tool_roughing,previous_offset,pixelstep_roughing):
#Dictionary faster then array
map_tool1 = {} #numarray.zeros((self.w, self.h), 'Float32') - self.image.min()
ts_roughing = tool_roughing.shape[0]
if prn_detail > 0: print "(Previous tool shape: {0} pixels)".format(ts_roughing)
if self.row_mill:
jrange = range(0, self.w - ts_roughing - 1, pixelstep_roughing)
irange = range(0, self.h - ts_roughing - 1)
ln = self.w - ts_roughing - 1
else:
jrange = range(0, self.h - ts_roughing - 1, pixelstep_roughing)
irange = range(0, self.w - ts_roughing - 1)
ln = self.h - ts_roughing - 1
if (len(jrange) == 0 or len(irange) == 0) and prn_detail > -1:
print "(WARNING! Perhaps: previous tool diametr[{0} pixels] is larger then len of image[{1}, {2}]! )".format(ts_roughing,self.w,self.h)
trange = range(0,ts_roughing)
for ry in jrange: #lines
progress(ry, ln)
for rx in irange: #pixels
if self.row_mill:
y,x = ry,rx
else:
x,y = ry,rx
m1 = offset_image[y:y+ts_roughing, x:x+ts_roughing]
hhh1 = (m1 - tool_roughing).max() + previous_offset
for i in trange: #lines tool
for j in trange: #pixels tool
t = tool_roughing[i,j]
if isinf(t): continue
ty = i+y
tx = j+x
# self.image[ty,tx] <= hhh1 !!! t >= 0
dt = -self.image[ty,tx] + hhh1 + t
#dt = round(dt,16)
if dt < -epsilon and prn_detail > -1: print "( delta < -0.00001 ",ty,tx,dt,self.image[ty,tx], hhh1, t," )"
if dt < .0: dt = .0
try:
if map_tool1[ty,tx] > dt:
map_tool1[ty,tx] = dt
except KeyError:
map_tool1[ty,tx] = dt
if prn_detail > 0: print "(End make map tool1. Map len: {0}. End at {1})".format(len(map_tool1),datetime.datetime.now())
if len(map_tool1) == 0 and prn_detail > -1: print "(WARNING! Map tool1 len: {0}! )".format(len(map_tool1))
return map_tool1
def set_rmf(self,base_image,map_tool1):
#map_tool2 = {}
if self.row_mill:
jrange = range(0, self.w1, self.pixelstep)
irange = range(0, self.h1)
ln = self.w1
else:
jrange = range(0, self.h1, self.pixelstep)
irange = range(0, self.w1)
ln = self.h1
trange = range(0,self.ts)
for lin in jrange: #lines
progress(lin, ln)
for pix in irange: #pixels
if self.row_mill:
y,x = lin,pix
else:
x,y = lin,pix
hhh1 = self.get_z(x,y)
founded = False
for i in trange: #lines tool
for j in trange: #pixels tool
t = self.tool[i,j]
if isinf(t): continue
ty = i+y
tx = j+x
#dt - without offset (base_image != self.image)!
im = -base_image[ty,tx]
dt = im + hhh1 + t #-base_image[ty,tx] + min(0.0, hhh1 + t)
#dt = round(dt,16)
if dt < -epsilon and prn_detail > -1:
print "( delta[{0}] < -0.00001 y,x[{1}, {2}] image={3} hhh1={4} tool={5})".format(dt,ty,tx,base_image[ty,tx], hhh1, t)
if dt < .0: dt = .0
if isinf(self.map_tool2[ty,tx]) or self.map_tool2[ty,tx] > dt:
self.map_tool2[ty,tx] = dt
try:
# "dt" must be >= "map_tool1", but not always
delta = map_tool1[ty,tx] - dt
except:
#1. Angles of image, at a round instrument.
#2. When 'previous tool diametr' is greater then image len.
#3. ?
delta = im
try:
if delta >= self.min_delta_rmf:
#find minimum of delta
if isinf(self.map_rmf[lin,pix]) or delta >= self.map_rmf[lin,pix]: #(y,x)!!! Not (ty,tx)!!!
#self.map_rmf[lin,pix] = delta
if self.min_delta_rmf == 0 and delta == 0:
if self.not_background(hhh1-self.roughing_offset,lin,pix):
self.map_rmf[lin,pix] = epsilon16
#else: self.map_rmf[lin,pix] = -1
else:
self.map_rmf[lin,pix] = delta
elif self.min_delta_rmf == 0 and delta < 0 and isinf(self.map_rmf[lin,pix]):
#self.map_rmf[lin,pix] = epsilon16
if self.not_background(hhh1-self.roughing_offset,lin,pix):
self.map_rmf[lin,pix] = epsilon16
else:
self.map_rmf[lin,pix] = -1
except: pass
if prn_detail > 0:
print "(Base min delta 'Roughing Minus Finish': {0} units)".format(self.min_delta_rmf)
print "( Min delta 'Roughing Minus Finish': {0} units)".format(self.map_rmf.min())
if self.map_rmf.min() < self.min_delta_rmf:
print "(Warning: Min delta [{0}] < Base min delta[{1}] )".format(self.map_rmf.min(),self.min_delta_rmf)
print "( Max delta 'Roughing Minus Finish': {0} units)".format(self.map_rmf.max())
if self.map_rmf.max() < self.min_delta_rmf:
print "(Error: Max delta [{0}] < Base min delta[{1}] )".format(self.map_rmf.max(),self.min_delta_rmf)
if self.map_rmf.max() < 0 and prn_detail > -1: print "(Error() Min RMF: {0} < 0 units)".format(self.map_rmf.max())
if prn_detail > 0: print "(End make map rmf at {0})".format(datetime.datetime.now())
return