python - 如何捕获 python 中所有索引超出范围的错误?

标签 python opencv

我是计算像素点之间的距离,只是在程序中做了一个鼠标回调函数,用于计算x和y坐标。

这是我试过的代码,

def distance():
    length = len(position)
    # Distance in terms of x
    distance_value = position[length-1][0] - position[length-2][0]
    # Distance in terms of y
    # distance_value = position[length-1][1] - position[length-2][1]

    print("Value of pixel is: " + str(distance_value))

IndexError: list index out of range.

最佳答案

我想您需要执行以下操作:

def distance():
    length = len(position)
    # Distance in terms of x
    try:
        distance_value = position[length-1][0] - position[length-2][0]
        print("Value of pixel is: " + str(distance_value))
    except IndexError as e:
        print('There is an error')
        print(str(e))

关于python - 如何捕获 python 中所有索引超出范围的错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55593355/

相关文章:

python - 在非交互式环境中应用 Django 迁移

javascript - 将绘图中的数据保存到 csv 或 excel 文件中

python - “模块”对象不可迭代

Python Opencv imshow 错误

OpenCV 错误 : Bad argument <Unknown array type> in unknown function, 文件 ..\..\..\modules\core\src\matrix.cpp,第 697 行

python - 使用 Django Rest Frame 序列化非 django 模型

python - python 3.6 及更早版本与 3.7 中不可变对象(immutable对象)的 "is"行为不一致

Python和覆盆子picamera对象计数,多次计数

opencv - 16 位图像到 32 位

opencv - opencv中大图像的关键点检测和匹配