注:.題中附錄并沒有給出蘋果的標簽集,所以需要我們自己通過前4問得到訓練的標簽集,采用的是yolov5 7.0 版本,該版本帶分割功能
一:關于數據集的制作:
clc;
close all;
clear;
%-----這個是生成yolov5 數據集的--------
% 圖像文件夾路徑
folder_path = 'E:/新建文件夾/yatai/Attachment/Apple/';
% 圖像文件列表
image_files = dir(fullfile(folder_path, '*.jpg')); % 假設所有圖片都是jpg格式% 解析文件名中的數字,并轉換為數值類型
numbers = cellfun(@(x) sscanf(x, '%d.jpg'), {image_files.name});% 根據解析出的數字對文件列表進行排序
[~, sorted_idx] = sort(numbers);
image_files = image_files(sorted_idx);
% 存儲每張圖片蘋果數量的數組
apple_counts = zeros(length(image_files), 1);% 存儲每張圖片的平均成熟度評分
average_red_intensity_ratio_per_image = zeros(length(image_files), 1);% 確保輸出文件夾存在
output_folder = 'E:\新建文件夾\yatai\Attachment\Attachment 2\APPlemasktxt';
if ~exist(output_folder, 'dir')mkdir(output_folder);
end% 存儲每張圖片的平均蘋果質量評分
average_quality_scores_per_image = zeros(length(image_files), 1);
% 遍歷每張圖片
for i = 1: length(image_files) %2 % 讀取圖像img = imread(fullfile(folder_path, image_files(i).name));·······省略了部分代碼% 給分割的對象標記不同的標簽labelled_img = bwlabel(binary_img);
% figure;
% 在原始圖像上繪制分割結果
% imshow(img);
% hold on;colors=['b' 'g' 'r' 'c' 'm' 'y'];for k = 1:length(unique(labelled_img)) - 1boundary = bwboundaries(labelled_img == k);for b = 1:length(boundary)plot(boundary{b}(:,2), boundary{b}(:,1), colors(mod(k,length(colors))+1), 'LineWidth', 2);endend% title('Segmented Apples');% hold off;% 計數分割后的蘋果number_of_apples = max(labelled_img(:));disp(['Number of segmented apples: ', num2str(number_of_apples)]);apple_counts(i) = number_of_apples;% 打印當前圖片的蘋果數量fprintf('Image %d (%s): %d apples detected.\n', i, image_files(i).name, number_of_apples);%下面是制作分割的數據集% 給分割的對象標記不同的標簽labelled_img = bwlabel(binary_img);% 準備寫入YOLOv5格式的分割輪廓點文件% 根據圖像文件名創建對應的txt文件名baseFileName = sprintf('%d.txt', i);txt_filename = fullfile(output_folder, baseFileName);fileID = fopen(txt_filename, 'w');% 確保文件已成功打開if fileID == -1error('Cannot open file %s for writing.', txt_filename);end% 獲取圖像尺寸img_height = size(img, 1);img_width = size(img, 2);% 遍歷每個蘋果,寫入輪廓點信息for k = 1:max(labelled_img(:))[B,~] = bwboundaries(labelled_img == k, 'noholes');contours = B{1}; % 取第一組輪廓點% 檢查contours的尺寸if size(contours, 2) == 2 % 確保contours有兩列% 轉換為歸一化坐標contours_normalized = contours ./ [img_height, img_width];% 寫入文件fprintf(fileID, '0 '); % 假設蘋果的類別ID為0for p = 1:size(contours_normalized, 1)
% fprintf('Plotting point at (%f, %f)\n', contours_normalized(p, 2), contours_normalized(p, 1)); % 調試信息fprintf(fileID, '%f %f ', contours_normalized(p, 2), contours_normalized(p, 1));endfprintf(fileID, '\n');elsewarning('Contour for apple %d in image %d does not have correct dimensions.', k, i);endendfclose(fileID);end
二:關于yolov5 7.0 的訓練:
我的電腦是3080 訓練了20輪測試,下面就是部分測試的結果
下面是關于數據集的劃分代碼?
'''
Descripttion: split_img.py
version: 1.0
Author: UniDome
Date: 2022-04-20 16:28:45
LastEditors: UniDome
LastEditTime: 2022-04-20 16:39:56
'''
import os, shutil, random
from tqdm import tqdmdef split_img(img_path, label_path, split_list):try: # 創建數據集文件夾Data = 'E:/新建文件夾/yatai/Attachment/Attachment 2/output'os.mkdir(Data)train_img_dir = Data + '/images/train'val_img_dir = Data + '/images/val'test_img_dir = Data + '/images/test'train_label_dir = Data + '/labels/train'val_label_dir = Data + '/labels/val'test_label_dir = Data + '/labels/test'# 創建文件夾os.makedirs(train_img_dir)os.makedirs(train_label_dir)os.makedirs(val_img_dir)os.makedirs(val_label_dir)os.makedirs(test_img_dir)os.makedirs(test_label_dir)except:print('文件目錄已存在')train, val, test = split_listall_img = os.listdir(img_path)all_img_path = [os.path.join(img_path, img) for img in all_img]# all_label = os.listdir(label_path)# all_label_path = [os.path.join(label_path, label) for label in all_label]train_img = random.sample(all_img_path, int(train * len(all_img_path)))train_img_copy = [os.path.join(train_img_dir, img.split('\\')[-1]) for img in train_img]train_label = [toLabelPath(img, label_path) for img in train_img]train_label_copy = [os.path.join(train_label_dir, label.split('\\')[-1]) for label in train_label]for i in tqdm(range(len(train_img)), desc='train ', ncols=80, unit='img'):_copy(train_img[i], train_img_dir)_copy(train_label[i], train_label_dir)all_img_path.remove(train_img[i])val_img = random.sample(all_img_path, int(val / (val + test) * len(all_img_path)))val_label = [toLabelPath(img, label_path) for img in val_img]for i in tqdm(range(len(val_img)), desc='val ', ncols=80, unit='img'):_copy(val_img[i], val_img_dir)_copy(val_label[i], val_label_dir)all_img_path.remove(val_img[i])test_img = all_img_pathtest_label = [toLabelPath(img, label_path) for img in test_img]for i in tqdm(range(len(test_img)), desc='test ', ncols=80, unit='img'):_copy(test_img[i], test_img_dir)_copy(test_label[i], test_label_dir)def _copy(from_path, to_path):shutil.copy(from_path, to_path)def toLabelPath(img_path, label_path):img = img_path.split('\\')[-1]label = img.split('.jpg')[0] + '.txt'return os.path.join(label_path, label)def main():img_path = r'E:\新建文件夾\yatai\Attachment\Apple'label_path = r'E:\新建文件夾\yatai\Attachment\Attachment 2\APPlemasktxt'split_list = [0.7, 0.2, 0.1] # 數據集劃分比例[train:val:test]split_img(img_path, label_path, split_list)if __name__ == '__main__':main()
A題詳細代碼數據集
https://docs.qq.com/doc/DZHh5ckNrWlNybFNs