【发布时间】:2019-01-14 00:02:22
【问题描述】:
我正在使用opencv 处理跟踪元素视频(基本上计算 hsv 阈值后的元素数量)。我有一个deque 缓冲区来存储质心位置。我选择了 64 的有限缓冲区(在 30 fps 上约 2 秒,可能更长)。我的目标是将数据保存到.csv 文件中,以方便我以后使用(见下文)。此外,我正在计算检测到的区域的数量。格式是这样的
cX cY number
444 265 19
444 265 19
444 264 19
444 264 19
...
cX 是 X 中的质心,cY 是 Y 中最大元素的质心,以及检测到的区域数。列命名不是主要目标,尽管它会很好。
出于显示目的,我需要将质心设为tuple。我使用appendleft 让它们逐帧增长:
center_points = deque(maxlen=64)
object_number = deque(maxlen=64)
iteration_counter = 1
while True
# read video frames..
# do stuff...
# get contours
my_cnts = cv2.findContours(...)
# get largest object
c = max(my_cnts, key=cv2.contourArea)
((x, y), radius) = cv2.minEnclosingCircle(c)
M = cv2.moments(c)
big_center = (int(M["m10"] / M["m00"]), int(M["m01"] / M["m00"]))
# count object number as int name it 'num'
center_points.appendleft(big_center)
object_number.appendleft(num)
现在,当缓冲区已满时,我想将数据保存到文件中):
# Convert to array to save
# Wait until the iteration number is divisible by the buffer length
if(iteration_number % 64 == 0):
print("Saving on iteration..." + str(iteration_number))
array_to_save = np.array([center_points, object_number]).T
with open(filename,'a') as outfile:
np.savetxt(outfile, array_to_save,
delimiter=',', fmt='%s')
# Add 1 to the counter
iteration_number = iteration_number + 1
问题
上面的代码工作并编写了如下所示的内容:
(444 265) 19
(444 265) 19
(444 264) 19
(444 263) 19
我想做类似np.array(center_points) 的操作并将其绑定到object_number。我遇到了尺寸问题(例如,(64,2)和(64)不兼容)。我尝试过np.append 和np.stack,但找不到正确的数据格式化方式。
否则,我可以保持代码不变,但我想以某种方式摆脱第 1 列和第 2 列上的括号并保存该对象(已在 array_to_save 上尝试过正则表达式但没有成功)。所有三列都应该是数字或保存为字符串,但在以后阅读时很容易检索为数字。
更新
基于我尝试过的 cmets
array_to_save = np.concatenate([np.array(center_points), object_number[:, None]])
TypeError: sequence index must be integer, not 'tuple'
我也试过
array_to_save = np.concatenate([np.array(center_points), np.array(object_number)[:, None]])
ValueError: all the input array dimensions except for the concatenation axis must match exactly
【问题讨论】:
-
您可以使用
np.concatenate(x, y[:, None]),即添加额外的列维度以具有(64, 2)和(64, 1),然后您可以连接。 -
@a_guest 这不起作用我运行正确吗?
array_to_save = np.concatenate(np.array(center_points), object_number[:, None]) TypeError: sequence index must be integer, not 'tuple' -
您需要将参数包含在一个额外的序列中,即
np.concatenate([np.array(center_points), object_number[:, None]])。 -
@a_guest 请查看更新。
-
看来
object_number没有center_points那么多项目。无论如何,一般规则是沿着公共轴,在我们的例子中这是0-th轴,要连接的两个数组需要具有相同的长度。您可以通过.shape查看每个维度的长度。 IE。执行c = np.array(center_points); o = np.array(object_number)[:, None],然后检查c.shape和o.shape。由于shape[0]是公共轴,因此它必须是相同的编号。例如c.shape == (60, 2); o.shape == (60, 1)可以,c.shape == (60, 2); o.shape == (58, 1)不行。
标签: python regex deque saving-data