如何获取带边界条件的图像面积?

1 投票
1 回答
1105 浏览
提问于 2025-04-17 23:03

scipy.ndimage 这个库里,很多函数都有一个可选的参数 mode=nearest|wrap|reflect|constant,这个参数决定了当函数需要用到图像外部的数据时(也就是填充数据),应该怎么处理。填充的过程是由一个叫 NI_ExtendLine() 的内部代码来完成的。

我想要的是,不是直接在填充后的数据上运行 ndimage 函数,而是想要 直接获取填充后的数据,并且使用和 ndimage 一样的填充方式。

下面是一个例子(仅针对 mode=nearest,假设是二维图像):

"""
Get padded data.  Returns numpy array with shape (y1-y0, x1-x0, ...)
Any of x0, x1, y0, y1 may be outside of the image
"""
def get(img, y0, y1, x0, x1, mode="nearest"):
    out_img = numpy.zeros((y1-y0, x1-x0))
    for y in range(y0, y1):
        for x in range(x0, x1):
            yc = numpy.clip(y, 0, img.shape[0])
            xc = numpy.clip(x, 0, img.shape[1])
            out_img[y-y0, x-x0] = img[yc, xc]
    return out_img

这个方法是正确的,但因为它是逐个像素处理的,所以速度比较

那么,有什么更好的方法(最快、最清晰、最符合 Python 风格)来实现这个呢?

1 个回答

3

这段代码是用来做某些操作的,但具体的功能需要根据上下文来理解。通常情况下,代码块里会包含一些指令或者函数,这些指令会告诉计算机该怎么做。

如果你看到类似于

def get(img, y0, y1, x0, x1, mode="nearest"):
    xs, ys = numpy.mgrid[y0:y1, x0:x1]
    height, width = img.shape

    if mode == "nearest":
        xs = numpy.clip(xs, 0, height-1)
        ys = numpy.clip(ys, 0, width-1)

    elif mode == "wrap":
        xs = xs % height
        ys = ys % width

    elif mode == "reflect":
        maxh = height-1
        maxw = width-1

        # An unobvious way of performing reflecting modulo
        # You should comment this
        xs = numpy.absolute((xs + maxh) % (2 * maxh) - maxh)
        ys = numpy.absolute((ys + maxw) % (2 * maxw) - maxw)

    elif mode == "constant":
        output = numpy.empty((y1-y0, x1-x0))
        output.fill(0) # WHAT THE CONSTANT IS

        # LOADS of bounds checks and restrictions
        # You should comment this
        target_section = output[max(0, -y0):min(y1-y0, -y0+height), max(0, -x0):min(x1-x0, -x0+width)]
        new_fill = img[max(0, y0):min(height, y1), max(0, x0):min(width, x1)]

        # Crop both the sections, so that they're both the size of the smallest
        # Use more lines; I'm too lazy right now
        target_section[:new_fill.shape[0], :new_fill.shape[1]] = new_fill[:target_section.shape[0], :target_section.shape[1]]

        return output

    else:
        raise NotImplementedError("Unknown mode")

    return img[xs, ys]
这样的占位符,通常意味着这里应该有一段代码,但在这个地方没有显示出来。你可以把它想象成一个空白的框,里面应该填上具体的内容。

总之,代码的作用就是让计算机按照我们的要求去执行任务,而这些代码块就是实现这些任务的具体步骤。

撰写回答