首页 > 解决方案 > 将numpy数组转换为字符串

问题描述

我有一个 numpy 数组。 print(numpy_array[1])给出一个输出['path/to/file.jpg']

我想使用cv.imread(numpy_array[1]),但是当我这样做时,我得到了错误:

 Can't convert object of type 'numpy.ndarray' to 'str' for 'filename'

标签: pythonarrayspython-3.xnumpyopencv

解决方案


['path/to/file.jpg']是一个列表。您想要的可能是'path/to/file.jpg',这是此列表的第一个元素:['path/to/file.jpg'][0].

对于您的 CV 电话,请尝试cv.imread(numpy_array[1][0]).


或者,正如 nagyl 所建议的,您可以展平您的阵列。这是一个例子

>>> a = np.array([["path"],["file"]])
>>> a.flatten()
array(['path', 'file'], dtype='<U4')

推荐阅读