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/

相关文章:

java - 如何在OpenCV中获取由四个点定义的四边形内部的像素?

python - 调试时掉帧?

python - 在 Pandas 的列上应用 lambda

python - 为什么使用@contextmanager装饰器时需要 "try-finally"?

python - 如何使用 numpy 为图像的所有相对白色部分创建蒙版?

android - 在 Android 中成功加载 OpenCV 后,imgproc.Canny 出现 UnsatisfiedLinkError

python - 为什么我会收到 SQLAlchemy 嵌套回滚错误?

python - 如何使用 django (python) 和 s3 上传文件?

python - Python-使用yield停止无限循环,然后重定向

python - OpenCV - 新的 Python 绑定(bind)和 ImageROI?