Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- from PIL import Image
- import turtle
- def get_image_data(image_filepath):
- image = Image.open(image_filepath)
- pixels = image.load()
- width, height = image.size
- return width, height, pixels
- def pixel_tuple_to_hex(pixel_tuple):
- hex_code = "#"
- for rgb in pixel_tuple:
- if len(str(hex(rgb))) < 4:
- hex_code += "0" + str(hex(rgb))[-1:]
- else:
- hex_code += str(hex(rgb))[-2:]
- return hex_code
- def pixel_tuple_to_ascii(pixel_tuple):
- total = sum(pixel_tuple)
- if total > 612:
- return " "
- if total > 459:
- return "~"
- if total > 306:
- return "+"
- if total > 153:
- return "@"
- else:
- return "#"
- def turtle_plot_pixel(turtle,size):
- turtle.begin_fill()
- for i in range(4):
- turtle.forward(size)
- turtle.right(90)
- turtle.forward(size)
- turtle.end_fill()
- def turtle_plot_image(image_width, image_height, image_pixels, pixel_size):
- turtlex = 0-(image_width*(pixel_size/2))
- turtley = image_height*(pixel_size/2)
- canvas = turtle.Screen()
- canvas.setup(width = image_width*pixel_size, height = image_height*pixel_size, startx = turtlex, starty = turtley)
- t = turtle.Turtle()
- t.speed(999)
- t.penup()
- t.setx(turtlex)
- t.sety(turtley)
- t.pendown()
- for y in range(image_height):
- for x in range(image_width):
- t.color(pixel_tuple_to_hex(image_pixels[x,y]))
- turtle_plot_pixel(t,pixel_size)
- t.penup()
- turtley -= pixel_size
- t.setx(turtlex)
- t.sety(turtley)
- t.pendown()
- canvas.mainloop()
- def ascii_plot_image(image_width, image_height, image_pixels, ascii_filename):
- text_file = open(ascii_filename,"w")
- ascii_conversion = []
- for y in range(image_height):
- current_line = []
- for x in range(image_width):
- current_line.append(pixel_tuple_to_ascii(image_pixels[x,y]))
- ascii_conversion.append(current_line)
- for line in ascii_conversion:
- text_file.writelines("".join(line)+"\n")
- text_file.close()
- def image_to_turtle(image_filepath,pixel_size):
- image_width, image_height, image_pixels = get_image_data(image_filepath)
- turtle_plot_image(image_width, image_height, image_pixels, pixel_size)
- def image_to_ascii(image_filepath,ascii_filename):
- image_width, image_height, image_pixels = get_image_data(image_filepath)
- ascii_plot_image(image_width, image_height, image_pixels, ascii_filename)
- image_to_ascii("pika.jpg","pika_ascii.txt")
- image_to_turtle("pika.jpg",25)
Advertisement
Add Comment
Please, Sign In to add comment