【问题标题】:Creating overlapping, square patches for rectangular images为矩形图像创建重叠的方形补丁
【发布时间】:2020-04-07 21:10:33
【问题描述】:

给定一个矩形图像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 = 4hbo = 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】:

    可以修复上述问题,进行以下编辑:

    hbo = missing_h % (ht-1)
    wbo = missing_w % (wt-1)
    shso = int(missing_h / (ht-1))
    swso = int(missing_w / (wt-1))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-09
      • 2014-05-13
      • 2013-05-22
      • 2021-09-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多