我這邊主要修改的事資料集跟測試集的修改部分
資料集的修改
import os
import requests
from pathlib import Path
from tqdm.notebook import tqdm
import time
from urllib.parse import urljoin
# 定義包含映像的 GitHub 儲存庫資料夾的 URL
base_url = 'https://raw.githubusercontent.com/markl-a/objectDetectionDemo/main/dataset/IMG_'
# 定義儲存映像的本機目錄路徑
HOME = Path('')
IMAGE_DIR_PATH = HOME / 'images'
TEST_DIR_PATH = IMAGE_DIR_PATH / 'test'
TRAIN_DIR_PATH = IMAGE_DIR_PATH / 'train'
# 如果目錄不存在則建立它們
for dir_path in [IMAGE_DIR_PATH, TEST_DIR_PATH, TRAIN_DIR_PATH]:
dir_path.mkdir(parents=True, exist_ok=True)
# 生成 image URLs
image_urls = [urljoin(base_url, f"IMG_{index:04d}.jpeg") for index in range(670, 934)]
# 定義訓練集和測試集以及分割比例
train_ratio = 0.8
split_idx = int(len(image_urls) * train_ratio)
train_image_urls = image_urls[:split_idx]
test_image_urls = image_urls[split_idx:]
def download_images(image_urls, save_dir, max_retries=3):
"""下載圖像並保存到指定目錄."""
for image_url in tqdm(image_urls):
image_path = save_dir / os.path.basename(image_url)
# 重試機制
for _ in range(max_retries):
try:
with requests.get(image_url, stream=True, timeout=10) as response:
response.raise_for_status()
with open(image_path, 'wb') as f:
for chunk in response.iter_content(chunk_size=8192):
f.write(chunk)
break
except requests.RequestException as e:
print(f"Error downloading {image_url}: {e}, retrying...")
time.sleep(1)
else:
print(f"Failed to download {image_url} after {max_retries} retries.")
# 重命名 .jpeg to .jpg
if image_path.exists() and image_path.suffix == '.jpeg':
image_path.rename(image_path.with_suffix('.jpg'))
# 下載並保存訓練和測試圖像
download_images(train_image_urls, TRAIN_DIR_PATH)
download_images(test_image_urls, TEST_DIR_PATH)
# 列印訓練和測試圖像的路徑
print('Training images:', list(TRAIN_DIR_PATH.glob('*')))
print('Testing images:', list(TEST_DIR_PATH.glob('*')))
以及最後方面的使用測試集預測
import subprocess
from pathlib import Path
# 定義模型路徑和測試圖片資料夾路徑
TRAINED_MODEL_PATH = f"{HOME}/runs/detect/train/weights/best.pt"
# 遍歷測試圖片資料夾中的每張圖片
for image_path in TEST_DIR_PATH.glob("*.jpg"): # 適應圖片格式,例如 *.png, *.jpeg 等
# 建構yolo預測指令
print(f"Predicting for image: {image_path}")
cmd = f"yolo predict model={TRAINED_MODEL_PATH} source={image_path}"
# 使用subprocess運行命令
result = subprocess.run(cmd, shell=True, capture_output=True, text=True, encoding='utf-8')
# 列印命令的輸出和錯誤訊息
print("Output:", result.stdout)
print("Error:", result.stderr)
# !yolo predict model={TRAINED_MODEL_PATH} source={INPUT_VIDEO_PATH}
希望是明天能把兩個平台搞定,不過大概有點難就是了。