啤酒瓶瓶口检测及其圆心坐标与半径计算

第一步利用 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()

结果:

886a31c68844437c979d6e0b45dd8c50.png

 记录课堂小作业(需要数据集和代码找我要)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值