如何将 Turtle 画布另存为图像(.png 或 .jpg) [英] How can I save a Turtle canvas as an image (.png or .jpg)

查看:171
本文介绍了如何将 Turtle 画布另存为图像(.png 或 .jpg)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在使用乌龟模块,并希望将其用作开发一个可以识别数字/字母的简单图像识别程序的起点.我需要能够将海龟保存为我可以操纵的图像 - 重新缩放、旋转等,以尝试调节图像.我已经研究了几个小时,似乎找不到任何有效的方法.我发现了如何将 Turtle 输出保存为 Tkinter 画布:

I've been working with the turtle module and want to use it as a starting point to work on a simple image recognition program that could recognize numbers/letters. I need to be able to save the turtle as an image I could manipulate - rescaling, rotating, etc. to try to regulate the images. I've been researching for hours and cannot seem to find anything that works. I have discovered how to save the Turtle output as a Tkinter canvas:

import turtle
t = turtle.Turtle()
# Draw something
canvas = t.getscreen().getcanvas()  # Saves a Tkinter canvas object

这似乎很好用.下一步是将其另存为 .png 或 .jpg.但是,我唯一能找到的是如何将其另存为 postscript 文件:

This seems to work great. The next step is to save that as a .png or .jpg. However, the only thing I can find is how to save it as a postscript file:

canvas.postscript(file="turtle_img.ps")  # Saves as a .ps file

从那里开始,我尝试使用 PIL 将 .ps 文件转换为 .png 或 .jpeg 文件.这是我的代码以及我得到的错误:

From there, I have attempted to convert the .ps file into a .png or .jpeg file using PIL. Here is my code for that and the error that I get:

from PIL import Image
turtle_img = Image.open("turtle_img.ps")
turtle_img.save("turtle_img", "png")
# Also tried:   turtle_img.save("turtle_img, "jpeg")

运行 "turtle_img.save("turtle_img", "png") 行产生:

Running the line "turtle_img.save("turtle_img", "png") produces:

OSError: Unable to locate Ghostscript on paths

我喜欢以下之一:1. 一种将 .ps 转换为 .jpeg、.png 甚至位图的方法2.另一种保存Tkinter画布的方法,更容易使用

I would love one of the following: 1. a way to convert a .ps into a .jpeg, .png, or even a bitmap 2. An alternate way of saving a Tkinter canvas that is easier to work with

我想澄清一下,我将使用大量这些,并希望在脚本中自动化该过程,而不是对每个图像使用命令行.

I wanted to clarify that I would be working with a large number of these and would like to automate the process in a script rather than use the command line for each image.

推荐答案

您可以使用 Ghostscript 将 PostScript 程序呈现为位图.例如:

You can use Ghostscript to render a PostScript program to a bitmap. For example:

gs -sDEVICE=png16m -o out.png input.ps

还有其他文件格式和颜色深度可用,例如 png256、jpeg 等.如果是多页输入文件,则:

There are other file formats and colour depths available, such as png256, jpeg etc. If it's a multi-page input file then:

gs -sDEVICE=png16m -o out%d.png input.ps

这篇关于如何将 Turtle 画布另存为图像(.png 或 .jpg)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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