image2gcode 1.2.0__py3-none-any.whl → 2.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: image2gcode
3
- Version: 1.2.0
3
+ Version: 2.0.0
4
4
  Summary: image2gcode: convert an image to gcode.
5
5
  Keywords: engraving,laser,image,laser engraving,PWM,gcode
6
6
  Author-email: Johannes Noordanus <mailjohannes.mailnoordanus@gmail.com>
@@ -20,21 +20,42 @@ Note that option```--validate```makes it possible to validate the gcode (result)
20
20
 
21
21
  It is important to use images that have a high contrast ratio, because burnlevels have less intensity range.
22
22
 
23
+ Version 2.0.0 has important new speed optimizations. Engravings run significantly faster and skip from one image zone to the other at maximum speed. See options ```--speedmoves``` and ```--noise``` for example.
24
+ To summarize:
25
+ Optimized gcode
26
+ - draw pixels in one go until change of power
27
+ - emit X/Y coordinates only when they change
28
+ - emit linear move 'G1/G0' code minimally
29
+ - does not emit zero power (or below cutoff) pixels
30
+ General optimizations
31
+ - laser head has defered and sparse moves.
32
+ (XY locations are virtual, head does not always follow)
33
+ - moves at high speed (G0) over 10mm (default) or more zero pixels
34
+ - low burn levels (stray pixels) can be suppressed (default off)
35
+
23
36
  ### Install
