python - 如何将输出写入csv
问题描述
我有一个使用 Yolo 用 Python 编写的自定义对象检测代码。我想将一些输出值,如 image_name、detected_object_label、box_co-ordinate 值、置信度百分比写入 2 个 csv 文件。1个csv应该有image_name、detected_object_label、置信百分比,另一个应该有image_name、detected_object_label、box_co-ordinate值
到目前为止,我已经编写了自定义对象检测的代码。
import cv2
import glob
from glob import glob
import os
import shutil
import numpy as np
import argparse
import imutils
from keras.preprocessing.image import img_to_array
from keras.models import load_model
#import tensorflow as tf
from PIL import Image
import json
import sys
import csv
#from utils import label_map_util
#from utils import visualization_utils as vis_util
from os.path import isfile,join
import pandas as pd
########################################## EXTRACT FRAMES FROM VIDEO###########################
def extractFrames(m):
global vid_name
global img_name
vid_files=glob(m)
complete_videos = get_completed_videos()
new_vid_files = [x for x in vid_files if get_vid_name(x) not in complete_videos]
for vid in new_vid_files:
print("path of video========>>>>.",vid)
v1 = os.path.basename(vid)
try:
vid_name = get_vid_name(vid)
vidcap = cv2.VideoCapture(vid)
except cv2.error as e:
print(e)
except:
print('error')
fsize = os.stat(vid)
print('=============size of video ===================:' , fsize.st_size)
try:
if ( fsize.st_size > 1000 ):
fps = vidcap.get(cv2.CAP_PROP_FPS) # OpenCV2 version 2 used "CV_CAP_PROP_FPS"
frameCount = int(vidcap.get(cv2.CAP_PROP_FRAME_COUNT))
duration = frameCount/fps
minutes = int(duration/60)
print('fps = ' + str(fps))
print('number of frames = ' + str(frameCount))
print('duration (S) = ' + str(duration))
if (duration <= 5):
success,image = vidcap.read()
count=0
success=True
while success:
img_name = vid_name + '_f' + str(count) + ".jpg"
success,image = vidcap.read()
if count % 10 == 0 or count ==0:
target_non_target(img_name, image)
count+=1
vidcap.release()
cv2.destroyAllWindows()
elif (duration > 5 and duration <= 10):
success,image = vidcap.read()
count = 0
success = True
while success:
img_name = vid_name + '_f' + str(count) + ".jpg"
success,image = vidcap.read()
if count%20 == 0 or count == 0:
target_non_target(img_name,image)
count+=1
vidcap.release()
cv2.destroyAllWindows()
elif (duration > 10 and duration <= 20):
success,image = vidcap.read()
count = 0
success = True
while success:
img_name = vid_name + '_f' + str(count) + ".jpg"
success,image = vidcap.read()
if count%30 == 0 or count == 0:
target_non_target(img_name,image)
count+=1
vidcap.release()
cv2.destroyAllWindows()
elif (duration > 20 and duration <= 100):
success,image = vidcap.read()
count = 0
success = True
while success:
img_name = vid_name + '_f' + str(count) + ".jpg"
success,image = vidcap.read()
if count%50 == 0 or count == 0:
target_non_target(img_name,image)
count+=1
vidcap.release()
cv2.destroyAllWindows()
elif (duration > 100 and duration <= 300):
success,image = vidcap.read()
count = 0
success = True
while success:
img_name = vid_name + '_f' + str(count) + ".jpg"
success,image = vidcap.read()
if count%100 == 0 or count == 0:
target_non_target(img_name,image)
count+=1
vidcap.release()
cv2.destroyAllWindows()
elif (duration > 300 and duration <= 600):
success,image = vidcap.read()
count = 0
success = True
while success:
img_name = vid_name + '_f' + str(count) + ".jpg"
success,image = vidcap.read()
if count%150 == 0 or count == 0:
target_non_target(img_name,image)
count+=1
vidcap.release()
cv2.destroyAllWindows()
elif (duration > 600 and duration <= 900):
success,image = vidcap.read()
count = 0
success = True
while success:
img_name = vid_name + '_f' + str(count) + ".jpg"
success,image = vidcap.read()
if count%300 == 0 or count == 0:
target_non_target(img_name,image)
count+=1
vidcap.release()
cv2.destroyAllWindows()
elif (duration > 900 and duration <= 1200):
success,image = vidcap.read()
count = 0
success = True
while success:
img_name = vid_name + '_f' + str(count) + ".jpg"
success,image = vidcap.read()
if count%600 == 0 or count == 0:
target_non_target(img_name,image)
count+=1
vidcap.release()
cv2.destroyAllWindows()
elif (duration > 1200 and duration <= 1800):
success,image = vidcap.read()
count = 0
success = True
while success:
img_name = vid_name + '_f' + str(count) + ".jpg"
success,image = vidcap.read()
if count%900 == 0 or count == 0:
target_non_target(img_name,image)
count+=1
vidcap.release()
cv2.destroyAllWindows()
elif (duration > 1800 and duration <= 3600):
success,image = vidcap.read()
count = 0
success = True
while success:
img_name = vid_name + '_f' + str(count) + ".jpg"
success,image = vidcap.read()
if count%1200 == 0 or count == 0:
target_non_target(img_name,image)
count+=1
vidcap.release()
cv2.destroyAllWindows()
elif (duration > 3600 and duration <= 7200):
success,image = vidcap.read()
count = 0
success = True
while success:
img_name = vid_name + '_f' + str(count) + ".jpg"
success,image = vidcap.read()
if count%1500 == 0 or count == 0:
target_non_target(img_name,image)
count+=1
vidcap.release()
cv2.destroyAllWindows()
elif (duration > 7200 and duration <= 10800):
success,image = vidcap.read()
count = 0
success = True
while success:
img_name = vid_name + '_f' + str(count) + ".jpg"
success,image = vidcap.read()
if count%2000 == 0 or count == 0:
target_non_target(img_name,image)
count+=1
vidcap.release()
cv2.destroyAllWindows()
elif (duration > 10800):
success,image = vidcap.read()
count = 0
success = True
while success:
img_name = vid_name + '_f' + str(count) + ".jpg"
success,image = vidcap.read()
if count%2500 == 0 or count == 0:
target_non_target(img_name,image)
count+=1
vidcap.release()
cv2.destroyAllWindows()
else:
print("video length exceeds max limit")
except:
print("error")
print('finished processing video ', vid)
with open('C:\\Python35\\target_non_target\\'+'video_info.csv', 'a') as csv_file:
fieldnames = ['Video_Name','Process']
file_is_empty = os.stat('C:\\Python35\\target_non_target\\'+'video_info.csv').st_size == 0
writer = csv.DictWriter(csv_file, fieldnames=fieldnames)
if file_is_empty:
writer.writeheader()
writer.writerow({'Video_Name':vid_name,'Process':'done'})
#print('finished processing video {0} with frames {1}'.format(vid_files[v_f], count))
def get_vid_name(vid):
return os.path.splitext(os.path.basename(vid))[0]
def get_completed_videos():
completed_videos = []
with open("C:\\Python35\\target_non_target\\video_info.csv") as csv_file:
for row in csv.reader(csv_file):
for col in range(0,len(row)):
try:
completed_videos.append(row[col])
except Exception as e:
print(str(e))
print(completed_videos[0])
return completed_videos
###########################CHECK FOR TARGET IMAGES FROM FRAMES###########################
def target_non_target(img_name, image):
try:
image_re = cv2.resize(image, (28, 28))
image_fl = image_re.astype("float") / 255.0
image_arr = img_to_array(image_fl)
image_expanded = np.expand_dims(image_arr, axis=0)
model_file = "C:\\Python35\\target_non_target\\target_non_target.model"
model = load_model(model_file)
(non_target, target) = model.predict(image_expanded)[0]
if target > non_target:
print("[INFO] Target DETECTED...")
#recognize_object(image)
draw_pred(image, class_ids[i], confidences[i], round(x), round(y), round(x + w), round(y + h))
else:
print("[INFO] NON TARGET...")
except Exception as e:
print(str(e))
#################################OBJECT RECOGNITION MODEL CODE################################
#def recognize_object(image):
yolo_cfg = "C:\\Python35\\custom_yolo_object_detector\\darknet\\custom\\yolov3-tiny.cfg"
weights = "C:\\Python35\\custom_yolo_object_detector\\darknet\\custom\\yolov3-tiny_final.weights"
class_names = "C:\\Python35\\custom_yolo_object_detector\\darknet\\custom\\objects.names"
def getOutputsNames(net):
layersNames = net.getLayerNames()
return [layersNames[i[0] - 1] for i in net.getUnconnectedOutLayers()]
def draw_pred(image, class_id, confidence, x, y, x_plus_w, y_plus_h):
label = str(classes[class_id])
color = COLORS[class_id]
cv2.rectangle(img, (x,y), (x_plus_w,y_plus_h), color, 2)
cv2.putText(img, label, (x-10,y-10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, color, 2)
classes = None
with open(class_names, 'r') as f:
classes = [line.strip() for line in f.readlines()]
print(classes)
COLORS = np.random.uniform(0, 255, size=(len(classes), 3))
net = cv2.dnn.readNet(weights,yolo_cfg)
image=cv2.resize(image, (299, 299))
blob = cv2.dnn.blobFromImage(image, 1.0/255.0, (299,299), [0,0,0], True, crop=False)
Width = image.shape[1]
Height = image.shape[0]
net.setInput(blob)
outs = net.forward(getOutputsNames(net))
class_ids = []
confidences = []
boxes = []
conf_threshold = 0.5
nms_threshold = 0.4
for out in outs:
for detection in out:
scores = detection[5:]
class_id = np.argmax(scores)
confidence = scores[class_id]
if confidence > 0.5:
center_x = int(detection[0] * Width)
center_y = int(detection[1] * Height)
w = int(detection[2] * Width)
h = int(detection[3] * Height)
x = center_x - w / 2
y = center_y - h / 2
class_ids.append(class_id)
confidences.append(float(confidence))
boxes.append([x, y, w, h])
indices = cv2.dnn.NMSBoxes(boxes, confidences, conf_threshold, nms_threshold)
for i in indices:
i = i[0]
box = boxes[i]
x = box[0]
y = box[1]
w = box[2]
h = box[3]
#draw_pred(obj_img, class_ids[i], confidences[i], round(x), round(y), round(x+w), round(y+h))
cv2.putText(image, label, (0, 15), cv2.FONT_HERSHEY_SIMPLEX, .6, (255, 0, 0))
cv2.imshow(image)
if __name__ == "__main__":
x="C:\\Python36\\videos\\*.mp4"
extractFrames(x)
解决方案
你可以将你的值传递给这个函数
def writeToCSV(value1,value2,value3...):
with open('new.csv', 'a') as writeFile:
writer = csv.writer(writeFile)
for i in range(len(result)):
writer.writerow(result)
推荐阅读
- python - Python多线程通信效率
- python - 将 txt 文件数据加载到 numpy 数组中/出现错误
- java - 将 ParseInt() 与 JTextField.getText() 一起使用会引发错误
- typescript - Typescript Type Guards 和粗箭头函数
- python - Matplotlib 的 get_ticklabels 不适用于自定义字符串标签
- angular - 如何使用 Angular 6 中的发布请求下载大文件
- url - 安装 Drupal 的 URL
- angularjs - 为什么 Chrome DevTools 不显示对象的所有属性?
- javascript - 角度 4 - 以分钟为单位的可观察计时器
- sql-server - 在每一页上重复静态 Tablix