Files
Feeding_control_system/vision/camera_picture.py

87 lines
3.2 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import os
import threading
from datetime import datetime
import cv2
import time
def capture_camera_images(rtsp_url, save_dir, camera_name, img_count=10, interval=0.5, reverse=False):
"""
从RTSP摄像头抓取指定数量图片并保存
:param rtsp_url: 摄像头RTSP地址
:param save_dir: 保存目录
:param camera_name: 摄像头名称(用于文件名区分)
:param img_count: 抓取图片数量
:param interval: 抓取间隔(秒)
:param reverse: 是否翻转180
"""
# 创建摄像头专属保存目录
camera_save_dir = os.path.join(save_dir, camera_name)
if not os.path.exists(camera_save_dir):
os.makedirs(camera_save_dir)
# 抓取并保存图片
for i in range(img_count):
cap = None
try:
# 打开RTSP流
cap = cv2.VideoCapture(rtsp_url, cv2.CAP_FFMPEG)
if not cap.isOpened():
continue
cap.set(cv2.CAP_PROP_BUFFERSIZE, 1)
ret, frame = cap.read()
if reverse: # 镜像翻转
frame = cv2.flip(frame, -1)
if ret and frame is not None:
img_filename = f"{camera_name}_{datetime.now().strftime('%Y%m%d%H%M%S')}_{i+1}.jpg"
img_path = os.path.join(camera_save_dir, img_filename)
cv2.imwrite(img_path, frame)
time.sleep(interval)
except Exception as e:
print(f"⚠ 摄像头 {camera_name}{i+1} 次截图异常:{e},跳过")
finally:
if cap is not None and cap.isOpened():
cap.release()
print(f"✅ 摄像头 {camera_name} 完成,共保存 {img_count} 张浇筑满的图片")
def save_camera_picture(save_dir="full_images", img_count=15, interval=1.5, camera_60_rtsp=None, camera_61_rtsp=None):
"""
执行摄像头截图保存:
1. 创建以时间戳命名的目录,统一存放日志和图片
2. 抓取60和61摄像头各img_count张图片
:param save_dir: 保存浇筑满图片的顶级目录
:param img_count: 每次浇筑满, 保存的图片的总数量
:param interval: 保存两张浇筑满图片之间的时间间隔
"""
# 0. 先创建上级目录save_dir若不存在
if not os.path.exists(save_dir):
os.makedirs(save_dir)
# 1. 创建保存浇筑满图片的根目录
root_dir = f"{save_dir}/PourFull_{datetime.now().strftime('%Y%m%d%H%M%S')}"
if not os.path.exists(root_dir):
os.makedirs(root_dir)
# 2. 抓取两个摄像头的图片
if camera_60_rtsp is None:
camera_60_rtsp = "rtsp://admin:XJ123456@192.168.250.60:554/streaming/channels/101"
if camera_61_rtsp is None:
camera_61_rtsp = "rtsp://admin:XJ123456@192.168.250.61:554/streaming/channels/101"
# 并行抓取
t1 = threading.Thread(
target=capture_camera_images,
args=(camera_60_rtsp, root_dir, "camera60", img_count, interval, False),
daemon=True
)
t2 = threading.Thread(
target=capture_camera_images,
args=(camera_61_rtsp, root_dir, "camera61", img_count, interval, True),
daemon=True
)
t1.start()
t2.start()
return root_dir