24
- Depends on python libraries *numpy*, *PIL* and (inverse function) *gcode2image* (https://github.com/johannesnoordanus/gcode2image/)
25
37
  ```
26
38
  > pip install gcode2image
27
39
  > pip install image2gcode
28
40
  >
41
+
42
+ Note: on Manjaro it is 'pipx' now!
29
43
  ```
30
44
  ### Example:
31
45
  ```
32
- > image2gcode.py logo.png logo.gc
46
+ [somedir]> image2gcode --maxpower 300 --showimage --speedmoves 5 --noise 5 --validate test.png test.gc
47
+
48
+ This command generates a gcode file 'test.gc' from an image 'test.png'. It burns pixels - .1mm^2 default - at a maximum of 300 (which level is laser machine dependend).
49
+ Option --showimages starts an image viewer containing the original image in B&W and added white background (when transparent) and option --validate shows the resulting image via an inverse function - gcode2image - to be able to verify the gcode file.
50
+ Option --speedmove 5 generates a maximum speed moves (G0) for non burn zones which (can) speed up engravings significantly. Option --noise 5 omits all pixels having burn values of 5 or less, this can remove noise (stray pixels) from some images.
51
+ The result file 'test.gc' contains highly optimized gcodes (the file is of minimal length) and gcodes run a minimal path.
33
52
  ```
34
53
  ### Usage:
35
54
  ```
36
- > image2gcode.py -h
37
- usage: image2gcode.py [-h] [--showimage] [--pixelsize <default:0.1>] [--speed <default:800>] [--maxpower <default:300>] [--offset X-off Y-off] [--validate] [-V] image [gcode]
55
+ [somedir]> image2gcode --help
56
+ usage: image2gcode [-h] [--showimage] [--pixelsize <default:0.1>] [--speed <default:800>] [--maxpower <default:300>] [--offset X-off Y-off] [--speedmoves <default:10>]
57
+ [--noise <default:0>] [--validate] [-V]
58
+ image [gcode]
38
59
 
39
60
  Convert an image to gcode for GRBL v1.1 compatible diode laser engravers.
40
61
 
@@ -50,11 +71,13 @@ options:
50
71
  --speed <default:800>
51
72
  draw speed in mm/min
52
73
  --maxpower <default:300>
53
- maximum laser power while drawing (as a rule of thumb set to 1/3 of the machine maximum)
74
+ maximum laser power while drawing (as a rule of thumb set to 1/3 of the maximum of a machine having a 5W laser)
54
75
  --offset X-off Y-off laser drawing starts at offset (default: X10.0 Y10.0)
76
+ --speedmoves <default:10>
77
+ length of zero burn zones in mm (0 sets no speedmoves): issue speed (G0) moves when skipping space of given length (or more)
78
+ --noise <default:0> noise power level, do not burn pixels below this power level
55
79
  --validate validate gcode file, do inverse and show image result
56
80
  -V, --version show version number and exit
57
81
 
58
82
  ```
59
-
60
83
 
@@ -0,0 +1,6 @@
1
+ image2gcode.py,sha256=nJWEhAOaIaCGYEIeW0VyUoL0Me-K_weuKFdDPgQAhAU,10893
2
+ image2gcode-2.0.0.dist-info/entry_points.txt,sha256=hQPqVKIhO8DUuxZtlnVCDygpjK9Ya_rv_L7O6Ks43H4,48
3
+ image2gcode-2.0.0.dist-info/LICENSE,sha256=ghSxQl_EUJUTiu712NkZkroJHvgOrR0j4CddAq8Y7Tc,1085
4
+ image2gcode-2.0.0.dist-info/WHEEL,sha256=EZbGkh7Ie4PoZfRQ8I0ZuP9VklN_TvcZ6DSE5Uar4z4,81
5
+ image2gcode-2.0.0.dist-info/METADATA,sha256=CT4rcqgNQm_d0fuhN8ndfCcZkgQ6gCyulGFif25LB5o,4771
6
+ image2gcode-2.0.0.dist-info/RECORD,,
image2gcode.py CHANGED
@@ -2,9 +2,10 @@
2
2
  """
3
3
  image2gcode: convert an image to gcode.
4
4
  """
5
- __version__ = "1.2.0"
5
+ __version__ = "2.0.0"
6
6
 
7
7
  import sys
8
+ import math
8
9
  import argparse
9
10
  from argparse import Namespace
10
11
  from datetime import datetime
@@ -40,6 +41,26 @@ def loadImage(imagefile: str = None, showimage: bool = True):
40
41
 
41
42
  return None
42
43
 
44
+ def distance(A: (float,float),B: (float,float)):
45
+ """
46
+ Does Pythagoras
47
+ """
48
+ # |Ax - Bx|^2 + |Ay - By|^2 = C^2
49
+ # distance = √C^2
50
+ return math.sqrt(abs(A[0] - B[0])**2 + abs(A[1] - B[1])**2)
51
+
52
+ def boundingbox(bbox:dict[str,float], XY: (float,float)) -> dict[str,float]:
53
+ """
54
+ boundingbox: update bounding box
55
+ """
56
+ if bbox is not None:
57
+ bbox["minX"] = XY[0] if XY[0] < bbox["minX"] else bbox["minX"]
58
+ bbox["minY"] = XY[1] if XY[1] < bbox["minY"] else bbox["minY"]
59
+ bbox["maxX"] = XY[0] if XY[0] > bbox["maxX"] else bbox["maxX"]
60
+ bbox["maxY"] = XY[1] if XY[1] > bbox["maxY"] else bbox["maxY"]
61
+
62
+ return bbox
63
+
43
64
  def image2gcode(img, args) -> str:
44
65
  """
45
66
  image2gcode: convert image to gcode
@@ -61,9 +82,10 @@ def image2gcode(img, args) -> str:
61
82
  gcode_footer = ["M5","M9","M2"]
62
83
 
63
84
  # header comment
64
- gcode = [';\n; ' + sys.argv[0] + " " + __version__ + " (" + str(datetime.now()).split('.')[0] + ")\n" +
65
- '; Area: ' + str(round(img.shape[1] * args.pixelsize,2)) + "mm x " + str(round(img.shape[0] * args.pixelsize,2)) + "mm (XY)" +
66
- '; > pixelsize ' + str(args.pixelsize) + ' mm^2, speed ' + str(args.speed) + ' mm/min, maxpower ' + str(args.maxpower) + ', offset ' + str(args.offset) + "\n;\n" ]
85
+ gcode = [f"; {sys.argv[0]} {__version__} ({str(datetime.now()).split('.')[0]})\n"
86
+ f'; Area: {str(round(img.shape[1] * args.pixelsize,2))}mm X {str(round(img.shape[0] * args.pixelsize,2))}mm (XY)\n'
87
+ f'; > pixelsize {str(args.pixelsize)}mm^2, speed {str(args.speed)}mm/min, maxpower {str(args.maxpower)},\n'
88
+ f'; speedmoves {args.speedmoves}, noise level {args.noise}, offset {args.offset})\n;\n']
67
89
 
68
90
  # init gcode
69
91
  gcode += ["G00 G17 G40 G21 G54","G90"]
@@ -77,20 +99,34 @@ def image2gcode(img, args) -> str:
77
99
  # go to start
78
100
  gcode += [f"G0X{X}Y{Y}"]
79
101
 
102
+ # initiate boundingbox
103
+ bbox = {'minX':X,'minY':Y,'maxX':X,'maxY':Y}
104
+
80
105
  # set write speed and G1 move mode
81
106
  # (note that this stays into effect until another G code is executed,
82
107
  # so we do not have to repeat this for all coordinates emitted below)
83
108
  gcode += [f"G1F{args.speed}"]
84
109
 
85
- # Print left to right, right to left (etc.)
110
+ # Print left to right, shift one scan line down, then right to left,
111
+ # one scanline down (repeat)
112
+ #
86
113
  # Optimized gcode:
87
- # - draw pixels until change of power
114
+ # - draw pixels in one go until change of power
88
115
  # - emit X/Y coordinates only when they change
89
- # - emit linear move 'G1' code only once
90
- # - does not emit in between spaces
116
+ # - emit linear move 'G1/G0' code minimally
117
+ # - does not emit zero power (or below cutoff) pixels
118
+ #
119
+ # General optimizations:
120
+ # - laser head has defered and sparse moves.
121
+ # (XY locations are virtual, head does not always follow)
122
+ # - moves at high speed (G0) over 10mm (default) or more zero pixels
123
+ # - low burn levels (noise pixels) can be suppressed (default off)
91
124
  #
92
125
  left2right = True
93
126
 
127
+ # current location of laser head
128
+ head = (X,Y)
129
+
94
130
  # start print
95
131
  for line in img:
96
132
 
@@ -112,15 +148,41 @@ def image2gcode(img, args) -> str:
112
148
  for count, pixel in enumerate(line):
113
149
  laserpow = round((1.0 - float(pixel/255)) * args.maxpower) if invert_intensity else round(float(pixel/255) * args.maxpower)
114
150
 
115
- # delay emit first pixel (so all same power pixels can be emitted in one sweep)
116
151
  if count == 0:
152
+ # delay emit first pixel (so all same power pixels can be emitted in one sweep)
117
153
  prev_pow = laserpow
154
+ # set last head loaction on start of the line
155
+ lastloc = (X,Y)
118
156
 
119
157
  # draw pixels until change of power
120
158
  if laserpow != prev_pow or count == line.size-1:
121
- code = f"X{X}"
122
- code += f"S{prev_pow}"
123
- gcode += [code]
159
+ #if prev_pow != 0:
160
+ if prev_pow > args.noise:
161
+ code = ""
162
+ if lastloc:
163
+ # head is not at correct location, go there
164
+ if args.speedmoves and (distance(head,(X,Y)) > args.speedmoves):
165
+ # fast
166
+ code = f"G0 X{lastloc[0]}Y{lastloc[1]}\n"
167
+ code += f"G1\n"
168
+ else:
169
+ # normal speed
170
+ code = f"X{lastloc[0]}Y{lastloc[1]} S0\n"
171
+
172
+ # emit point
173
+ code += f"X{X}S{prev_pow}"
174
+ gcode += [code]
175
+
176
+ # update boundingbox
177
+ bbox = boundingbox(bbox, (X,Y))
178
+
179
+ # head at this location
180
+ head = (X,Y)
181
+ lastloc = None
182
+ else:
183
+ # didn't move head to location, save it
184
+ lastloc = (X,Y)
185
+
124
186
  if count == line.size-1:
125
187
  continue
126
188
  prev_pow = laserpow # if laserpow != prev_pow
@@ -128,13 +190,15 @@ def image2gcode(img, args) -> str:
128
190
  # next point
129
191
  X = round(X + (args.pixelsize if left2right else -args.pixelsize), XY_prec)
130
192
 
131
- # go to next scan line
193
+ # next scan line (defer head movement)
132
194
  Y = round(Y + args.pixelsize, XY_prec)
133
- gcode += [f"Y{Y}S0"]
134
195
 
135
196
  # change print direction
136
197
  left2right = not left2right
137
198
 
199
+ # emit bounding box
200
+ gcode = [f';\n; Boundingbox: (X{bbox["minX"]},Y{bbox["minY"]}):(X{bbox["maxX"]},Y{bbox["maxY"]})\n;\n'] + gcode
201
+
138
202
  # laser off, fan off, program stop
139
203
  gcode += gcode_footer
140
204
 
@@ -148,6 +212,8 @@ def main() -> int:
148
212
  pixelsize_default = 0.1
149
213
  speed_default = 800
150
214
  power_default = 300
215
+ speedmoves_default = 10
216
+ noise_default = 0
151
217
 
152
218
  # Define command line argument interface
153
219
  parser = argparse.ArgumentParser(description='Convert an image to gcode for GRBL v1.1 compatible diode laser engravers.')
@@ -159,9 +225,13 @@ def main() -> int:
159
225
  parser.add_argument('--speed', default=speed_default, metavar="<default:" + str(speed_default)+">",
160
226
  type=int, help='draw speed in mm/min')
161
227
  parser.add_argument('--maxpower', default=power_default, metavar="<default:" +str(power_default)+ ">",
162
- type=int, help="maximum laser power while drawing (as a rule of thumb set to 1/3 of the machine maximum)")
228
+ type=int, help="maximum laser power while drawing (as a rule of thumb set to 1/3 of the maximum of a machine having a 5W laser)")
163
229
  parser.add_argument('--offset', default=[10.0, 10.0], nargs=2, metavar=('X-off', 'Y-off'),
164
230
  type=float, help="laser drawing starts at offset (default: X10.0 Y10.0)")
231
+ parser.add_argument('--speedmoves', default=speedmoves_default, metavar="<default:" + str(speedmoves_default)+">",
232
+ type=float, help="length of zero burn zones in mm (0 sets no speedmoves): issue speed (G0) moves when skipping space of given length (or more)")
233
+ parser.add_argument('--noise', default=noise_default, metavar="<default:" +str(noise_default)+ ">",
234
+ type=int, help="noise power level, do not burn pixels below this power level")
165
235
  parser.add_argument('--validate', action='store_true', default=False, help='validate gcode file, do inverse and show image result' )
166
236
  parser.add_argument('-V', '--version', action='version', version='%(prog)s ' + __version__, help="show version number and exit")
167
237
 
@@ -179,8 +249,9 @@ def main() -> int:
179
249
  # flip image updown because Gcode and raster image coordinate system differ
180
250
  narr = np.flipud(loadImage(args.image.name,args.showimage))
181
251
 
182
- print('Area: ' + str(round(narr.shape[1] * args.pixelsize,2)) + "mm x " + str(round(narr.shape[0] * args.pixelsize,2)) + "mm (XY)")
183
- print('> pixelsize', args.pixelsize, 'mm^2, speed', args.speed, 'mm/min, maxpower ' + str(args.maxpower) + ', offset', args.offset)
252
+ print(f'Area: {str(round(narr.shape[1] * args.pixelsize,2))}mm X {str(round(narr.shape[0] * args.pixelsize,2))}mm (XY)\n'
253
+ f' > pixelsize {args.pixelsize}mm^2, speed {args.speed}mm/min, maxpower {str(args.maxpower)},\n'
254
+ f' speedmoves {args.speedmoves}, noise level {args.noise}, offset {args.offset})')
184
255
 
185
256
  # emit gcode for image
186
257
  print(image2gcode(narr, args), file=args.gcode)
@@ -1,6 +0,0 @@
1
- image2gcode.py,sha256=sgXXCReZxBKTvigQB44Qal6Zq48epjZVRZaqjTX1DTs,7910
2
- image2gcode-1.2.0.dist-info/entry_points.txt,sha256=hQPqVKIhO8DUuxZtlnVCDygpjK9Ya_rv_L7O6Ks43H4,48
3
- image2gcode-1.2.0.dist-info/LICENSE,sha256=ghSxQl_EUJUTiu712NkZkroJHvgOrR0j4CddAq8Y7Tc,1085
4
- image2gcode-1.2.0.dist-info/WHEEL,sha256=EZbGkh7Ie4PoZfRQ8I0ZuP9VklN_TvcZ6DSE5Uar4z4,81
5
- image2gcode-1.2.0.dist-info/METADATA,sha256=3siHRwsJXXmlml9Of9qrMRwNna5jtwpSXeFhnIeN03M,2929
6
- image2gcode-1.2.0.dist-info/RECORD,,