草莓成熟度检测数据集 3700张 草莓成熟 带标注voc yolo 3类

草莓成熟度检测数据集 3700张 草莓成熟 带标注voc yolo

草莓成熟度检测数据集

名称

草莓成熟度检测数据集 (Strawberry Maturity Detection Dataset)

规模
  • 图像数量:共3713张图像。
  • 类别:分为三个级别:未熟 (raw)、半熟 (turning) 和 成熟 (ripe)。
  • 标注个数:总共23044个标注。
数据划分
  • 训练集 (Train):通常占总数据的80%左右,约2970张图像。
  • 验证集 (Validation):通常占总数据的20%左右,约743张图像。
数据特点
  • 草莓成熟度标注:每个图像都标注了草莓的成熟度等级,便于机器学习算法进行分类。
  • 丰富的标注:每张图像可能包含多个草莓实例,且每个实例都被准确地框出。
应用领域
  • 农业自动化:帮助农民在收获时更有效地筛选不同成熟度的草莓。
  • 食品质量控制:在分拣和包装过程中实现自动化,提高生产效率。
  • 科研应用:为计算机视觉和模式识别领域的研究提供有价值的数据资源。
1. 安装依赖库

首先,确保安装了必要的依赖库。可以在项目目录中的requirements.txt文件中列出这些依赖库,然后运行以下命令进行安装:

pip install -r requirements.txt

requirements.txt 文件内容示例:

torch==1.10.0
torchvision==0.11.1
pandas==1.3.4
cv2
albumentations==1.1.0
2. 创建数据集

定义一个自定义的数据集类,并创建数据加载器。

import os
import pandas as pd
import cv2
from torch.utils.data import Dataset, DataLoader
from torchvision.transforms import Compose, ToTensor, Normalize, Resize
from albumentations import HorizontalFlip, RandomBrightnessContrast, ShiftScaleRotate, BboxFromMasks, BBoxFormatPASCAL
from albumentations.pytorch import ToTensorV2

# 自定义数据集类
class StrawberryDataset(Dataset):
    def __init__(self, data_root, annotations_file, transforms=None):
        self.data_root = data_root
        self.annotations = pd.read_csv(annotations_file)
        self.transforms = transforms

    def __len__(self):
        return len(self.annotations)

    def __getitem__(1, idx):
        img_path = os.path.join(self.data_root, self.annotations.iloc[idx, 0])
        image = cv2.imread(img_path)
        bboxes = self.annotations.iloc[idx, 1:].values.reshape(-1, 4)  # bounding box coordinates
        labels = self.annotations.columns[1:]

        if self.transforms:
            augmented = self.transforms(image=image, bboxes=bboxes)
            image = augmented['image']
            bboxes = augmented['bboxes']

        return image, bboxes, labels

# 图像预处理
def get_transforms():
    """构建预处理函数"""
    _transform = [
        Resize(height=416, width=416, interpolation=cv2.INTER_LINEAR),
        HorizontalFlip(p=0.5),
        RandomBrightnessContrast(p=0.2),
        ShiftScaleRotate(p=0.5, shift_limit=0.0625, scale_limit=0.2, rotate_limit=15),
        Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),
        ToTensorV2(),
        BboxFromMasks(format=BBoxFormatPASCAL)
    ]
    return Compose(_transform)

# 创建数据加载器
train_dataset = StrawberryDataset(
    data_root='path_to_your_train_images',
    annotations_file='path_to_your_train_annotations.csv',
    transforms=get_transforms()
)
val_dataset = StrawberryDataset(
    data_root='path_to_your_val_images',
    annotations_file='path_to_your_val_annotations.csv',
    transforms=get_transforms()
)

train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True, num_workers=4)
val_loader = DataLoader(val_dataset, batch_size=32, shuffle=False, num_workers=4)
3. 训练YOLOv5模型

使用YOLOv5进行训练。

!git clone https://github.com/ultralytics/yolov5  # 下载YOLOv5代码仓库
cd yolov5

# 使用YOLOv5训练模型
python train.py --weights yolov5s.pt --data path_to_your_data.yaml --name strawberry_maturity_detection --img 416 --batch 16 --epochs 100 --device 0
  • 数据配置文件:创建一个名为data.yaml的数据配置文件,其中包含训练和验证数据集的信息。
train: path_to_your_train_images
val: path_to_your_val_images
nc: 3
names: ['raw', 'turning', 'ripe']
4. 调整模型
  • 超参数调整:根据实际情况调整模型的超参数,例如学习率、批大小等。
  • 数据增强:增加数据增强策略,如旋转、缩放、翻转等,以提高模型鲁棒性。
5. 预测与评估

完成训练后,可以使用训练好的模型对新的图片进行预测和评估。

from models.experimental import attempt_load
from utils.datasets import ImageList
from utils.torch_utils import select_device, time_synchronized
from utils.plots import plot_results

# 加载模型
device = select_device('0')
model = attempt_load('runs/train/exp/weights/best.pt', map_location=device)  # 加载最佳权重

# 新建数据集
test_dataset = ImageList('path_to_test_images', transform=get_transforms())
test_loader = DataLoader(test_dataset, batch_size=1, shuffle=False, num_workers=4)

# 进行预测
results = []
with torch.no_grad():
    t0 = time_synchronized()
    for i, (x, path) in enumerate(test_loader):
        x = x.to(device)  # 将输入图像转换到设备上
        pred = model(x)[0]  # 获取预测结果
        results += plot_results(pred, path, save=True, show=False)  # 绘制预测结果图

print(f'Time {time_synchronized("start") - t0:.3f} s')

注意:以上代码仅供参考,请根据实际情况修改路径和参数。

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值