不墨迹上代码:
import cv2
import threading
from urllib.parse import urlparse
# 创建一个锁
lock = threading.Lock()
frame = None
running = True # 用于控制主循环的运行
def video_capture(url):
global frame
cap = cv2.VideoCapture(url)
while running: # 使用全局变量控制循环
ret, temp_frame = cap.read()
if ret:
with lock:
frame = temp_frame
else:
break
cap.release()
# 设置你要访问的网站URL
url = input("网站(使用格式如:http://example.com/path/to/video):")
parsed_url = urlparse(url)
domain = parsed_url.netloc # 获取域名部分
# 启动视频捕捉线程
capture_thread = threading.Thread(target=video_capture, args=(url,))
capture_thread.start()
window_name = 'Video Stream'
cv2.namedWindow(window_name, cv2.WINDOW_NORMAL)
desired_width = 900
desired_height = 500
cv2.resizeWindow(window_name, desired_width, desired_height)
while True:
with lock:
if frame is not None:
cv2.imshow(window_name, frame)
# 检查是否按下 'q' 键
if cv2.waitKey(1) & 0xFF == ord('q'):
running = False # 设置标志以停止循环
break
# 等待视频捕捉线程结束
capture_thread.join()
cv2.destroyAllWindows()