我VideoCapture對流式傳輸的視頻僅顯示第一幀的位置有疑問。在以下代碼中,我將視頻疊加在物件檢測產生的邊界框之上:
if view_img:
####video_name is a path to my video
img = cv2.VideoCapture(video_name)
ret_video, frame_video = img.read()
if not ret_video: ######so that the video can be played in a loop
img = cv2.VideoCapture(video_name)
ret_video, frame_video = img.read()
###here I look for the bounding boxes and superimpose the video
hsv = cv2.cvtColor(im0, cv2.COLOR_BGR2HSV)
mask = cv2.inRange(hsv, (0, 120, 120), (10, 255, 255))#(110, 120, 120), (130, 255, 255))#<- blue # RED: (0, 120, 120), (10, 255, 255))
thresh = cv2.dilate(mask, None, iterations=2)
contours = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
#contours = contours[0]
contours = imutils.grab_contours(contours)
#frame_counter = 0
for contour in contours:
if cv2.contourArea(contour) < 750:
continue
(x, y, w, h) = cv2.boundingRect(contour)
height = 480
width = 640
if y h < height and x w < width:
logo = cv2.resize(frame_video, (w, h))###frame_video is the frame from the video which I superimpose
img2gray = cv2.cvtColor(logo, cv2.COLOR_BGR2GRAY)
_, logo_mask = cv2.threshold(img2gray, 1, 255, cv2.THRESH_BINARY)
roi = im0[y:y h, x:x w]
roi[np.where(logo_mask)] = 0
roi = logo
cv2.imshow(str(p), im0)# im0 is the webcam frame
cv2.waitKey(25)
當我運行這段代碼時,會發生什么,而不是在網路攝像頭框架的頂部顯示整個視頻,它只顯示該視頻的第一幀。
疊加視頻在另一個腳本中作業正常,修改原始:源
我認為這個問題與waitKey()疊加視頻有關,因為它沒有具體說明。
如果我嘗試用while (cap.isopened()):或初始化視頻,while (True)然后程式凍結并且根本沒有輸出。
uj5u.com熱心網友回復:
cv2.VideoCapture應該為每個設備源運行一次。使用while loop應該排除cv2.VideoCapture(在回圈外初始化它)。它掛起的while loop原因是您多次打開同一設備的連接而沒有關閉它。
uj5u.com熱心網友回復:
我沒有測驗它。你只需這樣做:順便說一句
if view_img:
####video_name is a path to my video
img = cv2.VideoCapture(video_name)
while img.isOpened():
ret_video, frame_video = img.read()
if not ret_video: ######so that the video can be played in a loop
break
###here I look for the bounding boxes and superimpose the video
hsv = cv2.cvtColor(im0, cv2.COLOR_BGR2HSV)
mask = cv2.inRange(hsv, (0, 120, 120), (10, 255, 255))#(110, 120, 120), (130, 255, 255))#<- blue # RED: (0, 120, 120), (10, 255, 255))
thresh = cv2.dilate(mask, None, iterations=2)
contours = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
#contours = contours[0]
contours = imutils.grab_contours(contours)
#frame_counter = 0
for contour in contours:
if cv2.contourArea(contour) < 750:
continue
(x, y, w, h) = cv2.boundingRect(contour)
height = 480
width = 640
if y h < height and x w < width:
logo = cv2.resize(frame_video, (w, h))###frame_video is the frame from the video which I superimpose
img2gray = cv2.cvtColor(logo, cv2.COLOR_BGR2GRAY)
_, logo_mask = cv2.threshold(img2gray, 1, 255, cv2.THRESH_BINARY)
roi = im0[y:y h, x:x w]
roi[np.where(logo_mask)] = 0
roi = logo
cv2.imshow(str(p), im0)# im0 is the webcam frame
cv2.waitKey(25)
順便說一句,如果您使用的是 OpenCV4.5.5。您可能需要添加以下內容:
ret,contours = cv2.findContours
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/461995.html
