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调整代码缩进
时间: 2024-03-17 20:45:06 浏览: 159
好的,以下是调整缩进后的代码:
```python
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
```
希望这样调整后的代码更容易阅读和理解。如果您还有其他问题,请随时提出。
阅读全文