python - 在 python 中跟踪图像

标签 python numpy opencv image-processing

我写了这个 python 脚本来跟踪图像。但它抛出一个错误。它显示 “IndexError:索引 181 超出尺寸为 181 的轴 0 的范围”,其中我的图像尺寸为 181x158。我减小了范围以纠正此错误,但是没有用。

import cv2
import numpy as np
global p
a = cv2.imread('t.png',0);
b = (255 -a);
c = np.asarray(b);
p = np.count_nonzero(c)
[ay , ax] = c.shape;
z = np.zeros(c.shape, dtype=np.int)

def startTrace(yt,xt):
    global p
    p = p-1
    z[yt,xt] = 255;
    c[yt,xt] =0;
    if (c[yt, xt+1] > 0):
        startTrace(yt,xt+1)
    elif (c[yt+1,xt+1] > 0):
        startTrace(yt+1,xt+1)
    elif (c[yt+1,xt] > 0):
        startTrace(yt+1,xt)
    elif (c[yt+1,xt-1] >0) :
        startTrace(yt+1,xt-1)
    elif (c[yt,xt-1] >0):
        startTrace(yt,xt-1)
    elif (c[yt-1,xt-1] > 0):
        startTrace(yt-1,xt-1)
    elif (c[yt-1,xt] > 0):
        startTrace(yt-1,xt)
    elif (c[yt-1,xt+1] > 0):
        startTrace(yt-1,xt+1)


while (p > 0):
    for y in range(1,ay-2):
        for x in range(1,ax-2):
            if c[y,x] > 0 :
                startTrace(y,x);

最佳答案

请注意,您的代码是递归的(startTrace 调用自身)并且您不知道它将调用自身多少次。事实上,您能保证对 startTrace() 的一次调用会退出吗? startTrace() 可以永远调用 startTrace() 吗?这最终会导致堆栈溢出。但这不是你的问题(目前)。

代码失败是因为对 startTrace 的每次调用都与对 startTrace() 的原始调用具有不同的参数(+1、-1)。即使在“while”内调用确保你没有越界,如果递归调用 startTrace(),每个新调用可能有原始参数 +1,最终会增长到越界(没有检查在 startTrace() 内部,参数在图像的边界内)。您应该在函数的开头添加一个 if 以检查 xt 和 yt 是否在图像的边界内。

无论如何,我建议在 OpenCV 中搜索一种可以满足您要求的方法。例如,看看 findContours。

关于python - 在 python 中跟踪图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47917906/

相关文章:

python - 无法找出 Heroku 应用程序失败的位置 [错误 : pg_config executable not found.]

opencv - ORB/BFMatcher - 为什么是 norm_hamming 距离?

python - 从源文件构建 OpenCV 库

python - 如何在列表框上绑定(bind) "select all"事件?

python - 递归地收集 QTreeview 中的所有项目

python - 将 Pandas 数据框字符串拆分为单独的行

python - 使用 np.vectorize 时出现 ValueError - 我哪里出错了?

android - 如何使用级联分类器减少错误识别

python - 有条件分割字符串

python - 来自具有不同长度的列表列表的 NumPy 数组(填充)