简体   繁体   中英

How to return empty numpy array as np.ndarray([[[]]])

I have a program that retrieves image and return the RGB image as 3D np.ndarray . I want to return np.ndarray([[[]]]) when image is not available.

Can we do it?

Use numpy.empty

Which returns a new array of given shape and type, without initializing entries.

import numpy as np
empty_array = np.empty((1, 1, 1))
empty_array
array([[[5.e-324]]])

OR

import numpy as np
empty_array = np.empty((1, 1, 0))
empty_array
array([], shape=(1, 1, 0), dtype=float64)

which is basically

np.array([[[]]])

DOCS for more help

simply return np.empty((10,10,10),object) because x=np.empty((10,10,10)) returns array with random values already stored in the memory buffer. x=np.empty((10,10,10),object) will return array with none values.

Here (10,10,10) dimension is just for example. Use the dimensions favourable for you.

It's easy to make such an array:

In [128]: arr = np.array([[[]]])                                                                     
In [129]: arr                                                                                        
Out[129]: array([], shape=(1, 1, 0), dtype=float64)

You could also use np.zeros((1,1,0)) (or empty ); but it's no easier than [128].

But how are you going to use or test this? I suppose you could check:

In [130]: arr.nbytes                                                                                 
Out[130]: 0

I believe one of the image packages ( cv2 ?) returns None if it can't load the image. Testing for None is easy, reliable, and widely used in python.

In [131]: arr = None                                                                                 
In [132]: arr is None                                                                                
Out[132]: True

It might make more sent to use a 'image' with 0 size, but still the full 3 color channels, np.zeros((0,0,3), np.int8) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM