愚蠢的重设范围的字符阵列



如何在不得到TypeError的情况下重新设置字符数组的范围。

import numpy as np

bggr =   ([['B', 'G', 'B', 'G'],
['G', 'R', 'G', 'R'],
['B', 'G', 'B', 'G'],
['G', 'R', 'G', 'R']])


test = np.chararray((4, 4, 3)) #create empty chararray
test[:] = ''
test[::2, ::2, 2]=bggr[0::2, 0::2] #blue
test[1::2, ::2, 1]=bggr[1::2, 0::2] #green
test[::2, 1::2, 1]=bggr[0::2, 1::2] #green
test[1::2, 1::2, 0]=bggr[1::2, 1::2] #red
print(test)

Traceback (most recent call last):
File "main.py", line 16, in <module>
test[::2, ::2, 2]=bggr[0::2, 0::2] #blue
TypeError: list indices must be integers or slices, not tuple

用数字而不是字符尝试了完全相同的代码,效果很好。非常感谢。

您需要为bggr:使用numpy数组

import numpy as np

bggr = np.array([['B', 'G', 'B', 'G'],
['G', 'R', 'G', 'R'],
['B', 'G', 'B', 'G'],
['G', 'R', 'G', 'R']])

test = np.chararray((4, 4, 3)) #create empty chararray
test[::2, ::2, 2]=bggr[0::2, 0::2] #blue
test[1::2, ::2, 1]=bggr[1::2, 0::2] #green
test[::2, 1::2, 1]=bggr[0::2, 1::2] #green
test[1::2, 1::2, 0]=bggr[1::2, 1::2] #red
print(test)

输出:

[[['' '' b'B']
['' b'G' '']
['' '' b'B']
['' b'G' '']]
[['' b'G' '']
[b'R' b'x04' '']
['' b'G' '']
[b'R' '' '']]
[[b'x06' '' b'B']
['' b'G' '']
['' '' b'B']
['' b'G' '']]
[['' b'G' '']
[b'R' '' '']
['' b'G' '']
[b'R' '' '']]]

最新更新