给定一张特定物体图片, 从另外的图片中找出所有的这个物体并标记在图上, 请给出python代码
时间: 2024-03-12 15:49:43 浏览: 19
这是一个使用OpenCV和YOLOv3模型实现的例子,可以检测出给定的特定物体,并在另一张图片中标记出所有的这个物体。
请先确保已经安装了OpenCV和YOLOv3模型。
```python
import cv2
import numpy as np
# 加载YOLOv3模型
net = cv2.dnn.readNetFromDarknet("yolov3.cfg", "yolov3.weights")
# 加载COCO数据集标签
classes = []
with open("coco.names", "r") as f:
classes = [line.strip() for line in f.readlines()]
# 指定要检测的物体类别
target_class = "person"
# 加载测试图片
image = cv2.imread("test.jpg")
# 获取图片尺寸
height, width, _ = image.shape
# 构建输入图像的blob
blob = cv2.dnn.blobFromImage(image, 1 / 255.0, (416, 416), swapRB=True, crop=False)
# 设置输入blob并执行前向传播
net.setInput(blob)
layer_names = net.getLayerNames()
output_layers = [layer_names[i[0] - 1] for i in net.getUnconnectedOutLayers()]
outputs = net.forward(output_layers)
# 处理检测结果
boxes = []
confidences = []
class_ids = []
for output in outputs:
for detection in output:
scores = detection[5:]
class_id = np.argmax(scores)
confidence = scores[class_id]
if confidence > 0.5 and classes[class_id] == target_class:
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, 0.5, 0.4)
# 绘制边界框和标签
for i in indices:
i = i[0]
x, y, w, h = boxes[i]
label = "{}: {:.2f}".format(target_class, confidences[i])
cv2.rectangle(image, (x, y), (x + w, y + h), (0, 255, 0), 2)
cv2.putText(image, label, (x, y - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2)
# 显示结果图像
cv2.imshow("Image", image)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
在这个例子中,我们使用了COCO数据集的标签,如果你要检测的物体不在COCO数据集中,你需要准备自己的训练数据集,并训练一个适合你需求的模型。