Skip to content Skip to sidebar Skip to footer

How To Get Numpy Array Of Canvas Data?

I am building an application with Tkinter, where one is able to draw e.g. lines in a Canvas. This works well. However, I'm unable to find a method for getting the current Canvas da

Solution 1:

Like @Bryan Oakley said: there is no way to get a rasterized version of a Tkinter Canvas drawing.

However, I figured out this workaround:

import skimage.io as ski_io

(...)
# draw your canvas
(...)

# save canvas to .eps (postscript) file
canvas.postscript(file="tmp_canvas.eps",
                  colormode="color",
                  width=CANVAS_WIDTH,
                  height=CANVAS_HEIGHT,
                  pagewidth=CANVAS_WIDTH-1,
                  pageheight=CANVAS_HEIGHT-1)

# read the postscript data
data = ski_io.imread("tmp_canvas.eps")

# write a rasterized png file
ski_io.imsave("canvas_image.png", data)

I do not really like workarounds, but skimage seems to be the fastest solution for reading postscript files and writing pngs.

Scikit-image is developed as a toolkit for SciPy, therefore it is working with scipy.ndimage internally, which is exactly what I want and can be used to create np.ndarray very easily.

Additionally scikit-learn is a powerful and fast image processing software itself, which can manipulate, read, and save various image formats.

Now you have the full choice: get a NumPy np.ndarray out of Canvas data for further computations, manipulate the scipy.ndimage with SciPy/scikit-image or save the data, e.g. as a rasterized png, to disk.


Post a Comment for "How To Get Numpy Array Of Canvas Data?"