我在 humanbenchmark.com 上创建了一个用于目标训练器测试的机器人,我正在努力提高它的速度。目前,我定义了一个函数,可以截取屏幕截图,然后扫描目标图像并单击那里。但是,为了有效地确定目标在哪里,我需要检查三个不同像素的颜色,看看它们是否与背景颜色不同。这样做时,我有 3 个不同的 if 语句,我想知道是否可以将 if 语句组合成 1 个 if 语句和 2 个 or 语句。可能有一种更有效的方法来完全做到这一点,但这是我能想到的最好的方法。代码有点难以阅读,因为我尝试定义通用函数,而不仅仅是这个特定用途,但这并不可怕。
def scan(colors, width, height, start_x=66, start_y=231, stop_x=1900, stop_y=838):
im = auto.screenshot('C:\\Windows\\Temp\\screenshot.png')
coordinates = []
additive = round((height / 2), 0)
x_range = stop_x - start_x
y_range = stop_y - start_y
for x in range(0, math.ceil((x_range / width))):
for y in range(0, math.ceil((y_range / height))):
pixel_1 = im.getpixel((((width * x) + start_x), (start_y + (height * y))))
pixel_2 = im.getpixel((((width * x) + start_x), (start_y + (height * (y + 1)))))
pixel_3 = im.getpixel((((width * x) + start_x), (additive + start_y + (height * y))))
for i in range(0, len(colors)):
if pixel_1 == colors[i]:
location_x = (width * x) + start_x
location_y = (height * y) + start_y
coordinates.append(location_x)
coordinates.append(location_y)
break
if pixel_2 == colors[i]:
location_x = (width * x) + start_x
location_y = (height * (y + 1)) + start_y
coordinates.append(location_x)
coordinates.append(location_y)
break
if pixel_3 == colors[i]:
location_x = (width * x) + start_x
location_y = (height * y) + start_y + additive
coordinates.append(location_x)
coordinates.append(location_y)
break
return coordinates[0], coordinates[1]
这就是我想要做的事情。
def scan(colors, width, height, start_x=66, start_y=231, stop_x=1900, stop_y=838):
im = auto.screenshot('C:\\Windows\\Temp\\screenshot.png')
coordinates = []
additive = round((height / 2), 0)
x_range = stop_x - start_x
y_range = stop_y - start_y
for x in range(0, math.ceil((x_range / width))):
for y in range(0, math.ceil((y_range / height))):
pixel_1 = im.getpixel((((width * x) + start_x), (start_y + (height * y))))
pixel_2 = im.getpixel((((width * x) + start_x), (start_y + (height * (y + 1)))))
pixel_3 = im.getpixel((((width * x) + start_x), (additive + start_y + (height * y))))
for i in range(0, len(colors)):
if pixel_1 == colors[i] or pixel_2 == colors[i] or pixel_3 == colors[i]:
...
return coordinates[0], coordinates[1]
有一些边缘情况使该程序不起作用,但它们并不常见,因此不值得为了解决这些问题而牺牲效率。
我尝试将其作为一个 if 语句,但我无法找到一种方法来判断哪个语句是正确的。我尝试将其减少到只检查一两个像素,但这导致了太多的情况,它没有检测到目标并且程序崩溃了。我希望能够加快程序速度,因为目前该函数的每次调用大约需要 200 毫秒。
您可以在测试时使用海象运算符来分配变量
pixel = None
if (pixel_1 == colors[i] and (pixel := 1)) or (pixel_2 == colors[i] and (pixel := 2)) or (pixel_3 == colors[i] and (pixel := 3)):
location_x = (width * x) + start_x
if pixel == 1:
location_y = (height * y) + start_y
elif pixel == 2:
location_y = (height * (y + 1)) + start_y
else:
location_y = (height * y) + start_y + additive
coordinates.append(location_x)
coordinates.append(location_y)
break