首页 > 解决方案 > 所以写了这段代码来打开网络摄像头的视频,我想保存打开摄像头但文件没有停止更新的日志

问题描述

所以我是 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")

标签: pythonfilecv2

解决方案


问题来自您记录的位置...当您将记录代码放在while True语句下时,它将继续记录,直到循环被中断。

cap = cv2.VideoCapture(0)我猜这一行是打开网络摄像头的那一行,因为之后您正在检查网络摄像头是否已成功打开......为什么不移动日志代码之后喜欢

# 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))

推荐阅读