首页 > 解决方案 > 为什么我的图像在 Microsoft Paint 中绘制不正确?

问题描述

我创建了一个程序,其目标是在 Microsoft 绘图中重新绘制图片,但是,它不是重新创建确切的图像,而是将每个像素放在错误的位置。例如,这是我将尝试重新创建的图像,这是它将在此处绘制的图像 是我的 (python) 代码:

import pyautogui as py
from PIL import Image, ImageOps
import time
from playsound import playsound

im = Image.open('google.jpg')  # Can be many different formats.
pix = im.load()

a = 0
b = 0
c = 460
d = 0
e = 0
g = 0
x, y = 5, 144
pixx, pixy = 0, 0
w, h = im.size

py.moveTo(x=132, y=1080)
time.sleep(1)
py.click()
while a <= w * h:
    py.click(x=984, y=95)
    while b <= 2:
        py.doubleClick(x=831, y=c)
        f = str(pix[pixx, pixy][b])
        py.write(f)
        b += 1
        c += 20
    py.click(x=466, y=520)
    b = 0
    c = 460
    d += 1
    a += 1
    if pixx < w:
        pixx += 1
    if pixx == w:
        pixx = 0
        pixy += 1
    if e < w and g <= h:
        py.click(x, y)
        x += 1
        e += 1
        # pixx += 1
    elif e == w and g <= h:
        py.click(x, y)
        g += 1
        y += 1
        x = 5
        e = 0
        # pixx = 0
        # pixy += 1
    else:
        playsound('bruh.mp3')
        print('bruh')

playsound('bruh.mp3')

标签: pythonpython-3.x

解决方案


我认为您的代码中有两个问题,这两个问题都源于您的代码不是 DRY 的事实。

DRY 代表不要重复自己。您的代码具有用于从源图像中选择下一个像素以及在目标图像中绘制像素的位置的单独代码。这两件事的行为需要相同,但是因为它使用不同的代码路径,很可能某个地方的错误会使这种行为不同。

我不可能在本地测试您的代码,但我认为两个错误是:

  • 在源像素坐标更新之前读取源像素,但在目标像素坐标更新后单击目标像素
  • 在更新其 x 坐标后检查源像素是否超出行尾 - 仅在不更新 x 坐标时检查目标像素是否超出行尾(在前一种情况下,有一个if而不是一个elif)

与其循环以获得正确的像素数,不如单独循环xy然后您可能会丢失所有容易出错的代码,您可以在其中检查需要更新的坐标。

为什么不更新两组坐标,而不是更新一组坐标,以及转换到另一组的简单方法?

就像是:

def set_colour_from_source(x, y):
    py.click(x=984, y=95)
    for b in range(2):
        c = 460 + (20 * b)
        py.doubleClick(x=831, y=c)
        f = str(pix[x, y][b])
        py.write(f)
    py.click(x=466, y=520)

def get_destination_coords(x, y):
    return (5 + x, 144 + y)

for x in range(w):
    for y in range(h):
        set_colour_from_source(x, y)
        dx, dy = get_destination_coords(x, y)
        py.click(dx, dy)

推荐阅读