if (c & 0xFF == ord('q')).any(): # 按下 q 程序结束 stop = True cv2.destroyAllWindows() # 释放窗口

在 OpenCV 中处理键盘事件时,您可能会遇到以下错误:

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

此错误通常发生在您尝试使用布尔运算符(如 == 或 !=)比较 NumPy 数组时。由于数组可能包含多个元素,因此 Python 不知道如何解释该数组的真值。为了解决此问题,您可以使用 a.any()a.all() 方法。

a.any() 方法检查数组中是否存在任何 True 元素,而 a.all() 方法检查数组中是否所有元素都为 True。

示例代码:

import cv2

# ...

while True:
    # ...

    # 获取键盘输入
    c = cv2.waitKey(1)

    # 检查是否按下 q 键
    if (c & 0xFF == ord('q')).any():  # 按下 q 程序结束
        stop = True
        cv2.destroyAllWindows()  # 释放窗口

    # ...

在上面的示例代码中,我们将 (c & 0xFF == ord('q')) 括起来,并使用 any() 方法来检查数组中是否存在任何 True 元素。如果按下 q 键,则该条件将为 True,程序将结束。

通过使用 a.any()a.all() 方法,您可以正确地处理 NumPy 数组的真值,并避免出现上述错误。

OpenCV 中处理键盘事件的 ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all() 错误解决

原文地址: https://www.cveoy.top/t/topic/mUeY 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录