image2gcode 2.9.8__tar.gz → 2.9.10__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,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: image2gcode
3
- Version: 2.9.8
3
+ Version: 2.9.10
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>
@@ -35,7 +35,7 @@ If this is too cumbersome, use option --size (release 2.5.0 or above), also for
35
35
 
36
36
  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.
37
37
 
38
- 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.
38
+ 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.
39
39
 
40
40
  Please consider supporting me, so I can make this application better and add new functionality to it: <http://paypal.me/johannesnoordanus/5,00>
41
41
 
@@ -20,7 +20,7 @@ If this is too cumbersome, use option --size (release 2.5.0 or above), also for
20
20
 
21
21
  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.
22
22
 
23
- 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.
23
+ 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.
24
24
 
25
25
  Please consider supporting me, so I can make this application better and add new functionality to it: <http://paypal.me/johannesnoordanus/5,00>
26
26
 
@@ -1,4 +1,4 @@
1
1
  """
2
2
  image2gcode: convert an image to gcode.
3
3
  """
4
- __version__ = "2.9.8"
4
+ __version__ = "2.9.10"
@@ -85,6 +85,8 @@ def main() -> int:
85
85
  "speedmoves_default" : 10,
86
86
  "noise_default" : 0,
87
87
  "overscan_default" : 0,
88
+ "invert_default" : True,
89
+ "constantburn_default" : True,
88
90
  }
89
91
 
90
92
  if os.path.exists(config_file):
@@ -107,7 +109,8 @@ def main() -> int:
107
109
  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)")
108
110
  parser.add_argument('--poweroffset', default=cfg["poweroffset_default"], metavar="<default:" +str(cfg["poweroffset_default"])+ ">",
109
111
  type=int, help="pixel intensity to laser power: shift power range [0-maxpower]")
110
- parser.add_argument('--noinvert', action='store_true', default=False, help='do not invert the image' )
112
+ # parser.add_argument('--invert', action='store_true', default=True, help='when true invert image pixels (default)' )
113
+ parser.add_argument('--invert', action=argparse.BooleanOptionalAction, default=cfg["invert_default"], help='default invert image pixels')
111
114
  parser.add_argument('--size', default=None, nargs=2, metavar=('gcode-width', 'gcode-height'),
112
115
  type=float, help="target gcode width and height in mm (default: not set and determined by pixelsize and image source resolution)")
113
116
  parser.add_argument('--offset', default=None, nargs=2, metavar=('X-off', 'Y-off'),
@@ -120,7 +123,7 @@ def main() -> int:
120
123
  parser.add_argument('--overscan', default=cfg["overscan_default"], metavar="<default:" +str(cfg["overscan_default"])+ ">",
121
124
  type=int, help="overscan image lines to avoid incorrect power levels for pixels at left and right borders, number in pixels, default off")
122
125
  parser.add_argument('--showoverscan', action='store_true', default=False, help='show overscan pixels (note that this is visible and part of the gcode emitted!)' )
123
- parser.add_argument('--constantburn', action='store_true', default=False, help='select constant burn mode M3 (a bit more dangerous!), instead of dynamic burn mode M4')
126
+ parser.add_argument('--constantburn', action=argparse.BooleanOptionalAction, default=cfg["constantburn_default"], help='default constant burn mode (M3)')
124
127
  parser.add_argument('--validate', action='store_true', default=False, help='validate gcode file, do inverse and show image result' )
125
128
  parser.add_argument('--genimages', default=None, nargs=3, metavar=('pixel-width', 'pixel-height', 'write'),
126
129
  type=int, help="write (when set non zero) a set of test (calibration) images to the file system")
@@ -136,6 +139,7 @@ def main() -> int:
136
139
  sys.exit(1)
137
140
  elif args.image is None:
138
141
  print(f"{os.path.basename(sys.argv[0])}, error: the following arguments are required: image")
142
+ parser.print_usage(sys.stderr)
139
143
  sys.exit(1)
140
144
 
141
145
  # check incompatible arguments
@@ -0,0 +1,296 @@
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)
@@ -51,7 +51,7 @@ class Image2gcode:
51
51
  :param pixel: int range [0-255]
52
52
  :param maxpower: machine maximum laser power (typically [0-1000])
53
53
  :param offset: int range [0-maxpower] (shift power range)
54
- :param invert: true/false (default true, when true 'black = white')
54
+ :param invert: true/false (default true, when true 'black == white')
55
55
  :return: laser intensity for this pixel
56
56
  """
57
57
  return offset + round((1.0 - float(pixel/255)) * (maxpower - offset)) if invert else round(float(pixel/255) * (maxpower - offset))
@@ -243,7 +243,7 @@ class Image2gcode:
243
243
 
244
244
  # draw this pixel line
245
245
  for count, pixel in enumerate(line):
246
- laserpow = self._power(pixel, args["maxpower"], args["poweroffset"], not args["noinvert"])
246
+ laserpow = self._power(pixel, args["maxpower"], args["poweroffset"], args["invert"])
247
247
 
248
248
  if count == 0:
249
249
  # delay emit first pixel (so all same power pixels can be emitted in one sweep)
File without changes
File without changes