Skip to main content
 首页 » 编程设计

python之如果有 2 个字幕,说明会丢失,只有 1 个可以正常工作

2024年11月24日10think

当我将文本值“(255, 255, 255)”而不是 location 放在 while 和 if 指令中时,一切正常。我已经排除故障 3 个小时了,我的想法已经用完了。我已经确保当颜色相同时,这个循环就会丢失。

我正在制作一个在游戏中使用它的程序,作为我的学校项目。它需要检测你在哪里,我通过颜色检测它,特别是 ImageGrab 库。

from PIL import ImageGrab 
import time 
 
time.sleep(1) 
px=ImageGrab.grab().load()                
 
x = 20 
 
y = 20 
 
color = px[x, y] 
 
location = '(255, 255, 255)' 
 
if (color == location): 
    print('you are here') 
 
 
if not (color == location): 
    print('you arent here') 

即使像素是白色,它每次都会告诉它不是,这是不正确的。怎么了?这对我来说真的很奇怪。

请您参考如下方法:

ImageGrab.grab().load() 函数返回的是一个整数元组数组。

换句话说,每个像素都是一个元组,看起来像这样:

In [4]: im = ImageGrab.grab().load() 
 
In [5]: im[0,0] 
Out[5]: (24, 24, 25, 255) 

其中包含 (red,green,blue,alpha) 类型的值 int。

您正在尝试将一个数字元组与一个字符串进行比较,location = '(255, 255, 255)'。它会失败,因为您无法将字符串(字符数组)与数字进行比较。

例如,

In [12]: 2 == '2' 
Out[12]: False 

我不会为你解决你的家庭作业,但也许这会有所帮助:

In [14]: location = (255,255,255) 
 
In [15]: color = (255,255,255,0) 
 
In [16]: [color[i] == location[i] for i in range(3)] 
Out[16]: [True, True, True] 
 
In [17]: all([color[i] == location[i] for i in range(3)]) 
Out[17]: True