我想创建一个csv文件,当我进入python shell窗口时,该文件应具有每个对象的坐标。
import cv2
import pandas as pd
# capture frames from a video
cap = cv2.VideoCapture('video.avi')
# Trained XML classifiers describes some features of some object we want
to detect
car_cascade = cv2.CascadeClassifier('cars.xml')
no_obj_det=0
frames_got_processed = 0
frame_processed = []
number_of_object_detected= []
# loop runs if capturing has been initialized.
while True:
# reads frames from a video
try:
ret, frames = cap.read()
frames_got_processed += 1
# convert to gray scale of each frames
gray = cv2.cvtColor(frames, cv2.COLOR_BGR2GRAY)
# Detects cars of different sizes in the input image
cars = car_cascade.detectMultiScale(gray, 1.1, 1)
# To draw a rectangle in each cars
for (x,y,w,h) in cars:
cv2.rectangle(frames,(x,y),(x+w,y+h),(0,0,255),2)
cv2.imshow('video2', frames)
if cv2.waitKey(33) == 27:
break
# loop to count the number of objects detected at every 5th frame
if frames_got_processed % 5 == 0:
print "appended in frame
number",frames_got_processed,len(cars),cars
frame_processed.append(frames_got_processed)
number_of_object_detected.append(len(cars))
df.to_csv('example.csv')
# De-allocate any associated memory usage
cv2.destroyAllWindows()
在python shell上输出我想要在csv文件中的相同输出 [1]:https://i.stack.imgur.com/vfPEP.png
答案 0 :(得分:0)
由于您可能需要连续向CSV写入数据,因此最好在执行时进行此操作,而不是尝试附加所有数据然后将其写入末尾。这样可以避免最终耗尽内存。
Python csv
库可用于执行以下操作:
import cv2
import csv
# capture frames from a video
cap = cv2.VideoCapture('video.avi')
# Trained XML classifiers describes some features of some object we want to detect
car_cascade = cv2.CascadeClassifier('cars.xml')
frames_got_processed = 0
with open('example.csv', 'w', newline='') as f_output:
csv_output = csv.writer(f_output)
# loop runs if capturing has been initialized.
while True:
# reads frames from a video
try:
ret, frames = cap.read()
frames_got_processed += 1
# convert to gray scale of each frames
gray = cv2.cvtColor(frames, cv2.COLOR_BGR2GRAY)
# Detects cars of different sizes in the input image
cars = car_cascade.detectMultiScale(gray, 1.1, 1)
# To draw a rectangle in each cars
for (x,y,w,h) in cars:
cv2.rectangle(frames,(x,y),(x+w,y+h),(0,0,255),2)
cv2.imshow('video2', frames)
if cv2.waitKey(33) == 27:
break
# loop to count the number of objects detected at every 5th frame
if frames_got_processed % 5 == 0:
print "appended in frame number", frames_got_processed, len(cars), cars
csv_output.writerow([frames_got_processed, len(cars)] + list(cars))
except:
pass
# De-allocate any associated memory usage
cv2.destroyAllWindows()
这应该给您一行,其中包含车架号,汽车数量,以及每辆汽车的坐标。