首先在文件yolov5文件夹内创建一个.py文件,名字就叫dataread,然后在里面加入如下代码。然后把图片文件夹放入当前目录,目录命名为data
from torch.utils.data import Dataset
import os
class MyData(Dataset):
def __init__(self, root_dir, image_dir):
self.root_dir = root_dir
self.image_dir = image_dir
self.image_path = os.path.join(self.root_dir, self.image_dir)
self.image_list = os.listdir(self.image_path)
self.image_list.sort()
def __getitem__(self, idx):
img_name = self.image_list[idx]
img_item_path = os.path.join(self.root_dir, self.image_dir, img_name)
img_item_path.replace("\\", "/")
return img_item_path
def __len__(self):
return len(self.image_list)
if __name__ == '__main__':
root_dir = ""#当前根目录,在当前文件夹就不写
image_ants = "data"#图片文件夹名字,需要跟detect.py同一个文件夹下面
ants_dataset = MyData(root_dir, image_ants)
print(ants_dataset[1])
然后在detect.py文件第一排加上
from dataread import MyData
然后在然后在detect.py文件最后
if __name__ == "__main__":里面全部改成如下
if __name__ == "__main__":
opt = parse_opt()
root_dir = ""#当前根目录,在当前文件夹就不写
image = "data"#图片文件夹名字,需要跟detect.py同一个文件夹下面
img = MyData(root_dir,image)
for i in range(len(img)):
opt.source = img[i]
main(opt)
效果如图: