将二进制图像划分为 4x4 Python 并计算像素



我有一个二进制图像,我想将其分成 4 x 4 像素的块,并计算块中黑色像素的数量。如果块中黑色像素的总和为偶数,则为相应的块分配值 0。否则,该值为 1。之后,将其保存/写入txt文件,以便我可以看到结果。

我尝试过使用代码,但卡住了

import matplotlib.pyplot as plt
import numpy as np
image = plt.imread('myplot1.png')
image = np.array(image)
image = image[:,:,1] #if RGB
print(image.shape)
for x in np.arange(0,image.shape[0]):
for y in np.arange(image.shape[1]):
if x+4 < image.shape[0] and y+4 < image.shape[1]:
sum = np.sum(image[x:x+4,y:y+4])
if sum > 4:
image[x:x + 4, y:y + 4] = 1
elif sum < 4:
image[x:x + 4, y:y + 4] = 0

借助为将 2D 数组拆分为较小块的问题提供的解决方案:

def block_view(A, block):
# Reshape the array into a 2D array of 2D blocks, with the resulting axes in the
# order of:
#    block row number, pixel row number, block column number, pixel column number
# And then rearrange the axes so that they are in the order:
#    block row number, block column number, pixel row number, pixel column number
return A.reshape(A.shape[0]//block[0], block[0], A.shape[1]//block[1], block[1])
.transpose(0, 2, 1, 3)
# Initial grayscale image
image = np.random.rand(16, 16)
# Boolean array where value is True if corresponding pixel in `image` is
# "black" (intensity less than 0.5)
image_bin = image < 0.5
# Create a 2D array view of 4x4 blocks
a = block_view(image_bin, (4, 4))
# XOR reduce each 4x4 block (i.e. reduce over last two axis), so even number
# of blacks is 0, else 1
a = np.bitwise_xor.reduce(a, axis=(-2, -1))
print(a.astype(np.uint8))

16x16 图像的示例输出:

[[0 1 1 0]
[0 0 1 0]
[1 1 1 1]
[0 0 0 1]]

编辑:

block_view()函数最初是在这个答案(使用as_strided()(之后实现的,但是经过更多的搜索,我决定改用这个答案的变体(它利用了重塑(。对这两种方法进行计时,后者的速度大约快了 8 倍(至少通过我的测试(。

> Einops 允许详细缩减。在您的情况下

import numpy as np
from einops import reduce
# Black / white image
image = np.random.rand(16, 16) < 0.5
# compute number of bright pixels in each block, then compute residual modulo 2
reduce(image, '(h h2) (w w2) -> h w', 'sum', h2=4, w2=4) % 2

示例输出:

array([[0, 0, 1, 1],
[1, 1, 0, 1],
[1, 0, 1, 1],
[0, 0, 1, 1]])

最新更新