python - 将双端队列保存到 csv 数据框中
问题描述
我正在使用跟踪元素视频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
但没有成功)。所有三列都应该是数字或保存为字符串,但稍后在阅读时可以轻松地检索为数字。
更新
根据我尝试过的评论
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
解决方案
您可以concatenate
沿列维度排列数组,以便(X, 3)
从(X, 2)
and数组中创建一个(X,)
数组。为了准备好连接,所有数组都需要具有相同的维数,因此您需要向平面数组添加一个额外的维数object_number
:(X,) -> (X, 1)
。这可以通过object_number[:, np.newaxis]
或完成object_number[:, None]
。那么完整的解决方案是:
np.concatenate([np.array(center_points),
np.array(object_number)[:, None]], axis=-1)
推荐阅读
- python - 正则表达式查找数字的前 5 位数字和后 2 位数字必须在 URL 中指定
- css - 如何使用引导程序以不同的顺序从 1 列到 3 个不同的列排序 div
- c# - VS 2019 Winform 项目和 SQLite 错误:无法加载 DLL 'SQLite.Interop.dll':找不到指定的模块
- angular - 如何解决角度中的“类型对象中不存在属性”错误?
- java - 如何在 Springboot 应用程序中实现非 Springboot 实用程序?
- angular - Angular 9 - 事件发射器不发射
- python - Pandas:使用 For 循环遍历已经按排序顺序排列的列的唯一值
- php - 如何仅显示列内的值并显示它(PHP & MySQL)
- html - 需要一个 div,其中有 2 个左右浮动的图像和 btwn 中的文本,它们要放置在 div 的确切中心
- ansible - 如何在 Ansible 服务器列表上设置组件名称