gpt4 book ai didi

python - 在python中获取棋盘图案中的像素值

转载 作者:行者123 更新时间:2023-12-01 06:12:13 25 4
gpt4 key购买 nike

我有一个黑白图像,每个像素值都作为 numpy (2948x1536) 的嵌套列表加载。我需要做的是从棋盘图案的列表中获取像素。所以我需要像这样提取像素:

0 1 0 1 0 1 0 1
1 0 1 0 1 0 1 0
0 1 0 1 0 1 0 1
....

这将如何完成?使用嵌套列表来完成这样的工作是个好主意吗?如果没有,你有什么建议?

图像处理对我来说很新鲜。

任何帮助将不胜感激,

最佳答案

让我们使用较小的尺寸,以便更容易看到结果:

import numpy as np
# w=2948
# h=1536
w=6
h=4
arr=np.arange(w*h).reshape(w,h)
print(arr)
print(arr.shape)
# [[ 0 1 2 3]
# [ 4 5 6 7]
# [ 8 9 10 11]
# [12 13 14 15]
# [16 17 18 19]
# [20 21 22 23]]
# (6, 4)

我们可以以棋盘模式构造一个 bool 数组:

coords=np.ogrid[0:w,0:h]
idx=(coords[0]+coords[1])%2 == 1
print(idx)
print(idx.shape)
# [[False True False True]
# [ True False True False]
# [False True False True]
# [ True False True False]
# [False True False True]
# [ True False True False]]
# (6, 4)

使用这个boolean array for indexing ,我们可以提取我们想要的值:

checkerboard=arr[idx].reshape(w,h//2)
print(checkerboard)
print(checkerboard.shape)
# [[ 1 3]
# [ 4 6]
# [ 9 11]
# [12 14]
# [17 19]
# [20 22]]
# (6, 2)
PS。这个答案的灵感来自 Ned Batchelder 的回答 here .

关于python - 在python中获取棋盘图案中的像素值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5198116/

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