python-3.xtkinterturtle-graphicstkinter-canvaspython-turtle

How can I save a Turtle canvas as an image (.png or .jpg)


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

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

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")

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

OSError: Unable to locate Ghostscript on paths

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

EDIT: 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.


Solution

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

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

    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