首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在python中跟踪图像

在python中跟踪图像
EN

Stack Overflow用户
提问于 2017-12-21 04:21:47
回答 2查看 3.1K关注 0票数 1

我编写了这个python脚本来跟踪图像。但这是个错误。它显示的是"IndexError:索引181对于大小为181“的的轴0是超出界限的,其中我的图像大小是181x158。我缩小了范围,以纠正这一错误,但,没有用。

代码语言:javascript
复制
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);
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2017-12-24 04:40:23

感谢你们的帮助。这段代码工作正常。

代码语言:javascript
复制
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);
票数 0
EN

Stack Overflow用户

发布于 2017-12-21 14:33:06

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

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

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

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/47917906

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档