为什么pyautogui.click()返回类型错误



我正在尝试制作一个可以检测眼睛是睁开还是闭合的脚本。我使用下面的代码来完成这项工作。

https://github.com/balajisrinivas/Color-Detection-OpenCV

感谢巴拉吉斯里尼瓦斯提供的代码!

使用此代码,我可以添加实时视频捕获,并创建一个在while循环中每2秒刷新一次的单个图像,而不是单个图像(以colorpic.jpg为例(。此外,我做了它,如果颜色是棕色或RGB接近棕色,计算机会发出哔哔声,但如果颜色是白色、黑色或虹膜的颜色,它就会知道你的眼睛没有闭上。有一个问题。问题是我必须点击图片才能得到结果,但我希望它能自动发生。因此,我在while True:循环中使用ifpyautogui.locateOnScreen(‘needle.jpg’, confidence=0.8)而不是if clicked。图片的指针。。jpg是我眼睛的照片。之后,我添加了pyautogui.click(‘needle.jpg’),它会点击图片的中心,给我一个睁开或闭上眼睛的结果,而无需手动点击。

我陷入困境的地方:


while True:
cv2.imshow("image", img)
if pyautogui.locateOnScreen('needle.jpg', confidence=0.8):
pyautogui.click('needle.jpg')
# cv2.rectangle(image, start point, endpoint, color, thickness)-1 fills entire rectangle
cv2.rectangle(img, (20, 20), (750, 60), (b, g, r), -1)
# Creating text string to display( Color name and RGB values )
text = get_color_name(r, g, b) + ' R=' + str(r) + 
' G=' + str(g) + ' B=' + str(b)

之前的代码是:

while True:
cv2.imshow("image", img)
if clicked:
# cv2.rectangle(image, start point, endpoint, color, thickness)-1 fills entire rectangle
cv2.rectangle(img, (20, 20), (750, 60), (b, g, r), -1)
# Creating text string to display( Color name and RGB values )
text = get_color_name(r, g, b) + ' R=' + str(r) + 
' G=' + str(g) + ' B=' + str(b)

唯一的问题是我得到了一个类型错误。

这就是错误:

Traceback (most recent call last):
File "C:Usersuser1DesktopColor-Detection-OpenCVhello.py", line 89, in <module>
pyautogui.click('needle.jpg')
line 598, in wrapper
returnVal = wrappedFunction(*args, **kwargs)
File "C:Usersuser1AppDataLocalProgramsPythonPython39libsite-packagespyautogui__init__.py", line 980, in click
x, y = _normalizeXYArgs(x, y)
TypeError: cannot unpack non-iterable NoneType object

只是想让你们知道,我是蟒蛇的新手,我是一名在校学生。如果你知道我为什么会出现这个错误的答案,请帮助我。谢谢!

看起来这只是pyautogui的有意疏忽。因为我们已经知道图像在您的locateOnScreen调用中的位置,所以为什么我们在单击时再次搜索。

来自他们的源代码:

def _normalizeXYArgs(firstArg, secondArg):
# skip

elif isinstance(firstArg, str):
# If x is a string, we assume it's an image filename to locate on the screen:
try:
location = locateOnScreen(firstArg)
# The following code only runs if pyscreeze.USE_IMAGE_NOT_FOUND_EXCEPTION is not set to True, meaning that
# locateOnScreen() returns None if the image can't be found.
if location is not None:
return center(location)
else:
return None
# skipping lines past this

最后我们看到评论说,如果找不到图像,locateOnScreen将返回None。

对于您对locateOnScreen的调用,您通过了confidence=0.8,但默认置信度为0.999

因此,在置信度为0.8的情况下,图像被发现,但不具有0.999。因此,它将None返回到location,然后引导if块返回None,这是不可打包的。

由于我目前在移动设备上,我无法测试自己,但我敢打赌locateOnScreen在匹配时会返回x,y坐标。

所以试着把if块改成这样。

try:
x, y = pyautogui.locateOnScreen( ~~~ )
except TypeError:
# value unpack failed, so we got None. Therefore no image matched.
# therefore no x exist.
# Put things you want to do when there's NO image matched.
pass
else:
# Put things you want to do when image matched.
pyautogui.click(x, y)

我强烈建议阅读错误处理部分的官方文件。

相关内容

最新更新