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

时间:2018-05-21 05:40:38

标签: python image opencv image-processing python-imaging-library

我有一个二进制图像,我想分成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

2 个答案:

答案 0 :(得分:6)

the solution provided to this question的帮助下,将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()函数最初是在this answer之后实现的(使用as_strided()),但经过更多搜索,我决定使用this answer的变体(利用重塑)。对两种方法进行定时,后者的速度提高了约8倍(至少通过我的测试)。

答案 1 :(得分:0)

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]])