|
| 1 | +#!/usr/bin/env python3 |
| 2 | +import datetime |
| 3 | +import json |
| 4 | +import math |
| 5 | +import os |
| 6 | + |
| 7 | +import numpy as np |
| 8 | +import torch |
| 9 | +import torchvision.transforms as transforms |
| 10 | +from PIL import Image |
| 11 | +from torch.utils.data import Dataset |
| 12 | + |
| 13 | +normalize = transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]) |
| 14 | + |
| 15 | + |
| 16 | +class INatDataset(Dataset): |
| 17 | + def __init__(self, data, root, train, transform=None, args=None): |
| 18 | + self.transform = transform |
| 19 | + self.args = args |
| 20 | + |
| 21 | + if train: |
| 22 | + if 'mini' in data: |
| 23 | + jpath = os.path.join(root, 'train_mini.json') |
| 24 | + else: |
| 25 | + jpath = os.path.join(root, 'train.json') |
| 26 | + else: |
| 27 | + jpath = os.path.join(root, 'val.json') |
| 28 | + |
| 29 | + samples = [] |
| 30 | + with open(jpath, 'r') as f: |
| 31 | + annotations = json.loads(f) |
| 32 | + for img, ann in zip(annotations['images'], annotations['annotations']): |
| 33 | + img_path = os.path.join(root, img['file_name']) |
| 34 | + label = ann['category_id'] |
| 35 | + extra = {'date': img['date'], 'latitude': img['latitude'], 'longitude': img['longitude']} |
| 36 | + samples.append((img_path, int(label), extra)) |
| 37 | + |
| 38 | + self.samples = samples |
| 39 | + |
| 40 | + def __len__(self): |
| 41 | + return len(self.samples) |
| 42 | + |
| 43 | + def __getitem__(self, idx): |
| 44 | + img_path, label, extra = self.samples[idx] |
| 45 | + date = extra['date'] # 拍摄时间 |
| 46 | + lat = extra['latitude'] # 纬度 -90 ~ 90 |
| 47 | + lng = extra['longitude'] # 经度 -180 ~ 180 |
| 48 | + if (lat is not None) and (lng is not None) and (date is not None): |
| 49 | + date_time = datetime.datetime.strptime(date[:10], '%Y-%m-%d') |
| 50 | + date = get_scaled_date_ratio(date_time) |
| 51 | + lat = float(lat) / 90 |
| 52 | + lng = float(lng) / 180 |
| 53 | + loc = [] |
| 54 | + if 'geo' in self.args.metadata: |
| 55 | + loc += [lat, lng] |
| 56 | + if 'temporal' in self.args.metadata: |
| 57 | + loc += [date] |
| 58 | + loc = np.array(loc) |
| 59 | + loc = encode_loc_time(loc) |
| 60 | + else: |
| 61 | + loc = np.zeros(self.args.mlp_cin, float) |
| 62 | + img = Image.open(img_path) |
| 63 | + if self.transform is not None: |
| 64 | + img = self.transform(img) |
| 65 | + return img, label, loc |
| 66 | + |
| 67 | + |
| 68 | +def encode_loc_time(loc_time): |
| 69 | + # assumes inputs location and date features are in range -1 to 1 |
| 70 | + # location is lon, lat |
| 71 | + feats = np.concatenate((np.sin(math.pi * loc_time), np.cos(math.pi * loc_time))) |
| 72 | + return feats |
| 73 | + |
| 74 | + |
| 75 | +def _is_leap_year(year): |
| 76 | + if year % 4 != 0 or (year % 100 == 0 and year % 400 != 0): |
| 77 | + return False |
| 78 | + return True |
| 79 | + |
| 80 | + |
| 81 | +def get_scaled_date_ratio(date_time): |
| 82 | + r''' |
| 83 | + scale date to [-1,1] |
| 84 | + ''' |
| 85 | + days = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] |
| 86 | + total_days = 365 |
| 87 | + year = date_time.year |
| 88 | + month = date_time.month |
| 89 | + day = date_time.day |
| 90 | + if _is_leap_year(year): |
| 91 | + days[1] += 1 |
| 92 | + total_days += 1 |
| 93 | + |
| 94 | + assert day <= days[month - 1] |
| 95 | + sum_days = sum(days[:month - 1]) + day |
| 96 | + assert sum_days > 0 and sum_days <= total_days |
| 97 | + |
| 98 | + return (sum_days / total_days) * 2 - 1 |
| 99 | + |
| 100 | + |
| 101 | +def load_train_dataset(args): |
| 102 | + if args.data == 'inat17': |
| 103 | + args.num_classes = 5089 |
| 104 | + elif args.data == 'inat18': |
| 105 | + args.num_classes = 8142 |
| 106 | + elif args.data == 'inat21_mini' or 'inat21_full': |
| 107 | + args.num_classes = 10000 |
| 108 | + else: |
| 109 | + raise NotImplementedError |
| 110 | + |
| 111 | + dataset = INatDataset( |
| 112 | + args.data, |
| 113 | + root=args.data_dir, |
| 114 | + train=True, |
| 115 | + transform=transforms.Compose([ |
| 116 | + transforms.RandomResizedCrop(224), |
| 117 | + transforms.RandomHorizontalFlip(), |
| 118 | + transforms.ToTensor(), |
| 119 | + normalize, |
| 120 | + ]), |
| 121 | + args=args, |
| 122 | + ) |
| 123 | + train_loader = torch.utils.data.DataLoader( |
| 124 | + dataset, |
| 125 | + batch_size=args.batch_size, |
| 126 | + shuffle=True, |
| 127 | + num_workers=args.num_workers, |
| 128 | + pin_memory=True, |
| 129 | + ) |
| 130 | + return train_loader |
| 131 | + |
| 132 | + |
| 133 | +def load_val_dataset(args): |
| 134 | + if args.data == 'inat17': |
| 135 | + args.num_classes = 5089 |
| 136 | + elif args.data == 'inat18': |
| 137 | + args.num_classes = 8142 |
| 138 | + elif args.data == 'inat21_mini' or 'inat21_full': |
| 139 | + args.num_classes = 10000 |
| 140 | + else: |
| 141 | + raise NotImplementedError |
| 142 | + |
| 143 | + if args.tencrop: |
| 144 | + dataset = INatDataset( |
| 145 | + args.data, |
| 146 | + root=args.data_dir, |
| 147 | + train=False, |
| 148 | + transform=transforms.Compose([ |
| 149 | + transforms.Resize(256), |
| 150 | + transforms.TenCrop(224), |
| 151 | + transforms.Lambda(lambda crops: torch.stack([transforms.ToTensor()(crop) for crop in crops])), |
| 152 | + transforms.Lambda(lambda crops: torch.stack([normalize(crop) for crop in crops])), |
| 153 | + ]), |
| 154 | + args=args, |
| 155 | + ) |
| 156 | + val_loader = torch.utils.data.DataLoader( |
| 157 | + dataset, |
| 158 | + batch_size=args.batch_size, |
| 159 | + shuffle=False, |
| 160 | + num_workers=args.num_workers, |
| 161 | + pin_memory=True, |
| 162 | + ) |
| 163 | + else: |
| 164 | + dataset = INatDataset( |
| 165 | + args.data, |
| 166 | + root=args.data_dir, |
| 167 | + train=False, |
| 168 | + transform=transforms.Compose([ |
| 169 | + transforms.Resize(256), |
| 170 | + transforms.CenterCrop(224), |
| 171 | + transforms.ToTensor(), |
| 172 | + normalize, |
| 173 | + ]), |
| 174 | + args=args, |
| 175 | + ) |
| 176 | + val_loader = torch.utils.data.DataLoader( |
| 177 | + dataset, |
| 178 | + batch_size=args.batch_size, |
| 179 | + shuffle=False, |
| 180 | + num_workers=args.num_workers, |
| 181 | + pin_memory=True, |
| 182 | + ) |
| 183 | + return val_loader |
0 commit comments