image2gcode 2.9.11__tar.gz → 2.9.14__tar.gz

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,12 +1,13 @@
1
- Metadata-Version: 2.1
1
+ Metadata-Version: 2.4
2
2
  Name: image2gcode
3
- Version: 2.9.11
3
+ Version: 2.9.14
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>
7
7
  Requires-Python: >=3.7
8
8
  Description-Content-Type: text/markdown
9
9
  Classifier: License :: OSI Approved :: MIT License
10
+ License-File: LICENSE
10
11
  Requires-Dist: gcode2image >= 2.3.1
11
12
  Requires-Dist: numpy >= 1.24.3
12
13
  Requires-Dist: Pillow >= 9.5.0
@@ -36,9 +37,12 @@ If this is too cumbersome, use option --size (release 2.5.0 or above), also for
36
37
 
37
38
  Some people noticed incorrect low burn levels at the edges of objects within an image, this can be remedied by using option '--overscan <nbr of pixels>'. This makes sure the laser head will continue for a few pixels on a line after the last non empty pixel, or start the head a few pixels before the first non empty pixel is written on a line.
38
39
 
40
+ Some machines will have better engraving results if laser is enabled when moving in one direction. Use '--onedirectionscan' for that. This option will produce gcode where laser is enabled only when moving left to right. Somewhat slower, but may have better engraving result.
41
+
39
42
  It is possible to calibrate your laser machine now: option ```--genimages pixel-width pixel-height write``` generates a set calibration files that can be used as input for ```image2gcode``` to experiment with settings like ```--pixelsize```, ```--speed``` and ```--maxpower``` to get the right setup! For example use ```image2gcode --showimage --genimages 200 200 0``` to generate test images of 200 by 200 pixels that show up in the viewer (but are not written to the file system). See chapter *calibrate* below.
40
43
 
41
- Please consider supporting me, so I can make this application better and add new functionality to it: <http://paypal.me/johannesnoordanus/5,00>
44
+ If you find this application useful, please consider donating, so I can continue maintaining and enhancing it.<br>
45
+ <http://paypal.me/johannesnoordanus/5,00>
42
46
 
43
47
  To summarize:
44
48
 
@@ -86,6 +90,7 @@ See notes below.
86
90
  ```
87
91
  image2gcode --help
88
92
  usage: image2gcode [-h] [--showimage] [--pixelsize <default:0.1>] [--speed <default:1200>] [--maxpower <default:300>] [--poweroffset <default:0>] [--invert | --no-invert]
93
+ [--onedirectionscan | --no-onedirectionscan]
89
94
  [--size gcode-width gcode-height] [--offset X-off Y-off] [--center] [--speedmoves <default:10>] [--noise <default:0>] [--overscan <default:0>]
90
95
  [--showoverscan] [--constantburn | --no-constantburn] [--validate] [--genimages pixel-width pixel-height write] [-V]
91
96
  [image] [gcode]
@@ -110,6 +115,8 @@ options:
110
115
  pixel intensity to laser power: shift power range [0-maxpower]
111
116
  --invert, --no-invert
112
117
  default invert image pixels
118
+ --onedirectionscan, --no-onedirectionscan
119
+ scan in one direction only. Laser is turned on only when moving left to right. (default: off, scan in both directions)
113
120
  --size gcode-width gcode-height
114
121
  target gcode width and height in mm (default: not set and determined by pixelsize and image source resolution)
115
122
  --offset X-off Y-off laser drawing starts at offset in mm (default not set, --center cannot be set at the same time)
@@ -21,9 +21,12 @@ If this is too cumbersome, use option --size (release 2.5.0 or above), also for
21
21
 
22
22
  Some people noticed incorrect low burn levels at the edges of objects within an image, this can be remedied by using option '--overscan <nbr of pixels>'. This makes sure the laser head will continue for a few pixels on a line after the last non empty pixel, or start the head a few pixels before the first non empty pixel is written on a line.
23
23
 
24
+ Some machines will have better engraving results if laser is enabled when moving in one direction. Use '--onedirectionscan' for that. This option will produce gcode where laser is enabled only when moving left to right. Somewhat slower, but may have better engraving result.
25
+
24
26
  It is possible to calibrate your laser machine now: option ```--genimages pixel-width pixel-height write``` generates a set calibration files that can be used as input for ```image2gcode``` to experiment with settings like ```--pixelsize```, ```--speed``` and ```--maxpower``` to get the right setup! For example use ```image2gcode --showimage --genimages 200 200 0``` to generate test images of 200 by 200 pixels that show up in the viewer (but are not written to the file system). See chapter *calibrate* below.
25
27
 
26
- Please consider supporting me, so I can make this application better and add new functionality to it: <http://paypal.me/johannesnoordanus/5,00>
28
+ If you find this application useful, please consider donating, so I can continue maintaining and enhancing it.<br>
29
+ <http://paypal.me/johannesnoordanus/5,00>
27
30
 
28
31
  To summarize:
29
32
 
@@ -71,6 +74,7 @@ See notes below.
71
74
  ```
