如何在Python中使用欠擬合,而不損失準確性?

2024-09-30 20:31:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我一直在努力使用tweening使Python中的鼠标移动平滑,我目前正在尝试自动化一些重复的任务。在

我曾尝试使用tweening来去除一些没有应用平滑的粗糙度,但是这样做我会损失大量的精确度,毕竟我的dy和{}的值被一个number分割,最后我得到了剩余的。这可以通过在我的两个值上得到greatest common factor来解决(因为dx和{}都需要被相同的number分割),不幸的是这导致GCD太小。在

因为鼠标不能移动屏幕上像素的剩余部分,所以我的精确度明显下降。在

问:如何在不损失准确性的情况下,将tweening应用于鼠标移动?在

import pytweening
import win32api
import win32con
from time import sleep

dy = [50, 46, 42, 38, 33, 29, 24, 20, 15, 10, 10]
dx = [-35, 6, -55, -43, 0, 17, 29, 38, 42, 42, 38]

while True:

    count = 0

    values = [(pytweening.getPointOnLine(0, 0, x, y, 0.20)) for x, y in zip(dx, dy)]

    while win32api.GetAsyncKeyState(win32con.VK_RBUTTON) and win32api.GetAsyncKeyState(win32con.VK_LBUTTON):

        if count < len(dx):

            for _ in range(5):
                win32api.mouse_event(1, int(values[count][0]), int(values[count][1]), 0, 0)
                sleep(0.134 / 5)

            count += 1

Tags: importnumbercountsleep鼠标values损失while
2条回答

Question: Tweening, without losing accuracy?

参考

  • PyTweening - ^{}

    x, y = getLinePoint(startPoint x, startPoint y, endPoint x, endPoint y, intervall)

    The getLinePoint() function finds a point on the provided line.


  1. 将您的列表dxdy转换为tuple(x, y)的列表

    dx = [-35, 6, -55, -43, 0, 17, 29, 38, 42, 42, 38]
    dy = [50, 46, 42, 38, 33, 29, 24, 20, 15, 10, 10]
    
    points = list(zip(dx, dy))
    print(points)
    

    Output:

    [(-35, 50), (6, 46), (-55, 42), (-43, 38), (0, 33), (17, 29), (29, 24), (38, 20), (42, 15), (42, 10), (38, 10)]
    
  2. 在一个双for循环中处理这个points列表。在

    ^{pr2}$

    Output: The End Points are allways reached!

    First move from (-35, 50) to (6, 46):
    (-35, 50), (-26, 49), (-39, 48), (-36, 47), (-28, 46), (-24, 45),(-22, 44),
    (-20, 44), (-19, 43), (-19, 42), (-20, 42), (-2, 46), (6, 46)
    
    ... (omitted for brevity)
    
    Last move from (42, 10) to (38, 10):  
    (42, 10), (41, 10), (23, 18), (31, 17), (19, 16), (21, 15), (30, 14),
    (33, 13), (36, 12), (38, 12), (38, 11), (38, 10), (38, 10)
    

使用Python:3.6-pytweening:1.0.3进行测试

这里的基本问题是,您使用的是整数形式的相对移动量,这将不等于您要查找的总移动量。如果你只想线性移动,你也根本不需要平纹呢。这个解决方案怎么样?在

import win32api
import win32con
from time import sleep

Npoints = 5
sleeptime = 0.134 / Npoints

dys = [50, 46, 42, 38, 33, 29, 24, 20, 15, 10, 10]
dxs = [-35, 6, -55, -43, 0, 17, 29, 38, 42, 42, 38]

x, y = win32api.GetCursorPos()

for dx, dy in zip(dxs, dys):
    ddx = dx/Npoints
    ddy = dy/Npoints
    for _ in range(Npoints):
        x += ddx
        y += ddy

        win32api.SetCursorPos(int(x), int(y))
        sleep(sleeptime)

请注意,仍然会有一些非常小的舍入误差,并且光标将在点之间沿直线移动。如果光标从(0,0)开始,这是它将形成的形状(红色十字是光标将设置到的点):

Shape of the mouse movements

如果您希望在平滑曲线中通过点移动,并且您可以使用numpy和scipy,则可以处理该问题:

^{pr2}$

结果如下所示:

Spline interpolation between points

相关问题 更多 >