基于yolo的安检危险物品代码
时间: 2023-12-15 14:04:11 浏览: 34
以下是基于YOLO的安检危险物品代码示例,可以检测出常见的危险物品:
```python
import cv2
import numpy as np
import os
# Load Yolo
net = cv2.dnn.readNet("yolov3.weights", "yolov3.cfg")
classes = []
with open("coco.names", "r") as f:
classes = [line.strip() for line in f.readlines()]
# Load image
img = cv2.imread("test_image.jpg")
# Get image dimensions
height, width, channels = img.shape
# Create blob from image
blob = cv2.dnn.blobFromImage(img, 1/255, (416, 416), (0,0,0), swapRB=True, crop=False)
# Set input layer for the network
net.setInput(blob)
# Get output layer names
layer_names = net.getLayerNames()
output_layers = [layer_names[i[0] - 1] for i in net.getUnconnectedOutLayers()]
# Run forward pass through the network
outs = net.forward(output_layers)
# Initialize variables for boxes, confidences and class IDs
boxes = []
confidences = []
class_ids = []
# Loop through all detections
for out in outs:
for detection in out:
# Get confidence score for the detection
scores = detection[5:]
class_id = np.argmax(scores)
confidence = scores[class_id]
# Filter out weak detections with a low confidence score
if confidence > 0.5:
# Get the center coordinates and dimensions of the box
center_x = int(detection[0] * width)
center_y = int(detection[1] * height)
w = int(detection[2] * width)
h = int(detection[3] * height)
# Calculate top-left corner of the box
x = int(center_x - w / 2)
y = int(center_y - h / 2)
# Add box, confidence and class ID to the lists
boxes.append([x, y, w, h])
confidences.append(float(confidence))
class_ids.append(class_id)
# Apply non-max suppression to remove overlapping boxes
indices = cv2.dnn.NMSBoxes(boxes, confidences, 0.5, 0.4)
# Draw boxes and labels for the detected objects
for i in indices:
i = i[0]
box = boxes[i]
x = box[0]
y = box[1]
w = box[2]
h = box[3]
label = str(classes[class_ids[i]]) + " " + str(confidences[i])
cv2.rectangle(img, (x,y), (x+w,y+h), (0,255,0), 2)
cv2.putText(img, label, (x, y-10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0,255,0), 2)
# Display the result
cv2.imshow("Result", img)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
请注意,此示例使用的是COCO数据集预训练的YOLOv3模型,可以检测出多种物体,而不仅仅是危险物品。如果您想要检测特定的危险物品,请使用相应的数据集进行训练。