第一步利用 yolov8 训练出最佳的检测瓶盖的模型
安装环境:
python>=3.8
pip install ultralytics
(未用到 gpu)
代码:
from ultralytics import YOLO
if __name__ == '__main__':
# 加载预训练模型
model = YOLO('yolov8n.pt') # 你可以选择其他预训练模型,如 yolov8s.pt, yolov8m.pt
# 训练模型
results = model.train(data='C:\\Users\\lenovo\\Desktop\\bottle_cap_opened.v3i.yolov8-obb\\data.yaml', epochs=90, imgsz=640)
检测代码(来自gpt):
from ultralytics import YOLO
import cv2
# 加载训练好的模型
model_path = 'C:/Users/lenovo/Desktop/bottle_cap_opened.v3i.yolov8-obb/runs/detect/train8/weights/best.pt' # 替换为你的模型路径
model = YOLO(model_path)
# 加载图像
image_path = 'valid/images/16783_0_jpg.rf.555280bf85d0054adbced24477843732.jpg' # 替换为你的图像路径
img = cv2.imread(image_path)
# 检查图像是否加载成功
if img is None:
print(f"Error: Unable to load image from {image_path}")
exit()
# 假设图像的分辨率越大框架越小
dpi = 3300
# 进行检测
results = model(img)
# 解析检测结果
scale_factor = 0.83 # 调整比例因子,调整框架的因子
for result in results:
boxes = result.boxes
for box in boxes:
x1, y1, x2, y2 = box.xyxy[0]
x1, y1, x2, y2 = int(x1), int(y1), int(x2), int(y2)
center_x = (x1 + x2) // 2
center_y = (y1 + y2) // 2
width = (x2 - x1) * scale_factor
height = (y2 - y1) * scale_factor
radius_pixels = int(max(width, height) // 2) # 确保 radius 是整数
# 将像素转换为厘米
radius_cm = (radius_pixels / dpi) * 2.54
print(f"圆心坐标 (像素): ({center_x}, {center_y}), 半径 (像素): {radius_pixels}")
print(f"圆心坐标 (厘米): ({center_x / dpi * 2.54}, {center_y / dpi * 2.54}), 半径 (厘米): {radius_cm}")
# 可视化结果
cv2.circle(img, (center_x, center_y), radius_pixels, (0, 255, 0), 2)
cv2.circle(img, (center_x, center_y), 5, (0, 0, 255), -1)
# 显示图像
cv2.imshow("Image", img)
cv2.waitKey(0)
cv2.destroyAllWindows()
结果:
记录课堂小作业(需要数据集和代码找我要)
标签:瓶口,center,img,cv2,啤酒瓶,圆心,radius,y1,model From: https://blog.csdn.net/weixin_46943094/article/details/143406073