@syoyo (Syoyo Fujita)

Are you sure you want to delete the question?

Leaving a resolved question undeleted may help others!

numpy 画像で n ピクセルおきに抜き出し n 枚の画像を作りたい

背景

たとえば, numpy で Bayer 画像をそれぞれのチャネルの画像に分解したい.
tile の反対のような感じです.
(日本語でも英語でも説明しづらい)

リファレンスとしては以下になりますが, 画像サイズが大きくなると処理が遅くなります.

# Simple mosaic image to channel plane decompose utility
# result = CHW where C = ny * nx
# TODO: Find better way 
def decompose_to_planes(img, ny, nx):

    assert img.ndim == 2

    ret = np.zeros(((ny*nx), img.shape[0]//ny, img.shape[1]//nx), dtype=img.dtype)

    for y in range(0, img.shape[0], ny):
        for x in range(0, img.shape[1], nx):

            for sy in range(ny):
                for sx in range(nx):

                    c = sy * nx + sx
                    ret[c][y//ny, x//nx] = img[y + sy, x + sx]

    return ret

質問

  • numpy API で上記のような処理を効率よく処理する方法を探しています.
0 likes

1Answer

nx, ny 置きに値を取り出すならスライスが簡単です

H, W = image.shape
h, w = H//ny, W//nx
ret = []
for sy in range(ny):
  for sx in range(nx):
    channel = img[range(sy,H,ny)][:, range(sx,W,nx)]  # スライスで格子点の値を取り出す
    ret.append(channel)  # (h,w)のndarrayのリストになっているので(ny*nx, h, w)に直すこと
2Like

Comments

  1. @syoyo

    Questioner

    Super awesome!!!! :tada:
    ありがとうございます! 行けました!

Your answer might help someone💌