我有一个代码,我想要从相机捕获视频。我想使用Python的Logging库来获取shell上的消息或将它们导出到文本文件。
以下是我的代码的一部分,其中我想要打印的while循环相机已成功打开
import numpy as np
import cv2
import logging as log
cap = cv2.VideoCapture('5.mpg')
while True:
ret, image = cap.read()
if ret == True:
log.warning('Camera Opened Successfully')
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
clahe = cv2.createCLAHE(clipLimit = 15.0, tileGridSize=(8,8))
gray1 = clahe.apply(gray)
但我在shell中得到的是:
直到我终止正在运行的脚本。关于如何只打印一次的任何想法。
答案 0 :(得分:3)
import numpy as np
import cv2
import logging as log
cap = cv2.VideoCapture('5.mpg')
hasOpened = False
while True:
ret, image = cap.read()
if ret and not hasOpened:
log.warning('Camera Opened Successfully')
hasOpened = True
如果您想在打印后摆脱循环,请按照Matt的回答。此选项将在循环中继续,只打印一次。
答案 1 :(得分:1)
添加一个额外的布尔值来跟踪您是否在之前将其打印出来:
import numpy as np
import cv2
import logging as log
cap = cv2.VideoCapture('5.mpg')
printed = False
while True:
ret, image = cap.read()
if ret == True and not printed:
log.warning('Camera Opened Successfully')
printed = True
答案 2 :(得分:0)
你必须摆脱循环
import numpy as np
import cv2
import logging as log
cap = cv2.VideoCapture('5.mpg')
while True:
ret, image = cap.read()
if ret == True:
log.warning('Camera Opened Successfully')
break
答案 3 :(得分:0)
你需要打破while循环,因为你想在ret
为真的时候突然离开循环你可以使用:
ret = False
while not ret:
ret, image = cap.read()
if ret:
log.warning('Camera Opened Successfully')
# any other code
答案 4 :(得分:0)
设置标志以触发日志,然后将其设为false。当你准备退出循环以使它退出时,ret将变为False
import numpy as np
import cv2
import logging as log
cap = cv2.VideoCapture('5.mpg')
ret = True
logit = True
while ret:
ret, image = cap.read()
if logit == True:
log.warning('Camera Opened Successfully')
logit = False
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
clahe = cv2.createCLAHE(clipLimit = 15.0, tileGridSize=(8,8))
gray1 = clahe.apply(gray)
// process remainder of situation setting
答案 5 :(得分:-1)
假设你想使用你的主循环来处理你的应用程序逻辑,并且有一个循环用于检测它是否被打开而另一个用于处理它是没有意义的,那么我认为你想要的是设置一个变量以确定状态是否已更改。
import numpy as np
import cv2
import logging as log
cap = cv2.VideoCapture('5.mpg')
old_ret = False
while True:
ret, image = cap.read()
if old_ret == False and ret == True:
old_red = True
log.warning('Camera Opened Successfully')
if ret == True:
# Do other things that need the camera but no log