Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Numpy reranging chararray

How can one rerange chararrays without getting a 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[::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

Tried the exact same code with numbers instead of chars and it worked fine. Thank you.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You need to use a numpy array for bggr:

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)

output:

[[['' '' 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' '' '']]]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading