python调用海康工业相机并用opencv显示,并进行YOLO识别
时间: 2025-04-01 19:11:26 AIGC 浏览: 124
### Python调用海康威视工业相机并结合OpenCV显示图像及YOLO目标检测
#### 使用 OpenCV 调用海康威视工业相机
要通过 `cv2.VideoCapture()` 接口调用海康威视工业相机,可以使用 RTSP 协议连接到设备。以下是具体方法:
```python
import cv2
url = "rtsp://admin:[email protected]/Streaming/Channels/2"
cap = cv2.VideoCapture(url)
if not cap.isOpened():
print("无法打开摄像头")
else:
while True:
ret, frame = cap.read()
if not ret:
print("未能读取帧")
break
# 显示图像
cv2.imshow("Camera Feed", frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
```
上述代码实现了通过 RTSP 地址访问海康威视工业相机,并实时显示其捕获的画面[^2]。
---
#### 结合 YOLO 实现目标检测
为了在获取的视频流上应用 YOLO 进行目标检测,需加载预训练模型并对每一帧执行推理操作。以下是一个完整的示例代码:
```python
import cv2
import numpy as np
def load_yolo_model(weights_path, config_path, labels_path):
net = cv2.dnn.readNetFromDarknet(config_path, weights_path)
with open(labels_path, 'r') as f:
classes = [line.strip() for line in f.readlines()]
layer_names = net.getLayerNames()
output_layers = [layer_names[i - 1] for i in net.getUnconnectedOutLayers()]
return net, classes, output_layers
def detect_objects(frame, net, output_layers):
blob = cv2.dnn.blobFromImage(frame, scalefactor=0.00392, size=(416, 416), mean=(0, 0, 0), swapRB=True, crop=False)
net.setInput(blob)
outputs = net.forward(output_layers)
return outputs
def draw_boxes(outputs, frame, classes, confidence_threshold=0.5, nms_threshold=0.4):
class_ids = []
confidences = []
boxes = []
height, width = frame.shape[:2]
for output in outputs:
for detection in output:
scores = detection[5:]
class_id = np.argmax(scores)
confidence = scores[class_id]
if confidence > confidence_threshold:
center_x = int(detection[0] * width)
center_y = int(detection[1] * height)
w = int(detection[2] * width)
h = int(detection[3] * height)
x = int(center_x - w / 2)
y = int(center_y - h / 2)
boxes.append([x, y, w, h])
confidences.append(float(confidence))
class_ids.append(class_id)
indices = cv2.dnn.NMSBoxes(boxes, confidences, confidence_threshold, nms_threshold)
for i in indices.flatten():
box = boxes[i]
color = (0, 255, 0)
label = f"{classes[class_ids[i]]}: {confidences[i]:.2f}"
cv2.rectangle(frame, (box[0], box[1]), (box[0]+box[2], box[1]+box[3]), color, thickness=2)
cv2.putText(frame, label, (box[0], box[1]-10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, color, thickness=2)
return frame
# 加载 YOLO 模型
weights_path = "yolov3.weights"
config_path = "yolov3.cfg"
labels_path = "coco.names"
net, classes, output_layers = load_yolo_model(weights_path, config_path, labels_path)
# 打开摄像头
url = "rtsp://admin:[email protected]/Streaming/Channels/2"
cap = cv2.VideoCapture(url)
while True:
ret, frame = cap.read()
if not ret:
print("未能读取帧")
break
outputs = detect_objects(frame, net, output_layers)
detected_frame = draw_boxes(outputs, frame, classes)
cv2.imshow("YOLO Detection", detected_frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
```
此代码片段展示了如何加载 YOLOv3 模型、处理每帧数据以提取边界框和类别标签,并绘制结果于原始图像之上[^3]。
---
#### 注意事项
- **RTSP 配置**:确保 RTSP URL 正确无误,用户名密码与实际设备匹配。
- **性能优化**:对于高分辨率视频流,可考虑降低输入尺寸或调整推理频率来提升效率。
- **依赖安装**:运行前确认已安装必要库 (`opencv-python` 和 `numpy`) 及下载对应权重文件。
---
阅读全文
相关推荐


















