gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 21:16:08 26 4
gpt4 key购买 nike

我有一个二值图像,我想将其分成 4 x 4 像素的 block ,并计算 block 中黑色像素的数量。如果 block 中的黑色像素之和为偶数,则相应 block 的值为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

最佳答案

the solution provided to this question 的帮助下关于将二维数组拆分成更小的 block :

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 的变体。相反(它利用 reshape )。对这两种方法进行计时,后者大约快 8 倍(至少通过我的测试)。

关于python - 将二进制图像划分为 4x4 Python 并计算像素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50442597/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com