72
75
  image2gcode --help
73
76
  usage: image2gcode [-h] [--showimage] [--pixelsize <default:0.1>] [--speed <default:1200>] [--maxpower <default:300>] [--poweroffset <default:0>] [--invert | --no-invert]
77
+ [--onedirectionscan | --no-onedirectionscan]
74
78
  [--size gcode-width gcode-height] [--offset X-off Y-off] [--center] [--speedmoves <default:10>] [--noise <default:0>] [--overscan <default:0>]
75
79
  [--showoverscan] [--constantburn | --no-constantburn] [--validate] [--genimages pixel-width pixel-height write] [-V]
76
80
  [image] [gcode]
@@ -95,6 +99,8 @@ options:
95
99
  pixel intensity to laser power: shift power range [0-maxpower]
96
100
  --invert, --no-invert
97
101
  default invert image pixels
102
+ --onedirectionscan, --no-onedirectionscan
103
+ scan in one direction only. Laser is turned on only when moving left to right. (default: off, scan in both directions)
98
104
  --size gcode-width gcode-height
99
105
  target gcode width and height in mm (default: not set and determined by pixelsize and image source resolution)
100
106
  --offset X-off Y-off laser drawing starts at offset in mm (default not set, --center cannot be set at the same time)
@@ -1,4 +1,4 @@
1
1
  """
2
2
  image2gcode: convert an image to gcode.
3
3
  """
4
- __version__ = "2.9.11"
4
+ __version__ = "2.9.14"
@@ -87,6 +87,7 @@ def main() -> int:
87
87
  "overscan_default" : 0,
88
88
  "invert_default" : True,
89
89
  "constantburn_default" : True,
90
+ "onedirectionscan_default" : False,
90
91
  }
91
92
 
92
93
  if os.path.exists(config_file):
@@ -111,6 +112,7 @@ def main() -> int:
111
112
  type=int, help="pixel intensity to laser power: shift power range [0-maxpower]")
112
113
  # parser.add_argument('--invert', action='store_true', default=True, help='when true invert image pixels (default)' )
113
114
  parser.add_argument('--invert', action=argparse.BooleanOptionalAction, default=cfg["invert_default"], help='default invert image pixels')
115
+ parser.add_argument('--onedirectionscan', action=argparse.BooleanOptionalAction, default=cfg["onedirectionscan_default"], help='scan in one direction only. Laser is turned on only when moving left to right. (default: off, scan in both directions)')
114
116
  parser.add_argument('--size', default=None, nargs=2, metavar=('gcode-width', 'gcode-height'),
115
117
  type=float, help="target gcode width and height in mm (default: not set and determined by pixelsize and image source resolution)")
