一、復現YOLOV5代碼
1.github下載:https://github.com/MIPIT-Team/SSA-YOLO
2.配置環境:創建虛擬環境yolo5
conda create -n yolo5 python=3.9
#對應文件夾下pip install -r requirements.txt
報錯:ERROR: pip's dependency resolver does not currently take into account all the packages that are installed. This behaviour is the source of the following dependency conflicts.
imbalanced-learn 0.12.0 requires scikit-learn>=1.0.2, which is not installed.
imbalanced-learn 0.12.0 requires threadpoolctl>=2.0.0, which is not installed.
moviepy 1.0.3 requires imageio<3.0,>=2.5; python_version >= "3.4", which is not installed.?
解決方案:按照要求下載對應庫文件。
pip install -i https://pypi.tuna.tsinghua.edu.cn/simple " scikit-learn>=1.0.2"
pip install -i https://pypi.tuna.tsinghua.edu.cn/simple " threadpoolctl>=2.0.0"
pip install -i https://pypi.tuna.tsinghua.edu.cn/simple " imageio<3.0"&&">=2.5"
3.運行train.py,增加代碼:
os.environ["GIT_PYTHON_REFRESH"] = "quiet"
4.成功運行coco128數據集
二、訓練指定數據集--DeepPCB
1.數據集歸一化
a)明確數據集尺寸、標簽信息。本文使用DeepPCB數據集,該數據集圖片尺寸為640*640,標簽信息為左上右下兩個坐標點(絕對位置)及缺陷類型。需要將標簽信息修改為YOLOV5代碼格式(坐標點位置為相對位置):缺陷類型、中心點坐標、寬、高。--缺陷類型:1-open, 2-short, 3-mousebite, 4-spur, 5-copper, 6-pin-hole。
DeepPCB數據集:tangsanli5201/DeepPCB:一個PCB缺陷數據集。(具體閱讀對應的readme.txt)
- 根據自建數據集要求,利用trainval.txt文件生成圖片images和標簽labels文件夾。--配置1000張訓練圖。
import os
import shutildef move_files_from_txt(txt_path, img_target="./images", label_target="./labels"):"""從指定txt文件讀取路徑,移動對應圖片和標簽文件到目標文件夾參數:txt_path: 包含文件路徑的txt文件img_target: 圖片目標文件夾label_target: 標簽目標文件夾"""# 初始化統計變量success_count = 0fail_records = []# 創建目標文件夾(不存在則創建)os.makedirs(img_target, exist_ok=True)os.makedirs(label_target, exist_ok=True)print(f"圖片目標路徑: {os.path.abspath(img_target)}")print(f"標簽目標路徑: {os.path.abspath(label_target)}")try:# 讀取文件內容并處理每一行with open(txt_path, 'r', encoding='utf-8') as file:for line_num, line in enumerate(file, 1): # 記錄行號,方便定位錯誤line = line.strip() # 去除首尾空白和換行符if not line: # 跳過空行continuetry:# 分割行內容(處理可能的多空格情況)parts = line.split()if len(parts) < 2:raise ValueError("行格式不正確,至少需要兩個部分")# 構建圖片和標簽路徑img_name = f"{parts[0].split('.')[0]}_test.jpg"img_path = os.path.abspath(img_name) # 轉為絕對路徑,避免相對路徑問題label_path = os.path.abspath(parts[-1])# 檢查文件是否存在if not os.path.exists(img_path):raise FileNotFoundError(f"圖片文件不存在: {img_path}")if not os.path.exists(label_path):raise FileNotFoundError(f"標簽文件不存在: {label_path}")# 復制文件shutil.copy2(img_path, os.path.join(img_target, os.path.basename(img_path).split("_")[0]+".jpg"))shutil.copy2(label_path, os.path.join(label_target, os.path.basename(label_path)))success_count += 1print(f"已移動 [{line_num}行]: {os.path.basename(img_path)} 和 {os.path.basename(label_path)}")except Exception as e:# 記錄單行處理錯誤fail_info = f"第{line_num}行處理失敗: {str(e)}"fail_records.append(fail_info)print(fail_info)except FileNotFoundError:print(f"錯誤: 找不到txt文件 {txt_path}")returnexcept Exception as e:print(f"讀取txt文件時發生錯誤: {str(e)}")return# 輸出最終統計print("\n" + "=" * 60)print(f"處理完成: 成功移動 {success_count} 組文件")if fail_records:print(f"處理失敗 {len(fail_records)} 組文件,詳情如下:")for info in fail_records:print(f"- {info}")if __name__ == "__main__":# 配置路徑txt_file_path = "./trainval.txt" # 源txt文件路徑images_folder = "./images" # 圖片目標文件夾labels_folder = "./labels" # 標簽目標文件夾# 執行移動操作move_files_from_txt(txt_file_path, images_folder, labels_folder)
- 將標簽信息更改為標準形式:類別、中心點坐標、寬、高。--相對位置
import osdef convert_to_yolo_format(input_dir, output_dir=None, image_width=640, image_height=640):"""批量轉換標注文件格式為YOLO格式參數:input_dir: 包含原始txt標注文件的目錄output_dir: 轉換后文件的保存目錄,默認與輸入目錄相同image_width: 圖像寬度,默認640image_height: 圖像高度,默認640"""# 如果未指定輸出目錄,則使用輸入目錄if output_dir is None:output_dir = input_direlse:# 創建輸出目錄(如果不存在)os.makedirs(output_dir, exist_ok=True)# 統計變量total_files = 0total_lines = 0error_files = []# 遍歷輸入目錄中的所有txt文件for filename in os.listdir(input_dir):if filename.endswith('.txt'):total_files += 1input_path = os.path.join(input_dir, filename)output_path = os.path.join(output_dir, filename)try:with open(input_path, 'r', encoding='utf-8') as infile, \open(output_path, 'w', encoding='utf-8') as outfile:for line_num, line in enumerate(infile, 1):line = line.strip()if not line: # 跳過空行continuetotal_lines += 1# 分割行內容(格式為:x1 y1 x2 y2 class)parts = line.split()if len(parts) != 5:raise ValueError(f"格式錯誤,預期5個值,實際{len(parts)}個值")# 解析坐標和類別x1, y1, x2, y2, cls = parts# 轉換為浮點數try:x1 = float(x1)y1 = float(y1)x2 = float(x2)y2 = float(y2)except ValueError:raise ValueError("坐標值必須為數字")# 計算YOLO格式所需的參數center_x = (x1 + x2) / 2.0 / image_width # 中心點x坐標(歸一化)center_y = (y1 + y2) / 2.0 / image_height # 中心點y坐標(歸一化)width = (x2 - x1) / image_width # 寬度(歸一化)height = (y2 - y1) / image_height # 高度(歸一化)# 確保值在[0, 1]范圍內center_x = max(0.0, min(1.0, center_x))center_y = max(0.0, min(1.0, center_y))width = max(0.0, min(1.0, width))height = max(0.0, min(1.0, height))# 寫入轉換后的數據(保留6位小數)outfile.write(f"{cls} {center_x:.6f} {center_y:.6f} {width:.6f} {height:.6f}\n")print(f"已轉換: {filename}")except Exception as e:error_msg = f"處理文件 {filename} 時出錯: {str(e)}"print(error_msg)error_files.append(error_msg)# 輸出統計信息print("\n" + "=" * 60)print(f"轉換完成: 共處理 {total_files} 個文件,{total_lines} 行標注")if error_files:print(f"處理失敗 {len(error_files)} 個文件:")for err in error_files:print(f"- {err}")if __name__ == "__main__":# 配置輸入輸出目錄input_directory = "./labels" # 包含原始標注文件的目錄output_directory = "./labels-c" # 轉換后文件的保存目錄# 執行轉換convert_to_yolo_format(input_dir=input_directory,output_dir=output_directory,image_width=640,image_height=640)
b)將數據集文件放在與YOLOV5文件同一級的datasets中(./datasets/DeepPCB),生成PCBData.yaml(./data)文件。
# Train/val/test sets as 1) dir: path/to/imgs, 2) file: path/to/imgs.txt, or 3) list: [path/to/imgs1, path/to/imgs2, ..]
path: ../datasets/DeepPCB # dataset root dir
train: images/train2025 # train images (relative to 'path') 128 images
val: images/train2025 # val images (relative to 'path') 128 images
test: # test images (optional)# Classes
names:0: background1: open2: short3: mousebite4: spur5: copper6: pin-hole
2.運行train.py
建議:worker默認值修改為0。
利用Pycharm運行時出現閃退情況:IDE error occured。
解決方案:IDEA 性能優化設置。
打開vmoptions,做出如下修改。