所以写了这段代码来打开视频网络摄像头,我想保存摄像头打开时的日志,但文件不会停止更新

so have written this code that opens webcam for video and i want to save the logs of when the cam was turned on but the file doesn't stop updating

所以我是 python 的新手,但我想使用 cv2 打开网络摄像头,我也试图保存日志,就像打开网络摄像头时一样,所以我使用 file.txt 来存储,所以我使用日期时间并将其保存到 file.txt 但问题是文件在我关闭程序之前不会停止更新。请帮忙

from flask import Flask,render_template,request
import cv2
import datetime

app=Flask(__name__)

@app.route("/")
def main():
    return render_template('app.html')

@app.route("/calculate", methods=['POST'])
def webcam():
    import cv2

    cap = cv2.VideoCapture(0)

    # Check if the webcam is opened correctly
    if not cap.isOpened():
        raise IOError("Cannot open webcam")

    while True:
        
        ret, frame = cap.read()
        frame = cv2.flip(frame,1)
        frame = cv2.resize(frame, None, fx=1, fy=1, interpolation=cv2.INTER_AREA)
        

        # describe the type of font
        # to be used.
        font = cv2.FONT_HERSHEY_SIMPLEX
        
        #writing text
        cv2.putText(frame, "Press esc to quit", (50, 50), cv2.FONT_HERSHEY_SIMPLEX, 1, (199,21,133))
        
        cv2.imshow('Webcam', frame)
        
        #storing logs in a file
        with open("logs.txt",'w') as myfile:
            ct=datetime.datetime.now()
            myfile.write(str(ct))
             
        
        c = cv2.waitKey(1) #add 0 for frame pic when you stroke any key
        if c == 27:
            break
        
            
    
    cap.release()
    cv2.destroyAllWindows()
    return render_template("app.html")

问题出在您记录的位置...当您将记录代码放在 while True 语句下时,它会一直记录直到循环中断。

cap = cv2.VideoCapture(0) 我猜这一行是打开网络摄像头的那一行,因为在那之后你正在检查网络摄像头是否成功打开......为什么不在 like

之后移动日志代码
# Check if the webcam is opened correctly
if not cap.isOpened():
    raise IOError("Cannot open webcam")

#storing logs in a file
with open("logs.txt",'w') as myfile:
    ct=datetime.datetime.now()
    myfile.write(str(ct))