Dia*_*nto 2 python opencv image 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
Run Code Online (Sandbox Code Playgroud)
在这个问题的解决方案的帮助下,将 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))
Run Code Online (Sandbox Code Playgroud)
16x16图像的输出示例:
[[0 1 1 0]
[0 0 1 0]
[1 1 1 1]
[0 0 0 1]]
Run Code Online (Sandbox Code Playgroud)
编辑:
该block_view()函数最初是在这个答案(使用as_strided())之后实现的,但是经过更多的搜索,我决定使用这个答案的变体(使用重塑).对两种方法进行定时,后者的速度提高了约8倍(至少通过我的测试).