【问题标题】:Turn numpy array into a string将numpy数组转换为字符串
【发布时间】:2021-04-26 22:08:53
【问题描述】:

我有一个 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'

【问题讨论】:

  • ['path/to/file.jpg'] 不是另一个列表吗?如果是,请尝试将其也编入索引。
  • numpy_array = [['path/to/file.jpg'] ['path/to/file2.jpg'] ['path/to/file3.jpg']]
  • 在这种情况下,您也需要进入 nesed 列表。使用cv.imread(numpy_array[1][0]) 或者不使用嵌套列表
  • @Gedaz 那么它是一个数组数组。通过执行numpy_array = ['path/to/file.jpg', 'path/to/file2.jpg', 'path/to/file3.jpg'] 或索引numpy_array[1][0] 将它们更改为字符串。我建议做第一个,不需要额外的数组,因此让你的简单代码更复杂。下次请发布您的整个代码!

标签: python arrays python-3.x numpy opencv


【解决方案1】:

你有一个 2D 列表,意味着 numpy_array[1] 不是一个字符串,而是一个列表,并且在该列表内有一个字符串,所以使用 numpy_array[1, 0] 来获取其中的字符串,或者删除使用 numpy.squeeze(numpy_array) 的额外维度,然后使用 numpy_array[1] 将起作用。

cv.imread(numpy_array[1, 0])

numpy_array = numpy.squeeze(numpy_array)
cv.imread(numpy_array[1])

【讨论】:

    【解决方案2】:

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

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


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

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

    【讨论】:

    • 不需要额外的列表。至少,请考虑建议将嵌套列表更改为扁平列表。
    猜你喜欢
    • 2013-05-05
    • 2016-03-10
    • 2015-03-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-24
    • 2016-03-24
    • 1970-01-01
    相关资源
    最近更新 更多