在python中跟踪图像

问题描述 投票:1回答:2

我写了这个python脚本来跟踪图像。但这是一个错误。它显示“IndexError:索引181超出轴0的大小为181”,其中我的图像大小为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);
python numpy opencv image-processing
2个回答
1
投票

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

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

无论如何,我建议在OpenCV中搜索一个能做你想要的方法。例如,看看findContours。


0
投票

感谢大家的帮助。此代码工作正常。

import cv2
import numpy as np


global p
a = cv2.imread('t.png',0);
[ty,tx] = a.shape;
o = np.zeros((ty+2,tx+2),dtype=np.int)
o[1:ty+1,1:tx+1] = (255 -a);
c = np.asarray(o);
p = np.count_nonzero(c)
[ay , ax] = c.shape;
z = np.zeros(c.shape, dtype=np.int)

def startTrace(yt,xt):
    global p
    cv2.imshow('image',z);
    z[yt,xt] = 255;
    c[yt,xt] =0;
    p = np.count_nonzero(c)
    if((yt < ay-1) and (xt < ax -1)): 
        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);
© www.soinside.com 2019 - 2024. All rights reserved.