首页 > 解决方案 > python脚本在执行过程中停止而没有错误

问题描述

我有一个使用 python 显示 dfs 的简单脚本,它在没有完全执行的情况下停止

该脚本只输入一个图像,将其转换为只有 2 种颜色的图像(类似于 dfs 的岛屿和水问题)。

它从一个空白图像(背景)开始,然后显示一个动画,其中岛屿(前景色)一个一个变得可见。

它工作到某个点,然后完全停止。我检查了while循环停止时不满足的条件。

甚至没有打印 atexit 消息。

这是脚本

import imageFilters as imf
import imutils
import cv2
import numpy as np
import random
import sys
import atexit

sys.setrecursionlimit(1000000000)

atexit.register(print, "exited ")


background = [255, 255, 255] #white
foreground = [0,0,0] #black

img_path = input("ENTER IMAGE PATH:")

img = cv2.imread(img_path)

 #imf.createLineDrawing: resizes with height = 600 and creates an image with only two colors;
img = imf.createLineDrawing(img, foreground, background)
(height, width, channel) = img.shape

blank_image = np.ndarray([height, width, channel], img.dtype)
blank_image.fill(255)

done = np.ndarray([height, width], img.dtype)
countDone = 0

def searchNeighbour(x, y):

    global done,countDone

    done[y, x] = 1
    countDone += 1
    if list(img[y, x]) == foreground:
        blank_image[y, x] = foreground
    else:
        return

    cv2.imshow("o", blank_image)
    cv2.waitKey(1)

    if x - 1 >= 0 and not(done[y, x - 1]):
        searchNeighbour(x - 1, y)
    if x + 1 <= width - 1 and not(done[y, x + 1]):
        searchNeighbour(x + 1, y)
    if y - 1 >= 0 and not(done[y - 1, x]):
        searchNeighbour(x, y - 1)
    if y + 1 <= height - 1 and not(done[y + 1, x]):
        searchNeighbour(x, y + 1)


while countDone < height*width:
    x = random.randrange(0, width - 1)
    y = random.randrange(0, height - 1)
    if not(done[y, x]):
        searchNeighbour(x, y)

标签: pythonpython-3.xdepth-first-search

解决方案


把它贴在某个地方:

import pdb; pdb.set_trace()

然后h在它停止指示时键入。您可以逐行遍历并找出每一步的值


另外,完成后,也许可以尝试输入echo $?以查看它是否因错误退出。(如果您使用的是 unixy 的东西)(0表示它已完成,任何其他数字都表示一般情况下有些东西坏了)


或者,也许只是在项目的底部放一条线,上面写着

print("DONE PROGRAM %s" % countDone)

100% 不只是完成循环


推荐阅读