-->

How to get Numpy array of Canvas data?

2019-08-12 15:23发布

问题:

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 data. Preferably I would like to get a numpy array out of the current Canvas data, since my post-processing steps are mostly using numpy.

Is there any way to build numpy arrays out of the Canvas data? In some color format like RGB, by preference?


I know that I can get the information e.g. of lines (like coordinates) out of the Canvas, but I do not need this information. I need a rasterized image data of the whole Canvas scene. Like a numpy array or a (rasterized) image (jpg, png, tiff, bitmap, ...).

回答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.