image2gcode 2.9.14__tar.gz → 2.9.15__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.4
2
2
  Name: image2gcode
3
- Version: 2.9.14
3
+ Version: 2.9.15
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>
@@ -9,9 +9,9 @@ Description-Content-Type: text/markdown
9
9
  Classifier: License :: OSI Approved :: MIT License
10
10
  License-File: LICENSE
11
11
  Requires-Dist: gcode2image >= 2.3.1
12
- Requires-Dist: numpy >= 1.24.3
12
+ Requires-Dist: numpy >= 1.24.3,<= 2.4.6
13
13
  Requires-Dist: Pillow >= 9.5.0
14
- Requires-Dist: nptyping >= 2.0.0
14
+ Requires-Dist: np2typing >= 2.6.3
15
15
  Project-URL: Home, https://github.com/johannesnoordanus/image2gcode
16
16
 
17
17
  # image2gcode
@@ -1,4 +1,4 @@
1
1
  """
2
2
  image2gcode: convert an image to gcode.
3
3
  """
4
- __version__ = "2.9.14"
4
+ __version__ = "2.9.15"
@@ -13,9 +13,9 @@ dynamic = ["version", "description"]
13
13
  keywords = ["engraving", "laser", "image", "laser engraving", "PWM", "gcode"]
14
14
  dependencies = [
15
15
  "gcode2image >= 2.3.1",
16
- "numpy >= 1.24.3",
16
+ "numpy >= 1.24.3,<= 2.4.6",
17
17
  "Pillow >= 9.5.0",
18
- "nptyping >= 2.0.0",
18
+ "np2typing >= 2.6.3",
19
19
  ]
20
20
 
21
21
  requires-python = ">=3.7"
@@ -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,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"])
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
File without changes