YOLOV8 OpenCV + usb 相机 实时识别
0、STM32 上位机通信
STM32 上位机通信
1、OpenCV 读相机
import cv2
cap = cv2.VideoCapture(0)
while (1):
# get a frame
ret, frame = cap.read()
# show a frame
cv2.imshow("capture", frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
# cv2.imwrite("/opt/code/image/fangjian2.jpeg", frame)
#pass
break
cap.release()
cv2.destroyAllWindows()
2、yolov8推理
from ultralytics import YOLO
model =YOLO('yolov8n.pt')
result = model.predict('dog.jpg',imgsz = 640,show = True)
3、 yolov8 实时推理相机图片
from ultralytics import YOLO
import cv2
def get_img(cap):
while (1):
# get a frame
ret, frame = cap.read()
# show a frame
# cv2.imshow("capture", frame)
# if cv2.waitKey(1) & 0xFF == ord('q'):
# # cv2.imwrite("/opt/code/image/fangjian2.jpeg", frame)
# #pass
# break
return frame
m_cap = cv2.VideoCapture(0)
model =YOLO('yolov8n.pt')
# 输出检测结果和坐标
while True:
img = get_img(m_cap)
cv2.imshow("capture", img)
cv2.waitKey(1)
#results = model.predict(img)
results = model.predict(img)
annotated_frame = results[0].plot()
cv2.imshow("YOLOv8 Tracking", annotated_frame)
cv2.waitKey(1)
4、 result
5、 PS
总结,在一台老旧的电脑上
跑yolov8 n 感觉速度可以
识别精度也还凑合
6、 yolo v8 输出检测框坐标
import cv2
import os
from ultralytics import YOLO
import random
# 加载YOLOv8模型
#model = YOLO('yolov8n.pt')
model = YOLO('../runs/detect/train6/weights/last.pt')
# 打开视频文件
##--
frame = cv2.imread("I:/motor/fruit/" + str(7888) + '.jpg')
cv2.imshow('22', frame)
cv2.waitKey(0)
video_path = os.path.join('.', 'data', 'people.mp4')
fourcc = cv2.VideoWriter_fourcc(*'XVID')
cap_out = cv2.VideoWriter('testwrite.avi', fourcc, 10.0, (1920, 1080), True)
dic = {0: 'Pome', 1: 'Pear'}
colors = [ (255, 50, 255),(255, 0, 0)]
detection_threshold = 0.5
i = 7888
while i < 8050:
i += 1
frame = cv2.imread("I:/motor/fruit/" + str(i) + '.jpg')
results = model(frame)
for result in results:
detections = []
for r in result.boxes.data.tolist():
x1, y1, x2, y2, score, class_id = r
x1 = int(x1)
x2 = int(x2)
y1 = int(y1)
y2 = int(y2)
class_id = int(class_id)
cv2.rectangle(frame, (int(x1), int(y1)), (int(x2), int(y2)), (colors[class_id % len(colors)]), 3)
cv2.putText(frame, dic[class_id], (x1-10,y1-10), cv2.FONT_HERSHEY_SIMPLEX, 0.75, (colors[class_id % len(colors)]), 2)
cv2.putText(frame, '('+str(x1)+','+str(y1)+')', (x1+100, y1+100), cv2.FONT_HERSHEY_SIMPLEX, 0.75,(colors[class_id % len(colors)]), 2)
cv2.waitKey(2)
cv2.imshow('0', frame)
cap_out.write(frame)
if score > detection_threshold:
detections.append([x1, y1, x2, y2, score])
cap_out.write(frame)
cap_out.release()
cv2.destroyAllWindows()