【发布时间】: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