为矩形图像创建重叠的正方形补丁

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

给出矩形图像img和补丁s。现在,我想用边长为s的正方形色块覆盖整个图像,以便img中的每个像素都使用最少的色块数至少包含一个色块。此外,我希望相邻的补丁尽可能少地重叠。

至此:我已经在下面包含了我的代码,并给出了一个示例。但是,它并不完美。希望有人发现错误。

[示例:给出形状为img(4616, 3016)s = 224这意味着我将在较长的一侧上粘贴21个补丁,在宽度较小的一侧上粘贴14个补丁,总共21 * 14 = 294个补丁。

现在,我尝试找出补丁如何在补丁之间分配重叠部分。我的色块可以覆盖大小为(4704, 3136)的图像,因此我的色块在高度上必须覆盖88个重叠像素missing_h = ht * s - h,宽度类似。

现在我尝试找出如何在21个色块上分配88个像素。 88 = 4 * 21 + 4因此,我将有hso = 17个色块与shso = 4重叠,hbo = 4个色块与5重叠,宽度相似。

现在,我只需遍历整个图像并跟踪当前位置(cur_h, cur_w)。每次循环后,我都会调整cur_h, cur_w。我有s,我当前的补丁程序编号i, j,它指示补丁程序重叠的大小是小还是大。

import numpy as np

def part2(img, s):
    h = len(img)
    w = len(img[0])

    ht = int(np.ceil(h / s))
    wt = int(np.ceil(w / s))

    missing_h = ht * s - h
    missing_w = wt * s - w
    hbo = missing_h % ht
    wbo = missing_w % wt
    hso = ht - hbo
    wso = wt - wbo
    shso = int(missing_h / ht)
    swso = int(missing_w / wt)

    patches = list()
    cur_h = 0

    for i in range(ht):
        cur_w = 0
        for j in range(wt):
            patches.append(img[cur_h:cur_h + s, cur_w: cur_w + s])
            cur_w = cur_w + s
            if j < wbo:
                cur_w = cur_w - swso - 1
            else:
                cur_w = cur_w - swso
        cur_h = cur_h + s
        if i < hbo:
            cur_h = cur_h - shso - 1
        else:
            cur_h = cur_h - shso

    if cur_h != h or cur_w != w:
        print("expected (height, width)" + str((h, w)) + ", but got: " + str((cur_h, cur_w)))

    if wt*ht != len(patches):
        print("Expected number patches: " + str(wt*ht) + "but got: " + str(len(patches)) )


    for patch in patches:
        if patch.shape[0] != patch.shape[1] or patch.shape[0] != s:
            print("expected shape " + str((s, s)) + ", but got: " + str(patch.shape))
    return patches


def test1():
    img = np.arange(0, 34 * 7).reshape((34, 7))
    p = part2(img, 3)
    print("Test1 successful")


def test2():
    img = np.arange(0, 4616 * 3016).reshape((4616, 3016))
    p = part2(img, 224)
    print("Test2 successful")


test1()
test2()
python image-processing sampling subsampling
1个回答
1
投票

以上问题可以解决,请进行以下编辑:

hbo = missing_h % (ht-1)
wbo = missing_w % (wt-1)
shso = int(missing_h / (ht-1))
swso = int(missing_w / (wt-1))
© www.soinside.com 2019 - 2024. All rights reserved.