You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

修改实时人数统计代码后Log.csv无法写入的问题求助

问题:修改视频流初始化后Log.csv无法写入数据

我基于GitHub上的People-Counting-in-Real-Time-master项目开发自己的功能,将视频流初始化代码从:

if not args.get("input", False):
    print("[INFO] Starting the live stream..")
    vs = VideoStream(config.url).start()
    time.sleep(2.0)

改为本地摄像头模式:

if not args.get("input", False):
    print("[INFO] Starting the live stream..")
    vs = VideoStream(src=0).start()
    time.sleep(2.0)

之后Log.csv完全无法写入数据。我尝试过两种写入逻辑,均无效:

第一种写入代码:

if config.Log:
    datetimee = [datetime.datetime.now()]
    d = [datetimee, empty1, empty, x]
    export_data = zip_longest(*d, fillvalue = '')

    with open('Log.csv', 'w', newline='') as myfile:
        wr = csv.writer(myfile, quoting=csv.QUOTE_ALL)
        wr.writerow(("End Time", "In", "Out", "Total Inside"))
        wr.writerows(export_data)

第二种写入代码(判断文件是否存在):

if config.Log:
    datetimee = [datetime.datetime.now()]
    d = [datetimee, empty1, empty, x]
    export_data = zip_longest(*d, fillvalue = '')
    
    try:
        with open('Log.csv', 'r') as check:
            pass
    except FileNotFoundError:
        with open('Log.csv', 'w', newline='') as myfile:
            wr = csv.writer(myfile, quoting=csv.QUOTE_ALL)
            wr.writerow(("End Time", "In", "Out", "Total Inside"))
            wr.writerows(export_data)

距离项目展示仅剩一周,急需解决该问题。


排查与修复方案

1. 先确认写入分支是否被触发

核心问题可能是config.Log未设为True,导致写入代码根本没执行。在写入块开头加调试输出验证:

if config.Log:
    print("=== 进入Log写入分支 ===")  # 调试输出
    datetimee = [datetime.datetime.now()]
    d = [datetimee, empty1, empty, x]
    export_data = zip_longest(*d, fillvalue = '')

    with open('Log.csv', 'w', newline='') as myfile:
        wr = csv.writer(myfile, quoting=csv.QUOTE_ALL)
        wr.writerow(("End Time", "In", "Out", "Total Inside"))
        wr.writerows(export_data)
    print("=== Log写入完成 ===")  # 调试输出

如果控制台没出现这两行打印,直接去项目配置文件把Log参数设为True。

2. 修正写入逻辑(适配实时流场景)

原项目的写入逻辑是为视频文件处理设计的(处理完一次性写入),但本地摄像头是实时流,需要调整为追加模式或退出时触发写入:

方案A:实时追加写入(每次计数更新时写入)

把写入封装成函数,在计数逻辑更新后调用:

from datetime import datetime
from itertools import zip_longest
import csv

def write_log(empty1, empty, x):
    # 检查文件是否存在,不存在则写入表头
    file_exists = False
    try:
        with open('Log.csv', 'r'):
            file_exists = True
    except FileNotFoundError:
        pass

    # 用追加模式打开文件,避免覆盖原有数据
    with open('Log.csv', 'a', newline='') as myfile:
        wr = csv.writer(myfile, quoting=csv.QUOTE_ALL)
        if not file_exists:
            wr.writerow(("End Time", "In", "Out", "Total Inside"))
        # 直接写入当前状态(如果empty1/empty/x是单个数值,无需用zip)
        wr.writerow([datetime.now(), empty1, empty, x])

# 在计数更新的代码块中调用(比如有人进/出后)
if config.Log:
    write_log(empty1, empty, x)
方案B:程序退出时触发写入

捕获Ctrl+C信号,在退出时写入最终日志:

import signal
import sys
from datetime import datetime
from itertools import zip_longest
import csv

def exit_handler(sig, frame):
    print("\n程序退出,写入最终日志...")
    if config.Log:
        datetimee = [datetime.now()]
        d = [datetimee, empty1, empty, x]
        export_data = zip_longest(*d, fillvalue = '')
        with open('Log.csv', 'w', newline='') as myfile:
            wr = csv.writer(myfile, quoting=csv.QUOTE_ALL)
            wr.writerow(("End Time", "In", "Out", "Total Inside"))
            wr.writerows(export_data)
    sys.exit(0)

# 注册退出信号处理
signal.signal(signal.SIGINT, exit_handler)

# 视频流循环逻辑
while True:
    # 帧处理、计数更新...
    pass

3. 排查其他常见问题

  • 路径问题:Log.csv可能被写入到非预期目录,改用绝对路径测试(比如C:/your_project/Log.csv或/home/your_user/your_project/Log.csv)
  • 权限问题:当前用户没有目录写入权限,换个有权限的目录,或用管理员/root权限运行程序
  • 变量未初始化:empty1、empty、x如果是None或空值,会导致写入失败,检查计数逻辑是否正确赋值这三个变量

内容的提问来源于stack exchange,提问作者Zen Rokusyo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.22 00:05:33