import turtle def draw_image(image): turtle.speed(0) turtle.penup() turtle.goto(-250, 250) turtle.pendown() for row in image: for pixel in row: if pixel == 1: turtle.forward(10) else: turtle.penup() turtle.forward(10) turtle.pendown() turtle.penup() turtle.backward(len(row)*10) turtle.right(90) turtle.forward(10) turtle.left(90) turtle.pendown() image = [[0, 1, 1, 0, 0, 0, 1, 1, 0, 0], [1, 0, 0, 1, 0, 1, 0, 0, 1, 0], [1, 0, 0, 1, 0, 1, 0, 0, 1, 0], [0, 1, 1, 0, 0, 0, 1, 1, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 1, 1, 1, 1, 1, 1, 1, 1, 0], [0, 0, 0, 1, 0, 0, 1, 0, 0, 0], [0, 0, 0, 1, 0, 0, 1, 0, 0, 0], [0, 0, 0, 1, 0, 0, 1, 0, 0, 0], [0, 0, 0, 1, 0, 0, 1, 0, 0, 0]] draw_image(image) turtle.done() from PIL import Image def get_image_data(filename): # 打开图片 image = Image.open(filename) # 将图片转换为黑白模式 image = image.convert('1') # 获取图片的宽度和高度 width, height = image.size # 创建一个二维数组来存储图片数据 data = [[0]*width for _ in range(height)] # 遍历图片的每个像素点,将其值存储到二维数组中 for y in range(height): for x in range(width): pixel = image.getpixel((x, y)) data[y][x] = pixel return data 两个程序组合起来,变成一个程序使用
时间: 2023-09-29 14:07:25 浏览: 146
import turtle
from PIL import Image
def draw_image(image):
turtle.speed(0)
turtle.penup()
turtle.goto(-250, 250)
turtle.pendown()
for row in image:
for pixel in row:
if pixel == 1:
turtle.forward(10)
else:
turtle.penup()
turtle.forward(10)
turtle.pendown()
turtle.penup()
turtle.backward(len(row)*10)
turtle.right(90)
turtle.forward(10)
turtle.left(90)
turtle.pendown()
filename = "image.jpg"
image = get_image_data(filename)
draw_image(image)
turtle.done()
def get_image_data(filename):
# 打开图片
image = Image.open(filename)
# 将图片转换为黑白模式
image = image.convert('1')
# 获取图片的宽度和高度
width, height = image.size
# 创建一个二维数组来存储图片数据
data = [[0]*width for _ in range(height)]
# 遍历图片的每个像素点,将其值存储到二维数组中
for y in range(height):
for x in range(width):
pixel = image.getpixel((x, y))
data[y][x] = pixel
return data
阅读全文