python - 所以写了这段代码来打开网络摄像头的视频,我想保存打开摄像头但文件没有停止更新的日志
问题描述
所以我是 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)
我猜这一行是打开网络摄像头的那一行,因为之后您正在检查网络摄像头是否已成功打开......为什么不移动日志代码之后喜欢
# 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))
推荐阅读
- spring - 用户注销时 Spring Security 从数据库中删除会话
- java - 分析名称在一组名称中的比例。我的输出不正确。("John") 应该返回 0.25。玛丽应该是 0.5
- python - 如何根据字符串名称将向量附加到 numpy 矩阵?
- amazon-web-services - 具有相同 CodeUri 的 AWS 多个 lambda
- java - Java自顶向下合并排序 - Stackoverflow错误
- kubernetes - K8s:添加 env 值后应用 yaml 文件时出错
- c++ - x=10 和 x{10} 有什么区别?
- jquery - jQuery 无法处理 Ajax 加载的 div 内容
- javascript - 在组件中使用 Next.js 动态导入可以吗?
- sorting - 如何在 Google 表格中以相反的顺序填写公式