Python - Turtle 重新创建图像太慢

Python - Turtle recreating image too slow

我很好奇,想知道我是否可以让 pyautogui 模块检测图像中每隔几个像素的颜色,并让乌龟在 canvas 中使用小圆圈重新创建它们。我最终找到了一种让它发挥作用的方法,而且我喜欢这些图像的效果!我的代码的唯一问题是需要一段时间才能完成。根据图像的大小,完成可能需要将近 10-30 分钟。有什么办法可以优化我的代码吗?我是相当新的,并且一直在尝试不同的模块,所以我非常感谢任何建议或帮助!如果你需要我澄清什么,我也很乐意

import time
import turtle
import pyautogui

time.sleep(2)
minimum = pyautogui.position()
print(minimum)
time.sleep(2)
max_x, max_y = pyautogui.position()
print(max_x, max_y)#I use the first point as the top left corner, and the second as the bottom right.

wn = turtle.Screen()
t = turtle.Turtle()
wn.colormode(255)#Allows RGB colors
t.pensize(2)
t.speed(0)
wn.setup(width = 1.0, height = 1.0)
wn.bgcolor("black")
x, y = minimum
min_x, min_y = minimum

def turtlemove(x, y):
    t.pu()
    t.goto(x - 965, 565 - y)#Compared coordinates in pyautogui with positions in turtle so they match.

def circle():
    t.pd()
    t.begin_fill()
    t.circle(2.9)
    t.end_fill()
    t.pu()

screenshot = pyautogui.screenshot()
while x != max_x and y != max_y:
    coordinate = x, y
    color = screenshot.getpixel(coordinate)
    t.pencolor(color)
    t.fillcolor(color)
    turtlemove(x, y)
    circle()
    if x < max_x:
        x += 6
    else:
        x = min_x
        y += 6
        #if y >= max_y:
            #break
print(t.pos())

wn.exitonclick()

以下是三个主要提示:

  1. 避免使用 + 运算符连接字符串
  2. 使用地图功能
  3. 避免重新计算函数

https://towardsdatascience.com/3-techniques-to-make-your-python-code-faster-193ffab5eb36[Read 此博客以获取更多信息。][1]

下面最显着的速度变化是使用 tracer()update() 来最小化乌龟在屏幕上的移动。你会惊讶于这种差异。但是,我还更改了坐标的处理方式、点的绘制方式以及其他内容:

from time import sleep
from turtle import Screen, Turtle
from pyautogui import position, screenshot

DOT_DIAMETER = 6
CHROME = 14  # borders and other such overhead of turtle window

# Obtain the top left corner, and the bottom right:
print("Move mouse to upper left corner.")
sleep(2)
min_x, min_y = position()
print(min_x, min_y)

print("Move mouse to lower right corner.")
sleep(2)
max_x, max_y = position()
print(max_x, max_y)

screenshot = screenshot()

screen = Screen()
screen.setup(width=max_x - min_x + 1 + CHROME, height=max_y - min_y + 1 + CHROME)
screen.setworldcoordinates(min_x, max_y, max_x, min_y)
screen.bgcolor('black')
screen.colormode(255)
screen.tracer(False)

turtle = Turtle()
turtle.penup()

for y in range(min_y, max_y, DOT_DIAMETER):
    for x in range(min_x, max_x, DOT_DIAMETER):
        coordinate = x, y
        # on my system getpixel() returned four values
        *color, alpha = screenshot.getpixel(coordinate)
        turtle.goto(coordinate)
        turtle.dot(DOT_DIAMETER * 1.333, color)  # * 1.333 for color overlap

    screen.update()

screen.tracer(True)
screen.exitonclick()

我发现 screenshot.getpixel() 在我的系统上返回了四个值,但是海龟颜色只有三个,所以我不得不这样做:

*color, alpha = screenshot.getpixel(coordinate)

您可能需要在您的系统上改回。