1

I'm trying to generate a G-code using python. I write instructions according to the grey-scale image pixel values, but if I need to work with big images it takes forever to compile a code. Some G-code programs process these images in seconds. How can I make this program faster?

Thank you for your time.

gray_height = gray.shape[0]
gray_length = gray.shape[1]
print("length", gray_length)
print("height", gray_height)
for i in range(gray_length):
    j=0
    for j in range(gray_height):

        k = 'G01 X{}'.format(round(i*0.1,3)) + ' Y{}'.format(round(j*0.1,3)) + '\n' +'G01 Z -10' +'\n' +'G04 {}'.format(round(gray[i,j],2)) +'\n'  + 'G01 Z 10' +'\n'
        with open("file.txt", "a") as a_file:
            a_file.write(k)
    

1 Answers1

0

You can represent the total value of all ks in a generator:

k = (f'''G01 X{round(i*0.1,3)} Y{round(j*0.1,3)}
G01 Z -10
G04 {round(gray[i,j],2)
G01 Z 10
''' for i in range(gray_length) for j in range(gray_height))

and write it to the file all at once:

with open('file.txt', 'a') as a_file:
    a_file.writelines(k)

(I've used fstrings instead of str.format, as I think it greatly enhances the readability. It works with all recent versions of Python.)

The main gain here as many have mentioned in comments, is that you wouldn't be opening, closing, and reopening the file at each inner iteration.

kojiro
  • 74,557
  • 19
  • 143
  • 201