"""
BSD 3-Clause License
Copyright (c) Soumith Chintala 2016,
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of the copyright holder nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
Copyright 2020 Huawei Technologies Co., Ltd
Licensed under the BSD 3-Clause License (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
https://spdx.org/licenses/BSD-3-Clause.html
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
from torchvision import transforms
from torch.utils.data import dataset, dataloader
from torchvision.datasets.folder import default_loader
from utils.RandomErasing import RandomErasing
from utils.RandomSampler import RandomSampler, RandomSamplerDDP
import torch
from opt import opt
import os
import re
from torch.utils.data.distributed import DistributedSampler
class Data():
def __init__(self):
train_transform = transforms.Compose([
transforms.Resize((384, 128), interpolation=3),
transforms.RandomHorizontalFlip(),
transforms.ToTensor(),
transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),
RandomErasing(probability=0.5, mean=[0.0, 0.0, 0.0])
])
test_transform = transforms.Compose([
transforms.Resize((384, 128), interpolation=3),
transforms.ToTensor(),
transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
])
self.trainset = Market1501(train_transform, 'train', opt.data_path)
self.testset = Market1501(test_transform, 'test', opt.data_path)
self.queryset = Market1501(test_transform, 'query', opt.data_path)
if opt.device_num > 1:
self.train_sampler=RandomSampler(self.trainset, batch_id=opt.batchid,batch_image=opt.batchimage,
rank=opt.local_rank,world_size=opt.device_num)
self.train_loader = dataloader.DataLoader(self.trainset,
sampler=self.train_sampler,
batch_size=opt.batchid * opt.batchimage, num_workers=8,
shuffle=False,
pin_memory=True)
else:
self.train_loader = dataloader.DataLoader(self.trainset,
sampler=RandomSampler(self.trainset, batch_id=opt.batchid,
batch_image=opt.batchimage),
batch_size=opt.batchid * opt.batchimage, num_workers=8,
pin_memory=True)
self.test_loader = dataloader.DataLoader(self.testset, batch_size=opt.batchtest, num_workers=8, pin_memory=True, shuffle=False)
self.query_loader = dataloader.DataLoader(self.queryset, batch_size=opt.batchtest, num_workers=8, shuffle=False,
pin_memory=True)
if opt.mode == 'vis':
self.query_image = test_transform(default_loader(opt.query_image))
class Market1501(dataset.Dataset):
def __init__(self, transform, dtype, data_path):
self.transform = transform
self.loader = default_loader
self.data_path = data_path
if dtype == 'train':
self.data_path += '/bounding_box_train'
elif dtype == 'test':
self.data_path += '/bounding_box_test'
else:
self.data_path += '/query'
self.imgs = [path for path in self.list_pictures(self.data_path) if self.id(path) != -1]
self._id2label = {_id: idx for idx, _id in enumerate(self.unique_ids)}
def __getitem__(self, index):
path = self.imgs[index]
target = self._id2label[self.id(path)]
img = self.loader(path)
if self.transform is not None:
img = self.transform(img)
return img, target
def __len__(self):
return len(self.imgs)
@staticmethod
def id(file_path):
"""
:param file_path: unix style file path
:return: person id
"""
return int(file_path.split('/')[-1].split('_')[0])
@staticmethod
def camera(file_path):
"""
:param file_path: unix style file path
:return: camera id
"""
return int(file_path.split('/')[-1].split('_')[1][1])
@property
def ids(self):
"""
:return: person id list corresponding to dataset image paths
"""
return [self.id(path) for path in self.imgs]
@property
def unique_ids(self):
"""
:return: unique person ids in ascending order
"""
return sorted(set(self.ids))
@property
def cameras(self):
"""
:return: camera id list corresponding to dataset image paths
"""
return [self.camera(path) for path in self.imgs]
@staticmethod
def list_pictures(directory, ext='jpg|jpeg|bmp|png|ppm|npy'):
assert os.path.isdir(directory), 'dataset is not exists!{}'.format(directory)
return sorted([os.path.join(root, f)
for root, _, files in os.walk(directory) for f in files
if re.match(r'([\w]+\.(?:' + ext + '))', f)])