116
118
  parser.add_argument('--offset', default=None, nargs=2, metavar=('X-off', 'Y-off'),
@@ -222,6 +222,8 @@ class Image2gcode:
222
222
  # so we do not have to repeat this for all coordinates emitted below)
223
223
  gcode += [f"G1F{args['speed']}"]
224
224
 
225
+ # Determine scan direction
226
+ onedirectionscan = args.get("onedirectionscan", False)
225
227
  left2right = True
226
228
 
227
229
  # start image conversion
@@ -290,7 +292,13 @@ class Image2gcode:
290
292
  # next scan line (defer head movement)
291
293
  Y = round(Y + args["pixelsize"], XY_prec)
292
294
 
293
- # change print direction
294
- left2right = not left2right
295
+
296
+ # If onedirectionscan is True, always scan left to right
297
+ # Otherwise, alternate direction
298
+ if onedirectionscan:
299
+ # Go to line start & do not switch scan direction
300
+ X = round(args["offset"][0], XY_prec)
301
+ else:
302
+ left2right = not left2right
295
303
 
296
304
  return '\n'.join(gcode)
@@ -1,296 +0,0 @@
1
- """
2
- image2gcode: convert an image to gcode.
3
- """
4
-
5
- import os
6
- import sys
7
- import math
8
- import argparse
9
- from argparse import Namespace
10
- from datetime import datetime
11
- from collections import namedtuple
12
- from collections.abc import Callable
13
- from typing import Any
14
- from typing import Tuple
15
-
16
- from PIL import Image
17
- import numpy as np
18
-
19
- from image2gcode.boundingbox import Boundingbox
20
-
21
- # pip install nptyping[complete]
22
- # https://github.com/ramonhagenaars/nptyping/blob/master/USERDOCS.md#Quickstart
23
- from nptyping import NDArray, UInt8, Shape
24
-
25
- class Image2gcode:
26
- """
27
- Class Image2gcode handles the conversion of an image to gcode.
28
- """
29
-
30
- def __init__(self, power: Callable[[UInt8,int,int,bool],int] = None,
31
- transformation: Callable[[Tuple[float,float]],Tuple[float,float]] = None):
32
-
33
- # init
34
- self.bbox = Boundingbox()
35
- self._power = power if power is not None else self.linear_power
36
- self._transformation = transformation
37
-
38
- def distance(self, A: Tuple[float,float], B: Tuple[float,float]) -> float:
39
- """
40
- Pythagoras
41
- """
42
- # |Ax - Bx|^2 + |Ay - By|^2 = C^2
43
- # distance = √C^2
44
- return math.sqrt(abs(A[0] - B[0])**2 + abs(A[1] - B[1])**2)
45
-
46
- @staticmethod
47
- def linear_power(pixel: UInt8, maxpower: int, offset: int = 0, invert: bool = True) -> int:
48
- """
49
- Linear conversion of pixel value to laser intensity
50
-
51
- :param pixel: int range [0-255]
52
- :param maxpower: machine maximum laser power (typically [0-1000])
53
- :param offset: int range [0-maxpower] (shift power range)
54
- :param invert: true/false (default true, when true 'black == white')
55
- :return: laser intensity for this pixel
56
- """
57
- return offset + round((1.0 - float(pixel/255)) * (maxpower - offset)) if invert else round(float(pixel/255) * (maxpower - offset))
58
-
59
-
60
- def image2gcode(self, img: NDArray[Shape["*,*"], UInt8], args: dict[str, Any]) -> str:
61
- """
62
- :param img: image array (widthx,height), intensity values [0-255]
63
- :param args: conversion settings (like pixelsize, speed, maxpower, ..)
64
- :return: gcode for this img(age)
65
-
66
- algorithm outline:
67
- scan image left to right, shift one scan line down, then right to left
68
- for each scan line,
69
- for each pixel on the scan line,
70
- convert pixel intensity to laser power,
71
- generate gcode for the current coordinates (X,Y) at this intensity
72
- repeat
73
-
74
- Note that the algorithm outline does not cover the subtleties.
75
- In general, the laser machine head moves only when needed and does not always
76
- follow the image scan order, empty (0 burn or noise pixels) are skipped which
77
- alltogether generates the effect that only image objects within their contour
78
- are 'printed'
79
-
80
- detail:
81
- emit condensed gcode:
82
- - emit XY coordinates only when they change
83
- - emit modal gcode (linear move G1/G0) minimally
84
- - does not emit zero power (or below cutoff/noise) pixels
85
-
86
- optimizations:
87
- - draw pixels only when change of power
88
- - minimal laser head moves: laser head has defered and sparse moves.
89
- (XY locations are virtual, head does not always follow)
90
- - moves at high speed (G0) over 10mm (default) or more zero pixels
91
- - low burn levels (noise pixels) can be suppressed (default off)
92
- - overscan image: set laserhead a few pixels before the first pixels of a scan line,
93
- and move head a few pixels after the last pixels of a scan line (both directions)
94
- default off
95
- (this might reduce low burnrate pixels at the edges for some laser machines,
96
- note that speed adaptive burn mode M4 should automatically take care of this.)
97
- """
98
-
99
- def XYdelta(XY: Tuple[float,float]) -> Tuple[float,float]:
100
- """
101
- This function does a transformation.
102
- :param XY: point to transform
103
- :return: transformation of XY
104
- """
105
- XYd = XY if self._transformation is None else self._transformation(XY)
106
- return (round(XYd[0],XY_prec),round(XYd[1],XY_prec))
107
-
108
- def handle_overscan_at_eol(lastnoise):
109
- """
110
- This functions is called at the end of a scan line.
111
- It moves the laser head just after the last contour (point) of this line.
112
- :param lastnoise: location of the last 'noise' point
113
- :return: gcode to move the head to this location
114
- """
115
- nonlocal gcode
116
- nonlocal head
117
-
118
- # we are at the end of a scan line
119
- if args["overscan"] and head[1] == Y and lastnoise is not None:
120
- # we are past the (outer) contour of this image (that is: one or more points are drawn on
121
- # this line and one or more zero power pixels are not drawn)
122
- # we now add a few pixels to be drawn past this edge (nomally zero/noise pixels are skipped),
123
- # to make the laser head moves a few pixels further in the same scan direction
124
- if left2right:
125
- overscanpixels = min(round(head[0] + (args["overscan"] * args["pixelsize"]), XY_prec),
126
- round(args["offset"][0] + (line.size * args["pixelsize"]), XY_prec))
127
- else:
128
- overscanpixels = max(round(head[0] - (args["overscan"] * args["pixelsize"]), XY_prec),
129
- round(args["offset"][0], XY_prec))
130
-
131
- # get points after transformation (if any)
132
- overscandelta, Yd = XYdelta((overscanpixels,Y))
133
- # emit overscan pixels
134
- overscan = "180" if (args["overscan"] and args["showoverscan"]) else "0"
135
- gcode += [f"X{overscandelta}Y{Yd}S{overscan}"]
136
-
137
- # head at this location
138
- head = (overscanpixels,Y)
139
-
140
- def handle_overscan_at_begin_of_line(lastnoise) -> str:
141
- """
142
- This functions is called at the beginning of a scan line.
143
- It moves the laser head just before the first contour (point) of this line.
144
- :param lastnoise: location of the last 'noise' point
145
- :return: gcode to move the head to this location
146
- """
147
- code = ''
148
- # we are at the beginning of a scan line
149
- if args["overscan"] and head[1] != Y:
150
- # the laser head is still at aprevious line and is moved to this line, just a few
151
- # pixels before the start of a contour of this image
152
- if left2right:
153
- # go to next line and start overscan pixels earlier
154
- min_X = round(args["offset"][0], XY_prec)
155
- overscanpixels = round(lastnoise[0] - (args["overscan"] * args["pixelsize"]), XY_prec)
156
- overscanpixels = overscanpixels if overscanpixels > min_X else min_X
157
- else:
158
- max_X = round(args["offset"][0] + (line.size * args["pixelsize"]), XY_prec)
159
- overscanpixels = round(lastnoise[0] + (args["overscan"] * args["pixelsize"]), XY_prec)
160
- overscanpixels = overscanpixels if overscanpixels < max_X else max_X
161
-
162
- # get points after transformation (if any)
163
- overscandelta, lastnoisedelta = XYdelta((overscanpixels,lastnoise[1]))
164
-
165
- # go to overscan position
166
- code = f"X{overscandelta}Y{lastnoisedelta}S0\n"
167
- return code
168
-
169
- def handle_lastnoise(lastnoise) -> str:
170
- """
171
- This functions is called to move the laser head to the correct location
172
- before a point is emmitted.
173
- :param lastnoise: location of the last 'noise' point
174
- :return: gcode to move the head to this location
175
- """
176
- code = ""
177
- if lastnoise:
178
- # head is not at correct location, go there
179
-
180
- # Apply affine transformation (if needed)
181
- # (Note that an affine transformation does not necessarily preserve angles between
182
- # lines or distances between points!)
183
- XYlastnoise = XYdelta(lastnoise)
184
- XYhead = XYdelta(head)
185
-
186
- # move head to location just before a new point is emitted
187
- # (note that 'noise' points are not emitted and the laser head has to
188
- # catch up with the last noise point location, to be able to write a new pixel)
189
- if args["speedmoves"] and (self.distance(XYhead,XYlastnoise) > args["speedmoves"]):
190
- # fast
191
- code = f"G0 X{XYlastnoise[0]}Y{XYlastnoise[1]}\nG1\n"
192
- else:
193
- # normal speed
194
- code = handle_overscan_at_begin_of_line(lastnoise)
195
- overscan = "180" if (args["overscan"] and args["showoverscan"]) else "0"
196
- code += f"X{XYlastnoise[0]}Y{XYlastnoise[1]}S{overscan}\n"
197
-
198
- # update bounding box
199
- self.bbox.update(XYlastnoise)
200
- return code
201
-
202
- # set X/Y-axis precision to number of digits after
203
- XY_prec = len(str(args["pixelsize"]).split('.')[1])
204
-
205
- # set printer start coordinates
206
- X = round(args["offset"][0], XY_prec)
207
- Y = round(args["offset"][1], XY_prec)
208
-
209
- # get coordinates after transformation (if any)
210
- Xd, Yd = XYdelta((X,Y))
211
-
212
- # go to start
213
- gcode = [f"G0X{Xd}Y{Yd}"]
214
- # current location of laser head
215
- head = (X,Y)
216
-
217
- # initiate bbox
218
- self.bbox.update((Xd,Yd))
219
-
220
- # set write speed and G1 move mode
221
- # (note that this stays into effect until another G code is executed,
222
- # so we do not have to repeat this for all coordinates emitted below)
223
- gcode += [f"G1F{args['speed']}"]
224
-
225
- left2right = True
226
-
227
- # start image conversion
228
- for line in img:
229
-
230
- if not left2right:
231
- # reverse line when printing right to left
232
- line = np.flip(line)
233
-
234
- # add line terminator (makes this algorithm regular)
235
- line = np.append(line,0)
236
-
237
- # Note that (laser) drawing from a point to a point differs from setting a point (within an image):
238
- # 0 1 2 3 4 5 6 <-- gcode drawing points
239
- # one line: |[0]|[1]|[2]|[3]|[4]|[5]| <-- image pixels
240
- #
241
- # For example: drawing from X0 to X2 with value S10 corresponds to setting [0] = S10 and [1] = S10
242
- # Note also that drawing form left to right differs subtly from the reverse
243
-
244
- # draw this pixel line
245
- for count, pixel in enumerate(line):
246
- laserpow = self._power(pixel, args["maxpower"], args["poweroffset"], args["invert"])
247
-
248
- if count == 0:
249
- # delay emit first pixel (so all same power pixels can be emitted in one sweep)
250
- prev_pow = laserpow
251
- # set last noise location on start of the line
252
- lastnoise = (X,Y)
253
-
254
- # draw pixels when change of power
255
- if laserpow != prev_pow or count == line.size-1:
256
- # skip all zero power points
257
- if prev_pow > args["noise"]:
258
-
259
- # check if head is at the right location, if not go there
260
- code = handle_lastnoise(lastnoise)
261
-
262
- # emit point
263
- if self._transformation is not None:
264
- Xd, Yd = XYdelta((X,Y))
265
- code += f"X{Xd}Y{Yd}S{prev_pow}"
266
- # update bbox
267
- self.bbox.update((Xd,Yd))
268
- else:
269
- code += f"X{X}S{prev_pow}"
270
- # update bbox
271
- self.bbox.update((X,Y))
272
- gcode += [code]
273
-
274
- # head at this location
275
- head = (X,Y)
276
- lastnoise = None
277
- else:
278
- # didn't move head to location, save it
279
- lastnoise = (X,Y)
280
-
281
- if count == line.size-1:
282
- # overscan this line (if we can)
283
- handle_overscan_at_eol(lastnoise)
284
- continue
285
- prev_pow = laserpow # if laserpow != prev_pow
286
-
287
- # next point
288
- X = round(X + (args["pixelsize"] if left2right else -args["pixelsize"]), XY_prec)
289
-
290
- # next scan line (defer head movement)
291
- Y = round(Y + args["pixelsize"], XY_prec)
292
-
293
- # change print direction
294
- left2right = not left2right
295
-
296
- return '\n'.join(gcode)
File without changes