【问题标题】:How to convert Python OpenCV Image Matrix into a List of 4x4 blocks如何将 Python OpenCV 图像矩阵转换为 4x4 块列表
【发布时间】:2016-10-31 21:19:38
【问题描述】:

我有一个 512 x 512 个条目的矩阵形式的图像。像

[[12,234, . . ... .  (512 entries)],
 [[12,234, . . ... .  (512 entries)],
 [[12,234, . . ... .  (512 entries)],
 .
 .
 [12,234, . . ... .  (512 entries)]]

我想将图像分成 4x4 块并将它们放入一个列表中。我该怎么做呢?将有 128 个大小为 4 x 4 的块,从左侧开始索引。

【问题讨论】:

  • 那么,会有128 x 128 块对吗?
  • 你会怎么做?
  • 我想我会通过的。
  • You’re only as good as your weakest link
  • image[0:4, 0:4]image[a*4:a*4+4, b*4:b*4+4]?

标签: python arrays numpy


【解决方案1】:

这是我为此目的使用的一个函数:

def blockshaped(arr, nrows, ncols):

   h, w = arr.shape
   return (arr.reshape(h//nrows, nrows, -1, ncols)
           .swapaxes(1,2)
           .reshape(-1, nrows, ncols))

在哪里: arr = 你的输入二维 np 数组

windowsize = 整数,表示图块的大小

输出是一个形状为 (n, nrows, ncols) 的数组,其中 n * nrows * ncols = arr.size。

【讨论】:

  • 老兄,太长了。 Furas 更短
  • 它的代码更长,但速度更快,因为没有 for 循环。如果您需要处理大量图像,您不想在 Numpy 中使用 for-loop
  • 这是很好的信息@cf2。您能否修改此代码以将结果存储为一对块?我的意思是,在最终列表中,您将值存储为元组,其中每个元组是 (block, block_no) 其中 block_no 是处理此块的顺序?
【解决方案2】:

OpenCV 使用 numpynumpy 让您可以使用像 image[0:4, 0:4] 这样的索引来获得平方:

所以你需要类似这样的东西:

width, height = image.shape

# for image with ie. `RGB` color (3 bytes in every pixel)
#width, height, depth = image.shape 

blocks = []

for y in range(0, height, 4):
    for x in range(0, width, 4):
        blocks.append(image[y:y+4, x:x+4])

【讨论】:

  • ValueError: need more than 2 values to unpack
  • 感谢 furas,你是真正的上帝,不像 @Divakar 的假冒者
  • @Solly 你是对的 - 我用RGB color 对真实图像进行了测试。
  • 是的。你是老板。这是一个很好的解决方案。波兰人摇滚
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-06-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-03-10
  • 1970-01-01
  • 2012-05-24
相关资源
最近更新 更多