getting pixels value in a checkerboard pattern in python
I have a black and white image which every pixel values are loaded as a nested list with numpy (2948x1536). What i need to do is to grab the pixels from that list in a checkerboard pattern. So I need to extract pixels like this :
0 1 0 1 0 1 0 1
1 0 1 0 1 0 1 0 0 1 0 1 0 1 0 1 ....How would this be done ? Is thi开发者_JAVA百科s a good idea to use a nested list for such a job ? If not, what would you suggest ?
Image processing is quite new to me.
Any help would be greatly appreciated,
Let's use smaller dimensions so the result is easier to see:
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)
We can construct a boolean array in a checkerboard pattern:
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)
Using this boolean array for indexing, we can extract the values we desire:
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. Inspiration for this answer came from Ned Batchelder's answer here.
imgdat = ... #your 2948x1536 nested list
checker1 = [r[i%2::2] for i,r in enumerate(imgdat)]
checker2 = [r[(i+1)%2::2] for i,r in enumerate(imgdat)]
 
         加载中,请稍侯......
 加载中,请稍侯......
      
精彩评论