PC端yolov3处理视频流并返回坐标给树莓派的代码
时间: 2023-02-24 18:22:11 浏览: 207
下面是一个使用 yolov3 在 PC 端处理视频流,并返回坐标给树莓派的代码示例:
```
import cv2
import numpy as np
import time
import socket
# Load YOLO model
net = cv2.dnn.readNetFromDarknet("yolov3.cfg", "yolov3.weights")
classes = []
with open("coco.names", "r") as f:
classes = [line.strip() for line in f.readlines()]
layer_names = net.getLayerNames()
output_layers = [layer_names[i[0] - 1] for i in net.getUnconnectedOutLayers()]
colors = np.random.uniform(0, 255, size=(len(classes), 3))
# Start video capture
cap = cv2.VideoCapture(0)
# Connect to Raspberry Pi
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect(("192.168.1.100", 8000))
while True:
# Read a frame from the video
ret, frame = cap.read()
height, width, channels = frame.shape
# Detect objects in the frame
blob = cv2.dnn.blobFromImage(frame, 0.00392, (416, 416), (0, 0, 0), True, crop=False)
net.setInput(blob)
outs = net.forward(output_layers)
# Show the detection results
class_ids = []
confidences = []
boxes = []
for out in outs:
for detection in out:
scores = detection[5:]
class_id = np.argmax(scores)
confidence = scores[class_id]
if confidence > 0.5:
# Object detected
center_x = int(detection[0] * width)
center_y = int(detection[1] * height)
w = int(detection[2] * width)
h = int(detection[3] * height)
x = center_x - w / 2
y = center_y - h / 2
class_ids.append(class_id)
confidences.append(float(confidence))
boxes.append([x, y, w, h])
# Apply Non-Maxima Suppression
indices = cv2.dnn.NMSBoxes(boxes, confidences, 0.5, 0.4)
# Send the coordinates to Raspberry Pi
objects = []
for i in indices:
i = i[0]
box = boxes[i]
x = box[0]
y = box[1]
w = box[2]
h = box[3]
objects.append({"class_id": class_ids[i], "confidence": confidences[i], "x": x, "y": y, "w": w, "h": h})
client.
阅读全文