1

I had expected the following to create a new numpy array from the shape of an existing array but with modified element data type. My original array is an image with 8bit RGB pixels. I want to create a new array using same shape but with uint16 data type. The purpose is then to convert the image into 16bit pixels and perform some math. To my surprise the following didn't work.

>>> import scipy.misc        as msc
>>> import numpy             as np
>>> img_rgb = msc.imread('Jupiter_20160417_53.png')
>>> img_rgb.dtype
dtype('uint8')
>>> img_rgb.shape
(480, 640, 3)
>>> new= np.zeros(img_rgb.shape,dtype=uint16)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'uint16' is not defined

What did I miss?

Thanks, Gert

1
  • >>> a = np.zeros((3,3),dtype=np.uint16) works for me (import numpy as np of course) Commented Jun 12, 2016 at 6:28

1 Answer 1

1

The np.:

In [2]: np.zeros((3,4),dtype=np.uint16)
Out[2]: 
array([[0, 0, 0, 0],
       [0, 0, 0, 0],
       [0, 0, 0, 0]], dtype=uint16)

'uint16' (the string) would have worked as well.

int and float are Python names; almost all the other dtypes are numpy specific, and require either the np. namespace or a string name (which numpy understands).

The error NameError: name 'uint16' is not defined means that uint16 is not a variable in the main namespace. In other words it's not a builtin variable (or function), and it hasn't been imported as such. It is part of the numpy namespace which you imported a np.

e.g.

In [8]: z
...
NameError: name 'z' is not defined
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you hpaulj. The 'np.' prefix worked. What is the better code style? np.zeros((3,4),dtype='uint16') or np.zeros((3,4),dtype=np.uint16) ?
I don't think it matters. More details here: docs.scipy.org/doc/numpy-1.10.0/reference/arrays.scalars.html
I wonder why it doesn't it work for me, np.uint8 does, but on np.uint16 CV throws an exception that Assertion failed in cvShowImage

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.