#!/bin/bash
# encoding:utf-8
# 视频流服务的启动命令
STREAM_SERVICE_CMD="python yolov8_s.py"
# 检查网络连通性的命令
NETWORK_CHECK_CMD1="ping -c 1 192.168.1.208"
NETWORK_CHECK_CMD2="ping -c 1 192.168.1.189"
# 函数:检查进程是否存在
is_process_running() {
if [ -n "$1" ]; then
kill -0 $1 2>/dev/null
return $?
else
return 1
fi
}
# 函数:获取正在运行的yolov8_s.py进程ID
get_stream_service_pid() {
pgrep -f "python yolov8_s.py"
#ps aux | grep python yolov8_s.py
}
# 无限循环,保持脚本运行
while true; do
# 检查第一个网络连接
$NETWORK_CHECK_CMD1
if [ $? -eq 0 ]; then
# 检查第二个网络连接
$NETWORK_CHECK_CMD2
if [ $? -eq 0 ]; then
# 如果两个网络连接都成功,检查视频流服务是否已经在运行
STREAM_SERVICE_PID=$(get_stream_service_pid)
# echo "视频流服务已: $STREAM_SERVICE_PID"
if [ -z "$STREAM_SERVICE_PID" ]; then
# 如果服务未运行,启动视频流服务
echo "两个网络连接正常,启动视频流服务..."
$STREAM_SERVICE_CMD &
# 获取视频流服务的进程ID
STREAM_SERVICE_PID=$!
echo "视频流服务已启动,进程ID: $STREAM_SERVICE_PID"
else
echo "视频流服务已在运行,进程ID: $STREAM_SERVICE_PID"
fi
else
# 如果第二个网络连接失败,检查是否有正在运行的进程
STREAM_SERVICE_PID=$(get_stream_service_pid)
# if [ -n "$STREAM_SERVICE_PID" ] && is_process_running$STREAM_SERVICE_PID; then
if [ -n "$STREAM_SERVICE_PID" ] ; then
# 杀死视频流服务
echo "第二个网络连接失败,杀死视频流服务..."
kill $STREAM_SERVICE_PID
wait $STREAM_SERVICE_PID 2>/dev/null
STREAM_SERVICE_PID=
fi
echo "第二个网络连接失败,等待网络恢复..."
fi
else
# 如果第一个网络连接失败,检查是否有正在运行的进程
STREAM_SERVICE_PID=$(get_stream_service_pid)
# if [ -n "$STREAM_SERVICE_PID" ] && is_process_running$STREAM_SERVICE_PID; then
if [ -n "$STREAM_SERVICE_PID" ]; then
# 杀死视频流服务
echo "第一个网络连接失败,杀死视频流服务..."
kill $STREAM_SERVICE_PID
wait $STREAM_SERVICE_PID 2>/dev/null
STREAM_SERVICE_PID=
fi
echo "第一个网络连接失败,等待网络恢复..."
fi
# 等待一段时间再次检查网络连接
sleep 10
done
将以上代码放入sh文件中,运行即可
YOLOv8拉取视频流识别,并对坐标排序,排序为3行4列的格式,代码如下
from ultralytics import YOLO
import cv2
import os
import time
import json
# Load a model
model = YOLO("yolov8n.yaml") # build a new model from scratch
model = YOLO("./best.pt") # load a pretrained model (recommended for training)
def convert_to_dict_format(data):
result = []
for row in data:
for item in row:
result.append({'x': item[0], 'y': item[1], 'value': item[2]})
return result
# Use the model
#model.train(data="coco8.yaml", epochs=3) # train the model
#metrics = model.val() # evaluate model performance on the validation set
# 设置RTSP流地址
rtsp_url = 'rtsp://admin:12345@192.168.1.189:554/h264/ch1/main/av_stream'
# 设置图片保存的目录
save_dir = 'frames'
# 创建保存目录
if not os.path.exists(save_dir):
os.makedirs(save_dir)
# 打开RTSP流
cap = cv2.VideoCapture(rtsp_url)
fps = cap.get(cv2.CAP_PROP_FPS)
print("fps:", fps)
ii = 0
# 循环读取RTSP流中的每一帧
while True:
# 从RTSP流中读取一帧
ret, frame = cap.read()
ii += 1
# 如果读取成功
if ret:
# 获取当前时间戳
print("time.strftime('%Y-%m-%d %H:%M:%S'):", time.strftime('%Y-%m-%d %H:%M:%S'))
now = time.strftime('%Y-%m-%d-%H:%M:%S')
now_ms = int(time.time() * 1000 ) % 1000
print("now:", now)
# current_time_ms = f"{now}
# timestamp = cv2.putText(frame, f"{time.strftime('%Y-%m-%d-%H:%M:%S')}", (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 0.5,
# (0, 0, 255), 2)
timestamp = cv2.putText(frame, now, (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 0.5,
(0, 0, 255), 2)
results = model(source=frame,save=True) # predict on an image
#img = cv2.imread('./bus.jpg')
left_uper = []
cor_cls = []
for i, result in enumerate(results):
for box in result.boxes:
cls_rename = ''
x1, y1, x2, y2 = box.xyxy[0]
cls_name = result.names[int(box.cls)]
if cls_name == "phone":
cls_rename = "1"
elif cls_name == "no_phone":
cls_rename = "0"
x1, y1, x2, y2 = x1.cpu(), y1.cpu(), x2.cpu(), y2.cpu()
x1, y1, x2, y2 = x1.numpy(), y1.numpy(), x2.numpy(), y2.numpy()
left_uper.append((int(x1), int(y1)))
cor_cls.append((int(x1), int(y1), int(cls_rename)))
if len(left_uper) == 12:
#path = "/media/dgh/ultralytics/frames/" + str(ii) + '.jpg'
#cv2.imwrite("./sorted_groups.jpg", frame)
#cv2.imwrite(path, frame)
sorted_by_y = sorted(left_uper, key=lambda x: x[1])
# 将排序后的坐标分为四组,每组四个坐标
groups = [sorted_by_y[i:i + 4] for i in range(0, len(sorted_by_y), 4)]
# 对每组内的坐标按照X轴坐标从小到大排序
sorted_groups = [sorted(group, key=lambda x: x[0]) for group in groups]
# Convert cor_cls to a dictionary for easier lookup
cor_cls_dict = {tuple(point[:2]): point[2] for point in cor_cls}
# Replace the third value in sorted_groups with the corresponding value from cor_cls
for group in sorted_groups:
for i, point in enumerate(group):
# Replace the point with a tuple that includes the class value
group[i] = point + (cor_cls_dict.get(point, None),)
sorted_groups = convert_to_dict_format(sorted_groups)
# Convert the updated sorted_groups to a JSON string
sorted_groups_json = json.dumps(sorted_groups)
# Save the JSON string to a file
output_file = "./sorted_groups.json"
with open(output_file, "w") as f:
f.write(sorted_groups_json)
# cv2.rectangle(img, (int(x1), int(y1)), (int(x2), int(y2)), (0, 255, 0), 2)
# cv2.putText(img, result.names[int(box.cls)], (int(x1), int(y1) - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.9, (0, 255, 0), 2)
# cv2.imwrite('./bus11.jpg', img)
# print("results:", results)
YOLOv8改进参考博客https://blog.youkuaiyun.com/weixin_45679938/article/details/139077352