image2gcode 2.9.10__tar.gz → 2.9.12__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.10
3
+ Version: 2.9.12
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
@@ -29,12 +30,15 @@ It is possible to validate the gcode produced in one go: its size, placement and
29
30
 
30
31
  Note that to get great engravings it is important to use source images that have a high contrast ratio, because burnlevels have less intensity range. To get an engraving the right size, make sure images have enough pixels.
31
32
  For example if your machines laser width is 0.08mm I would recomment using a pixel size of 0.1mm; an engraving of 50x65 mm^2 (*width*x*height*) will need the source image resolution to be 500x650 pixels (*width*x*height*) in this case.
33
+
32
34
  It is also possible to set the DPI of an image to be exported from Inkscape (for example) and so get the right resolution for your laser machine. In this case the image to be exported should have a DPI setting of 254 (one inch is 25.4mm/0.1 = 254), note the image size when you do the export, because that will be exacly what you get on the laser machine!
33
35
 
34
36
  If this is too cumbersome, use option --size (release 2.5.0 or above), also for conveniance, to get the origin at the center, set --center. Note that --size will make a conversion of the source image.
35
37
 
36
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.
37
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
+
38
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.
39
43
 
40
44
  Please consider supporting me, so I can make this application better and add new functionality to it: <http://paypal.me/johannesnoordanus/5,00>
