简体   繁体   English

如何将空 numpy 数组返回为 np.ndarray([[[]]])

[英]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 .我有一个程序可以检索图像并将 RGB 图像返回为 3D np.ndarray I want to return np.ndarray([[[]]]) when image is not available.当图像不可用时,我想返回np.ndarray([[[]]])

Can we do it?我们能做到吗?

Use numpy.empty使用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.只需返回np.empty((10,10,10),object)因为x=np.empty((10,10,10))返回数组,其中随机值已存储在 memory 缓冲区中。 x=np.empty((10,10,10),object) will return array with none values. x=np.empty((10,10,10),object)将返回none值的数组。

Here (10,10,10) dimension is just for example.这里 (10,10,10) 维度只是一个例子。 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 );您也可以使用np.zeros((1,1,0)) (或empty ); but it's no easier than [128].但这并不比 [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.我相信其中一个图像包( cv2 ?)如果无法加载图像,则返回None Testing for None is easy, reliable, and widely used in python.在 python 中测试None简单、可靠且广泛使用。

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) .使用 0 尺寸的“图像”可能会发送更多信息,但仍然是完整的 3 个颜色通道np.zeros((0,0,3), np.int8)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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