【问题标题】:How to convert a contour list into a numpy array?如何将轮廓列表转换为 numpy 数组?
【发布时间】:2017-05-30 09:43:11
【问题描述】:

在这段代码中,我想将所有轮廓保存在一个.h5 文件中。但这只有在我将轮廓转换为 numpy 数组时才有可能。

import numpy as np
import h5py
import cv2

thresh,contours,hierarchy = cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
contours = sorted(contours, key = cv2.contourArea, reverse = False)[40:50]
l = len(contours)
cnts = []

for i,contour in enumerate(contours):
    contour = np.array(contour,dtype = np.int32)
    cnts.append(contour)

cnts = np.array(cnts).astype('int32')
directory = 'Hist_defects'
os.makedirs(directory,exist_ok = True)
h = h5py.File('Hist_defects/'+str(k)+'.h5') 
h.create_dataset('dataset_1',data=cnts)
h.close()

运行此程序时出现以下错误。

cnts = np.array(cnts).astype('int32')
ValueError: setting an array element with a sequence.

这种转换可能吗?

【问题讨论】:

  • 由于contour 是一个数组而不是int32,请尝试将cnts = np.array(cnts).astype('int32') 替换为cnts = np.array(cnts).astype('object')
  • 我认为代码不正确,我从未听说过np.acnts。如果您在问题中真正显示您的contours,会更容易。这样就可以轻松地重现代码。
  • @MSeifert 这是一个错字。我现在已经更正了
  • @AtulBalaji 轮廓呢?它们应该只有 10 个元素长。您能否在问题中包含该列表?
  • @Nuageux 现在我收到另一个错误:

标签: python arrays opencv numpy


【解决方案1】:

当您的contours 中的元素长度不相等时会发生错误:

>>> import numpy as np

>>> contours = [[1, 2, 3], [1, 2]]  # not equal lengths
>>> cnts = []

>>> for contour in contours:
...     cnts.append(np.array(contour, dtype=np.int32))

>>> cnts = np.array(cnts).astype('int32')
ValueError: setting an array element with a sequence.

那是因为 NumPy 不支持 "ragged arrays"。您可以用其他值填充较短的值,然后保存它们。

>>> contours = [[1, 2, 3], [1, 2]]

>>> maxlength = max(map(len, contours))

>>> cnts = []
>>> for contour in contours:
...     contour_arr = np.zeros(maxlength, dtype=np.int32)
...     contour_arr[:len(contour)] = contour
...     cnts.append(contour_arr)

>>> np.array(cnts)
array([[1, 2, 3],
       [1, 2, 0]])

除了np.zeros,您还可以使用np.full 选择另一个“缺失值”。

如果contours 是多维的,那就有点复杂了。但在这种情况下,您也可以使用np.pad

【讨论】:

  • 我收到以下错误:Traceback (most recent call last): File "hotspot_hist.py", line 55, in <module> maxlength = max(map(len, contours)) ValueError: max() arg is an empty sequence
  • 请出示您的contours,答案包含您解决问题所需的所有信息。如果您需要更多帮助必须 分享您的数据。否则无法为您提供更多帮助。
  • 当我给print(contours)时,它打印出一长串这样的点并给出以下错误:[[616, 589]], [[615, 588]], [[609 , 588]], [[608, 587]], [[605, 587]], [[604, 586]]], dtype=int32)] 回溯(最近一次调用最后):文件“hotspot_hist.py”,第 61 行,在 contour_arr[:len(contour)] = contour ValueError: could not broadcast input array from shape (21,1,2) into shape (21)
  • @AtulBalaji 如果您使用np.zeros((maxlength, 1, 2), dtype=np.int32),您能否检查该解决方案是否有效?而不是我在答案中的np.zeros 电话。
  • 由于我已经将一些轮廓设为零,所以当我绘制轮廓时,总是包含左上角。我如何排除这一点? @MSeifert
猜你喜欢
  • 2021-06-09
  • 2020-09-18
  • 2017-03-08
  • 2015-02-15
  • 2014-06-26
  • 2019-08-30
  • 2015-01-07
  • 2022-10-15
相关资源
最近更新 更多