@@ -83,11 +87,12 @@ The result file 'test.gc' contains highly optimized gcodes (the file is of minim
83
87
  ### Usage:
84
88
  See notes below.
85
89
  ```
86
- > image2gcode --help
87
- usage: image2gcode [-h] [--showimage] [--pixelsize <default:0.1>] [--speed <default:800>] [--maxpower <default:300>] [--poweroffset <default:0>]
88
- [--size gcode-width gcode-height] [--offset X-off Y-off] [--center] [--speedmoves <default:10>] [--noise <default:0>] [--overscan <default:0>]
89
- [--showoverscan] [--constantburn] [--validate] [--genimages pixel-width pixel-height write] [-V]
90
- [image] [gcode]
90
+ image2gcode --help
91
+ usage: image2gcode [-h] [--showimage] [--pixelsize <default:0.1>] [--speed <default:1200>] [--maxpower <default:300>] [--poweroffset <default:0>] [--invert | --no-invert]
92
+ [--onedirectionscan | --no-onedirectionscan]
93
+ [--size gcode-width gcode-height] [--offset X-off Y-off] [--center] [--speedmoves <default:10>] [--noise <default:0>] [--overscan <default:0>]
94
+ [--showoverscan] [--constantburn | --no-constantburn] [--validate] [--genimages pixel-width pixel-height write] [-V]
95
+ [image] [gcode]
91
96
 
92
97
  Convert an image to gcode for GRBL v1.1 compatible diode laser engravers,
93
98
  each image pixel is converted to a gcode move of pixelsize length.
@@ -101,13 +106,16 @@ options:
101
106
  --showimage show b&w converted image
102
107
  --pixelsize <default:0.1>
103
108
  pixel size in mm (XY-axis): each image pixel is drawn this size
104
- --speed <default:800>
109
+ --speed <default:1200>
105
110
  draw speed in mm/min
106
111
  --maxpower <default:300>
107
112
  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
113
  --poweroffset <default:0>
109
114
  pixel intensity to laser power: shift power range [0-maxpower]
110
- --noinvert do not invert the image
115
+ --invert, --no-invert
116
+ default invert image pixels
117
+ --onedirectionscan, --no-onedirectionscan
118
+ scan in one direction only. Laser is turned on only when moving left to right. (default: off, scan in both directions)
111
119
  --size gcode-width gcode-height
112
120
  target gcode width and height in mm (default: not set and determined by pixelsize and image source resolution)
113
121
  --offset X-off Y-off laser drawing starts at offset in mm (default not set, --center cannot be set at the same time)
@@ -118,10 +126,11 @@ options:
118
126
  --overscan <default:0>
119
127
  overscan image lines to avoid incorrect power levels for pixels at left and right borders, number in pixels, default off
120
128
  --showoverscan show overscan pixels (note that this is visible and part of the gcode emitted!)
121
- --constantburn select constant burn mode M3 (a bit more dangerous!), instead of dynamic burn mode M4
129
+ --constantburn, --no-constantburn
130
+ default constant burn mode (M3)
122
131
  --validate validate gcode file, do inverse and show image result
123
132
  --genimages pixel-width pixel-height write
124
- write (when set non zero) 11 calibration images of given pixel size to as much files
133
+ write (when set non zero) a set of test (calibration) images to the file system
125
134
  -V, --version show version number and exit
126
135
  ```
127
136
  You can also store those settings in ~/.config/image2gcode.toml, eg:
@@ -180,9 +189,12 @@ The ideal white balance for my 5W laser is at *speed* 1200 and *maxpower* 300, w
180
189
  Cutting depth of the 10W laser seems to be a factor 2 though.
181
190
  Also, contrast of the 5W laser is a lot better than that of the 10W laser. Images engraved by the 5W laser are laser sharp and smooth, while the 10W laser images are sharp, have reasonable smoothness and twice the cutting depth.
182
191
 
192
+ **Burn mode M3/M4**
193
+
194
+ Default *image2gcode* uses constant burn mode *M3* (version 2.9.10 and later). This can be overruled by setting option *--no-constantburn* which selects burn mode *M4*. Mode *M4* is not suitable for engravings because it automatically compensates (laser)power for speed. This conflicts with the specific gcode settings given by *image2gcode* for each pixel. In fact some experiments show that *M4* causes loss of quality and image deterioration when speed is increased. On white oak images had too much black and grey which did not go away for substantially higher speed. When switched back to constant burn (*M3*) mode, the same high speed gave excellent images having a sepia (licht yellow brown) color tone.
195
+
183
196
  **Wood**
184
197
 
185
198
  Obviously wood hardness determines the cutting depth (relief) of the engraving and a dark color reduces the contrast of the image.
186
199
  Note also that the white balance of an engraving is possibly shifted for different types of wood.
187
200
 
188
-
@@ -14,12 +14,15 @@ It is possible to validate the gcode produced in one go: its size, placement and
14
14
 
15
15
  Note that to get great engravings it is important to use source images that have a high contrast ratio, because burnlevels have less intensity range. To get an engraving the right size, make sure images have enough pixels.
16
16
  For example if your machines laser width is 0.08mm I would recomment using a pixel size of 0.1mm; an engraving of 50x65 mm^2 (*width*x*height*) will need the source image resolution to be 500x650 pixels (*width*x*height*) in this case.
17
+
17
18
  It is also possible to set the DPI of an image to be exported from Inkscape (for example) and so get the right resolution for your laser machine. In this case the image to be exported should have a DPI setting of 254 (one inch is 25.4mm/0.1 = 254), note the image size when you do the export, because that will be exacly what you get on the laser machine!
18
19
 
19
20
  If this is too cumbersome, use option --size (release 2.5.0 or above), also for conveniance, to get the origin at the center, set --center. Note that --size will make a conversion of the source image.
20
21
 
21
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.
22
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
+
23
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.
24
27
 
25
28
  Please consider supporting me, so I can make this application better and add new functionality to it: <http://paypal.me/johannesnoordanus/5,00>
@@ -68,11 +71,12 @@ The result file 'test.gc' contains highly optimized gcodes (the file is of minim
68
71
  ### Usage:
69
72
  See notes below.
70
73
  ```
71
- > image2gcode --help
72
- usage: image2gcode [-h] [--showimage] [--pixelsize <default:0.1>] [--speed <default:800>] [--maxpower <default:300>] [--poweroffset <default:0>]
73
- [--size gcode-width gcode-height] [--offset X-off Y-off] [--center] [--speedmoves <default:10>] [--noise <default:0>] [--overscan <default:0>]
74
- [--showoverscan] [--constantburn] [--validate] [--genimages pixel-width pixel-height write] [-V]
75
- [image] [gcode]
74
+ image2gcode --help
75
+ usage: image2gcode [-h] [--showimage] [--pixelsize <default:0.1>] [--speed <default:1200>] [--maxpower <default:300>] [--poweroffset <default:0>] [--invert | --no-invert]
76
+ [--onedirectionscan | --no-onedirectionscan]
77
+ [--size gcode-width gcode-height] [--offset X-off Y-off] [--center] [--speedmoves <default:10>] [--noise <default:0>] [--overscan <default:0>]
78
+ [--showoverscan] [--constantburn | --no-constantburn] [--validate] [--genimages pixel-width pixel-height write] [-V]
79
+ [image] [gcode]
76
80
 
77
81
  Convert an image to gcode for GRBL v1.1 compatible diode laser engravers,
78
82
  each image pixel is converted to a gcode move of pixelsize length.
@@ -86,13 +90,16 @@ options:
86
90
  --showimage show b&w converted image
87
91
  --pixelsize <default:0.1>
88
92
  pixel size in mm (XY-axis): each image pixel is drawn this size
89
- --speed <default:800>
93
+ --speed <default:1200>
90
94
  draw speed in mm/min
91
95
  --maxpower <default:300>
92
96
  maximum laser power while drawing (as a rule of thumb set to 1/3 of the maximum of a machine having a 5W laser)
93
97
  --poweroffset <default:0>
94
98
  pixel intensity to laser power: shift power range [0-maxpower]
95
- --noinvert do not invert the image
99
+ --invert, --no-invert
100
+ default invert image pixels
101
+ --onedirectionscan, --no-onedirectionscan
102
+ scan in one direction only. Laser is turned on only when moving left to right. (default: off, scan in both directions)
96
103
  --size gcode-width gcode-height
97
104
  target gcode width and height in mm (default: not set and determined by pixelsize and image source resolution)
98
105
  --offset X-off Y-off laser drawing starts at offset in mm (default not set, --center cannot be set at the same time)
@@ -103,10 +110,11 @@ options:
103
110
  --overscan <default:0>
104
111
  overscan image lines to avoid incorrect power levels for pixels at left and right borders, number in pixels, default off
105
112
  --showoverscan show overscan pixels (note that this is visible and part of the gcode emitted!)
106
- --constantburn select constant burn mode M3 (a bit more dangerous!), instead of dynamic burn mode M4
113
+ --constantburn, --no-constantburn
114
+ default constant burn mode (M3)
107
115
  --validate validate gcode file, do inverse and show image result
108
116
  --genimages pixel-width pixel-height write
109
- write (when set non zero) 11 calibration images of given pixel size to as much files
117
+ write (when set non zero) a set of test (calibration) images to the file system
110
118
  -V, --version show version number and exit
111
119
  ```
112
120
  You can also store those settings in ~/.config/image2gcode.toml, eg:
@@ -165,8 +173,11 @@ The ideal white balance for my 5W laser is at *speed* 1200 and *maxpower* 300, w
165
173
  Cutting depth of the 10W laser seems to be a factor 2 though.
166
174
  Also, contrast of the 5W laser is a lot better than that of the 10W laser. Images engraved by the 5W laser are laser sharp and smooth, while the 10W laser images are sharp, have reasonable smoothness and twice the cutting depth.
167
175
 
176
+ **Burn mode M3/M4**
177
+
178
+ Default *image2gcode* uses constant burn mode *M3* (version 2.9.10 and later). This can be overruled by setting option *--no-constantburn* which selects burn mode *M4*. Mode *M4* is not suitable for engravings because it automatically compensates (laser)power for speed. This conflicts with the specific gcode settings given by *image2gcode* for each pixel. In fact some experiments show that *M4* causes loss of quality and image deterioration when speed is increased. On white oak images had too much black and grey which did not go away for substantially higher speed. When switched back to constant burn (*M3*) mode, the same high speed gave excellent images having a sepia (licht yellow brown) color tone.
179
+
168
180
  **Wood**
169
181
 
170
182
  Obviously wood hardness determines the cutting depth (relief) of the engraving and a dark color reduces the contrast of the image.
171
183
  Note also that the white balance of an engraving is possibly shifted for different types of wood.
172
-
@@ -1,4 +1,4 @@
1
1
  """
2
2
  image2gcode: convert an image to gcode.
3
3
  """
4
- __version__ = "2.9.10"
4
+ __version__ = "2.9.12"
@@ -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