如何获取Numpy数组的Canvas数据? [英] How to get Numpy array of Canvas data?

查看:191
本文介绍了如何获取Numpy数组的Canvas数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用Tkinter构建一个应用程序,在该应用程序中可以绘制例如画布中的线条.这很好.但是,我找不到用于获取当前Canvas数据的方法.最好是我想从当前的Canvas数据中获取一个numpy数组,因为我的后处理步骤主要是使用numpy.

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.

有什么方法可以从Canvas数据中构建numpy数组吗?是某些颜色格式(例如RGB)吗?

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

我知道我可以获取信息,例如线(如坐标)中的所有像素,但我不需要此信息.我需要整个Canvas场景的栅格化图像数据.就像一个numpy数组或一个(光栅化的)图像(jpg,png,tiff,位图等).

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, ...).

推荐答案

就像@Bryan Oakley所说的:没有的方法来获取Tkinter画布图形的栅格化版本.

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)

我不太喜欢变通办法,但是skimage似乎是读取后记文件和编写png的最快解决方案.

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

Scikit图像被开发为

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.

另外scikit-learn本身是一款功能强大且快速的图像处理软件,可以操纵,读取和保存各种图像格式.

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

现在,您有完整的选择:从Canvas数据中获取 NumPy np.ndarray进行进一步的计算,用SciPy/scikit-image操纵scipy.ndimage或保存数据,例如作为光栅化的png到磁盘.

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.

这篇关于如何获取Numpy数组的Canvas数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