I am working with tracking elements video using opencv
(basically counting number of elements after hsv thresholding). I have a deque
buffer to store centroid positions. I chose a limited buffer of 64 (~2 seconds on 30 fps, could be longer). My goal is to save the data into .csv
file in such a format that I can readily use later (see below). Additionally, I am counting the number of detected regions. The format would be like
cX cY number
444 265 19
444 265 19
444 264 19
444 264 19
...
With cX
being the centroid in X and cY
the centroid in Y of the largest element, and the number of detected regions. Column naming is not the main goal although it would be nice.
For display purposes, I need to have the centroid as tuple
. I make them grow frame by frame using 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)
Now, when the buffer is full, I want to save the data into file):
# 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
Problem
The code above works and writes something that looks like this:
(444 265) 19
(444 265) 19
(444 264) 19
(444 263) 19
I would like to do something like np.array(center_points)
and bind that to object_number
. I have had trouble with dimensions (e.g, (64,2) and (64) not being compatible). I have tried np.append
and np.stack
but can't find the correct way of formatting the data.
Else, I could keep the code as is but I would like to somehow get rid of the parenthesis on columns 1 and 2 and save that object instead (have tried regular expressions on array_to_save
without success). All three columns should be numeric or saved as string but easily retrieved as numeric later in reading.
Update
Based on comments I tried
array_to_save = np.concatenate([np.array(center_points), object_number[:, None]])
TypeError: sequence index must be integer, not 'tuple'
I also tried
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