opencv 和 yolov8的代码
时间: 2023-10-19 15:03:54 浏览: 131
C++ opencv部署yolov8旋转框目标检测源码
5星 · 资源好评率100%
以下是 OpenCV 和 YOLOv3 的代码示例:
OpenCV:
```python
import cv2
# 读取图片
img = cv2.imread('image.jpg')
# 转换为灰度图像
gray_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# 显示图像
cv2.imshow('image', img)
cv2.imshow('gray_image', gray_img)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
YOLOv3:
```python
import cv2
import numpy as np
# 加载 YOLOv3 模型
net = cv2.dnn.readNet("yolov3.weights", "yolov3.cfg")
# 加载类别标签
classes = []
with open("coco.names", "r") as f:
classes = [line.strip() for line in f.readlines()]
# 读取图片
img = cv2.imread("image.jpg")
# 获取图像尺寸
height, width, _ = img.shape
# 将图像转换为 blob
blob = cv2.dnn.blobFromImage(img, 1 / 255.0, (416, 416), swapRB=True, crop=False)
# 设置输入层
net.setInput(blob)
# 获取输出层的名称
layer_names = net.getLayerNames()
output_layers = [layer_names[i[0] - 1] for i in net.getUnconnectedOutLayers()]
# 进行前向传播
outs = net.forward(output_layers)
# 解析输出
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:
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])
# 进行非最大值抑制
indexes = cv2.dnn.NMSBoxes(boxes, confidences, 0.5, 0.4)
# 绘制边框和标签
font = cv2.FONT_HERSHEY_PLAIN
colors = np.random.uniform(0, 255, size=(len(classes), 3))
for i in range(len(boxes)):
if i in indexes:
x, y, w, h = boxes[i]
label = str(classes[class_ids[i]])
color = colors[class_ids[i]]
cv2.rectangle(img, (x, y), (x + w, y + h), color, 2)
cv2.putText(img, label, (x, y + 30), font, 3, color, 3)
# 显示图像
cv2.imshow("Image", img)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
请注意,上述代码仅供参考,具体实现可能因不同的需求而有所不同。
阅读全文