├── .gitignore ├── requirements.txt ├── setup_script_part1.sh ├── setup_script_part2.sh ├── roadpoints.py ├── README.md ├── websample.py ├── heatmap.py ├── LICENSE └── scenes.py /.gitignore: -------------------------------------------------------------------------------- 1 | *~ 2 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | pytorch 2 | numpy 3 | scikit-image 4 | pandas 5 | torchvision 6 | matplotlib 7 | tqdm 8 | tensorboard 9 | gdal 10 | geopandas 11 | -------------------------------------------------------------------------------- /setup_script_part1.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | # Folders 4 | mkdir data 5 | mkdir weights 6 | 7 | # Places2 weights 8 | wget http://places2.csail.mit.edu/models_places365/alexnet_places365.pth.tar -O weights/alexnet_surface.pth.tar 9 | wget http://places2.csail.mit.edu/models_places365/densenet161_places365.pth.tar -O weights/densenet161_surface.pth.tar 10 | 11 | # Code 12 | git clone https://github.com/IQTLabs/Ukraine_Geolocation.git code 13 | cd code 14 | wget https://raw.githubusercontent.com/CSAILVision/places365/master/categories_places365.txt 15 | 16 | # Python environment 17 | conda create --name geoloc --file requirements.txt 18 | -------------------------------------------------------------------------------- /setup_script_part2.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | # Extracting CrossView USA 4 | cd data 5 | tar -xf flickr.tar 6 | tar -xf flickr_aerial.tar 7 | tar -xf streetview.tar 8 | tar -xf streetview_aerial.tar 9 | tar -xf metadata.tar 10 | 11 | # File list 12 | cat flickr_images.txt streetview_images.txt > all_images.txt 13 | 14 | # Preprocessing 15 | cd ../code 16 | conda activate geoloc 17 | python -c "from scenes import *; preprocess('../data/all_images.txt', '../data/preprocessed', view='surface')" 18 | 19 | # Reorganizing folders 20 | cd ../data 21 | mv flickr flickr_orig 22 | mv streetview streetview_orig 23 | mv preprocessed/flickr flickr 24 | mv preprocessed/streetview streetview 25 | ln -s flickr_aerial flickr_aerial_full 26 | ln -s streetview_aerial streetview_aerial_full 27 | rmdir preprocessed 28 | -------------------------------------------------------------------------------- /roadpoints.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | import argparse 4 | import osmnx as ox 5 | import pandas as pd 6 | 7 | def download(location, network_path): 8 | graph = ox.graph_from_place(location, network_type='all_private') 9 | ox.save_graphml(graph, filepath=network_path) 10 | 11 | 12 | def points(network_path, points_path, num): 13 | print('0') 14 | graph = ox.load_graphml(network_path) 15 | print('1') 16 | graph = ox.project_graph(graph) 17 | print('2') 18 | graph = ox.get_undirected(graph) 19 | print('3') 20 | points = ox.utils_geo.sample_points(graph, n=num) 21 | graph = None 22 | print('4') 23 | points = points.to_crs('EPSG:4326') 24 | print('5') 25 | points = pd.concat([points.y, points.x], axis=1) 26 | print('6') 27 | points.to_csv(points_path, sep=',', header=False, index=False) 28 | 29 | 30 | if __name__ == '__main__': 31 | parser = argparse.ArgumentParser() 32 | parser.add_argument('-d', '--download', action='store_true', 33 | help='Download street network') 34 | parser.add_argument('-p', '--points', action='store_true', 35 | help='Select random points') 36 | parser.add_argument('-n', '--num', type=int, default=1000000, 37 | help='Number of points to select') 38 | parser.add_argument('-l', '--location', default='Ukraine', 39 | help='Name of location') 40 | parser.add_argument('-x', '--network', default='./ukraine.gpkg', 41 | help='Path to road network file') 42 | parser.add_argument('-o', '--output', default='./points.csv', 43 | help='Path to points file') 44 | args = parser.parse_args() 45 | if args.download: 46 | download(args.location, args.network) 47 | if args.points: 48 | points(args.network, args.output, args.num) 49 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Ukraine Geolocation 2 | 3 | The code in this repo uses deep learning to try to geolocate photographs (such as from social media) by comparison to satellite imagery. The same trained model can be used for neighborhood-scale or national-scale geolocation. This code is used in [Deep Geolocation with Satellite Imagery of Ukraine](https://www.iqt.org/deep-geolocation-with-satellite-imagery-of-ukraine/). 4 | 5 | ## Setup & Training 6 | 7 | Download the two setup scripts, then run the first setup script: 8 | ``` 9 | ./setup_script_part1.sh 10 | ``` 11 | 12 | Download CVUSA tar files into the "data" folder. To get these files, follow instructions [here](https://mvrl.cse.wustl.edu/datasets/cvusa/). 13 | 14 | Run the second setup script: 15 | ``` 16 | ./setup_script_part2.sh 17 | ``` 18 | 19 | Train the model: 20 | ``` 21 | # In Python (run within code/ folder) 22 | from scenes import * 23 | extract_features('../data/all_images.txt', 24 | '../data/all_surface.pkl', 25 | view='surface', rule='cvusa', 26 | populate_latlon=True) 27 | train('../data/all_surface.pkl', 28 | view='overhead', rule='cvusa', arch='densenet161', batch_size=128) 29 | ``` 30 | Press Ctrl+c to end training. 31 | 32 | ## Neighborhood-Scale Geolocation 33 | 34 | To see all syntax options: 35 | ``` 36 | ./heatmap.py -h 37 | ``` 38 | 39 | ### Usage Example 40 | 41 | Save a file called `photo_paths.csv`, containing paths to ground-level photographs, one per line. Let `LINE_NUM` be the line with the photo you want to use. Then in the command below, change the projection (here, UTM 36N) and bounds (here, centered on Bucha/Irpin) as needed. Note: This is an example only; the repo does not include photos or satellite imagery. 42 | ``` 43 | ./heatmap.py --projection 32636 --bounds 300211 5598433 306475 5604575 --satpath SATELLITE_PHOTO.tif --photopath photo_paths.csv --csvpath OUTPUT_FILE_NAME.csv --row LINE_NUM --match --arch densenet161 --offset 10 44 | ``` 45 | 46 | ## National-Scale Geolocation 47 | 48 | To see all syntax options: 49 | ``` 50 | ./websample.py -h 51 | ``` 52 | 53 | ### Usage Example 54 | 55 | Run `roadpoints` to get a list of random geographic points, then run `websample` to get a feature vector for each point, then use the `score_file` Python function to compare a photo to those feature vectors, as shown below. 56 | Note: This requires your Bing Maps API key saved to a file at `PATH_TO_KEY`. 57 | ``` 58 | ./roadpoints.py --output points.csv 59 | ./websample.py --input points.csv --output features.csv --tempdir TEMPORARY_DIRECTORY --arch densenet161 --pause 10 --num 10000 -k PATH_TO_KEY 60 | ``` 61 | Letting `photo_paths.csv` and `LINE_NUM` have the same meaning as in the previous usage example: 62 | ``` 63 | # In Python: (run within code/ folder) 64 | from scenes import * 65 | score_file('features.csv', 66 | 'scores.csv', 67 | 'photo_paths.csv', LINE_NUM) 68 | ``` 69 | The file `scores.csv` will show how well each point matches the selected photo. In this file, 2nd column is latitude, 3rd column is longitude, and 4th column is score. Score is the negative of the feature space distance. 70 | 71 | ## Credits 72 | 73 | `scenes.py` is derived from [`cvig_fov.py`](https://github.com/IQTLabs/WITW/blob/main/model/cvig_fov.py). `heatmap.py` is derived from [`heatmap.py`](https://github.com/IQTLabs/WITW/blob/main/tools/heatmap/heatmap.py). The files in this repo are released under the same license (Apache 2.0) as those source files. 74 | -------------------------------------------------------------------------------- /websample.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | import argparse 4 | import subprocess 5 | from PIL import Image 6 | import time 7 | import tqdm 8 | 9 | from scenes import * 10 | 11 | def web_features(input_file, output_file, temp_dir, view, arch, suffix, num, backup_interval, pause, key): 12 | """ 13 | Given a dataset file with latitude/longitude, generate 14 | feature vectors using imagery from an API. 15 | """ 16 | # Get key value from key path 17 | with open(key, 'r') as keyfile: 18 | key = keyfile.read().rstrip() 19 | 20 | # Load model and dataset 21 | transform = get_transform(view, preprocess=False, finalprocess=True) 22 | model = load_model(view, arch, suffix).to(device) 23 | dataset = OneDataset(input_file, view) 24 | if num > 0: 25 | dataset.df = dataset.df[:num] 26 | dataset.paths_relative = dataset.paths_relative[:num] 27 | dataset.df = pd.concat([dataset.df.iloc[:, :3], pd.DataFrame(np.zeros((len(dataset.df), 365), dtype=np.float32))], axis=1) 28 | 29 | # Loop through geotags 30 | for i in tqdm.tqdm(range(len(dataset))): 31 | lat = dataset.df.iloc[i]['lat'] 32 | lon = dataset.df.iloc[i]['lon'] 33 | filepath = os.path.join(temp_dir, 'image_' + lat + '_' + lon + '.jpg') 34 | 35 | # Download image 36 | if not os.path.exists(filepath): 37 | if pause > 0: 38 | time.sleep(pause) 39 | cmd = 'wget -O ' + filepath + ' "https://dev.virtualearth.net/REST/v1/Imagery/Map/Aerial/' + lat + ',' + lon + '/18?mapSize=800,800&key=' + key + '"' 40 | subprocess.check_output(cmd, shell=True) 41 | 42 | # Extract feature vector 43 | image = Image.open(filepath) 44 | if image.mode != 'RGB': 45 | image = image.convert('RGB') 46 | image = transform(image).to(device) 47 | featvec = model(image.unsqueeze(0)).squeeze() 48 | dataset.df.iloc[i, 3:] = featvec.cpu().detach().numpy() 49 | 50 | # Delete image 51 | cmd = 'rm -v ' + filepath + ' 1>&2' 52 | subprocess.check_output(cmd, shell=True) 53 | 54 | # Backup feature vectors at regular intervals 55 | if (i + 1) % backup_interval == 0: 56 | backup_file = os.path.splitext(os.path.basename(output_file))[0] \ 57 | + '_backup' + str(i+1) \ 58 | + os.path.splitext(os.path.basename(output_file))[1] 59 | backup_path = os.path.join(temp_dir, backup_file) 60 | dataset.save(backup_path) 61 | 62 | # Save output 63 | dataset.save(output_file) 64 | 65 | 66 | if __name__ == '__main__': 67 | parser = argparse.ArgumentParser() 68 | parser.add_argument('-i', '--input', 69 | default='../points/points_formatted.txt', 70 | help='Path to input dataset file, with lat/lon') 71 | parser.add_argument('-o', '--output', 72 | default='../points/points_features.txt', 73 | help='Path to output dataset file, with features') 74 | parser.add_argument('-t', '--tempdir', 75 | default='../points/temp', 76 | help='Path to directory for backup files') 77 | parser.add_argument('-v', '--view', 78 | default='overhead', 79 | help='View: surface or overhead') 80 | parser.add_argument('-a', '--arch', 81 | default='alexnet', 82 | help='Model architecture') 83 | parser.add_argument('-s', '--suffix', 84 | default=None, 85 | help='Suffix of model weights file name') 86 | parser.add_argument('-n', '--num', 87 | type=int, default=0, 88 | help='How many dataset point to use, or 0 for all') 89 | parser.add_argument('-b', '--backup', 90 | type=int, default=1000, 91 | help='Number of images between backups') 92 | parser.add_argument('-p', '--pause', 93 | type=float, default=0., 94 | help='Pause between API calls') 95 | parser.add_argument('-k', '--key', 96 | default='key', 97 | help='Path to API key') 98 | args = parser.parse_args() 99 | web_features(args.input, args.output, args.tempdir, args.view, args.arch, args.suffix, args.num, args.backup, args.pause, args.key) 100 | -------------------------------------------------------------------------------- /heatmap.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | import argparse 4 | import subprocess 5 | from osgeo import osr 6 | from osgeo import gdal 7 | 8 | from scenes import * 9 | 10 | 11 | class TileDataset(torch.utils.data.Dataset): 12 | def __init__(self, source, windows, transform=None): 13 | self.source = source 14 | self.windows = windows 15 | self.transform = transform 16 | def __len__(self): 17 | return len(self.windows) 18 | def __getitem__(self, idx): 19 | mem_path = '/vsimem/tile%s.jpg' % str(idx) 20 | ds = gdal.Translate(mem_path, self.source, projWin=self.windows[idx]) 21 | raw = ds.ReadAsArray() 22 | gdal.GetDriverByName('GTiff').Delete(mem_path) 23 | image = torch.from_numpy(raw.astype(np.float32)/255.) 24 | data = {'image':image} 25 | if self.transform is not None: 26 | data['image'] = self.transform(data['image']) 27 | return data 28 | 29 | 30 | def sweep(sat_path, bounds, projection, edge, offset, 31 | photo_path, photo_row, csv_path, match, 32 | tensor_path, arch, suffix): 33 | 34 | # Compute center and window for each satellite tile 35 | center_eastings = [] 36 | center_northings = [] 37 | windows = [] 38 | e2 = edge / 2. 39 | for easting in np.arange(bounds[0] - e2, bounds[2] - e2, offset): 40 | for northing in np.arange(bounds[3] + e2, bounds[1] + e2, -offset): 41 | center_eastings.append(easting + e2) 42 | center_northings.append(northing - e2) 43 | windows.append([easting, northing, easting + edge, northing - edge]) 44 | 45 | # Load satellite strip 46 | sat_file = gdal.Open(sat_path) 47 | 48 | # Specify transformations 49 | surface_transform = get_transform('surface', preprocess=False, finalprocess=True, augment=False, already_tensor=False) 50 | overhead_transform = get_transform('overhead', preprocess=False, finalprocess=True, augment=False, already_tensor=True) 51 | 52 | # Load data 53 | surface_set = OneDataset(photo_path, view='surface', rule=None, 54 | transform=surface_transform) 55 | overhead_set = TileDataset(sat_file, windows, overhead_transform) 56 | surface_batch = torch.unsqueeze(surface_set[photo_row]['image'], 57 | dim=0).to(device) 58 | overhead_loader = torch.utils.data.DataLoader(overhead_set, batch_size=64, 59 | shuffle=False, num_workers=1) 60 | 61 | # Load the neural networks 62 | surface_model = load_model('surface').to(device) 63 | overhead_model = load_model('overhead', arch, suffix).to(device) 64 | # if device_parallel and torch.cuda.device_count() > 1: 65 | # surface_model = torch.nn.DataParallel( 66 | # surface_model, device_ids=device_ids) 67 | # overhead_model = torch.nn.DataParallel( 68 | # overhead_model, device_ids=device_ids) 69 | torch.set_grad_enabled(False) 70 | 71 | # Surface photo's features 72 | surface_vector = surface_model(surface_batch) 73 | 74 | # Describe surface image 75 | if match: 76 | # Load scenes 77 | scene_path = 'categories_places365.txt' 78 | scene_list = pd.read_csv(scene_path, sep=' ', header=None, 79 | names=['scene'], usecols=[0])['scene'].tolist() 80 | 81 | # Print best scene matches for surface image 82 | probs = torch.nn.functional.softmax(surface_vector.squeeze(), 0) 83 | df = pd.DataFrame({'scene': scene_list, 'prob': probs.cpu().numpy()}) 84 | df.sort_values('prob', ascending=False, inplace=True) 85 | df.reset_index(drop=True, inplace=True) 86 | print(surface_set[photo_row]['path_absolute']) 87 | print(df[:5]) 88 | 89 | # Overhead images' features 90 | if tensor_path is not None and os.path.exists(tensor_path): 91 | feat_vecs = torch.load(tensor_path) 92 | else: 93 | feat_vecs = None 94 | for batch, data in enumerate(tqdm.tqdm(overhead_loader)): 95 | images = data['image'].to(device) 96 | feat_vecs_part = overhead_model(images) 97 | if feat_vecs is None: 98 | feat_vecs = feat_vecs_part 99 | else: 100 | feat_vecs = torch.cat((feat_vecs, feat_vecs_part), dim=0) 101 | torch.save(feat_vecs, tensor_path) 102 | 103 | # Calculate score for each overhead image 104 | distance_func = WeightedPairwiseDistance().to(device) 105 | distances = distance_func(feat_vecs, surface_vector) 106 | 107 | # Find best scene match for each overhead image 108 | if match: 109 | match_indices = feat_vecs.argmax(dim=1).cpu().numpy() 110 | match_names = [scene_list[i] for i in match_indices] 111 | 112 | # Save information to disk 113 | df = pd.DataFrame({ 114 | 'x': center_eastings, 115 | 'y': center_northings, 116 | 'similar': -distances.cpu().detach().numpy(), 117 | }) 118 | if match: 119 | df['match'] = match_names 120 | path_out_csv = os.path.splitext(csv_path)[0] + '.csv' 121 | path_out_shp = os.path.splitext(csv_path)[0] + '.shp' 122 | path_out_tif = os.path.splitext(csv_path)[0] + '.tif' 123 | df.to_csv(path_out_csv, index=False) 124 | cmd = 'ogr2ogr -s_srs EPSG:' + str(projection) + ' -t_srs EPSG:' + str(projection) + ' -oo X_POSSIBLE_NAMES=x -oo Y_POSSIBLE_NAMES=y -f "ESRI Shapefile" ' + path_out_shp + ' ' + path_out_csv 125 | print(cmd) 126 | subprocess.check_output(cmd, shell=True) 127 | cmd = 'gdal_rasterize -a similar -tr ' + str(offset) + ' ' + str(offset) + ' -a_nodata 0.0 -te ' + ' '.join([str(x) for x in bounds]) + ' -ot Float32 -of GTiff ' + path_out_shp + ' ' + path_out_tif 128 | print(cmd) 129 | subprocess.check_output(cmd, shell=True) 130 | 131 | 132 | def layer(sat_path, bounds, layer_path): 133 | sat_file = gdal.Open(sat_path) 134 | window = [bounds[0], bounds[3], bounds[2], bounds[1]] 135 | gdal.Translate(layer_path, sat_file, projWin=window) 136 | 137 | 138 | if __name__ == '__main__': 139 | parser = argparse.ArgumentParser() 140 | parser.add_argument('-s', '--satpath', 141 | default='satellite.tif', 142 | help='Path to input satellite image') 143 | parser.add_argument('-b', '--bounds', 144 | type=float, 145 | nargs=4, 146 | default=(305541, 5541833, 311833, 5548133), 147 | metavar=('left', 'bottom', 'right', 'top'), 148 | help='Bounds given as UTM coordinates in this order: min easting, min northing, max easting, max northing') 149 | parser.add_argument('-j', '--projection', 150 | type=int, 151 | default=32637, 152 | help='EPSG Projection') 153 | parser.add_argument('-e', '--edge', 154 | type=float, 155 | default=368, 156 | help='Edge length of satellite imagery tiles [m]') 157 | parser.add_argument('-o', '--offset', 158 | type=float, 159 | default=25, 160 | help='Offset between centers of adjacent satellite imagery tiles [m]') 161 | parser.add_argument('-p', '--photopath', 162 | default='./images.csv', 163 | help='Path to surface photo dataset CSV file') 164 | parser.add_argument('-r', '--row', 165 | type=int, 166 | default=0, 167 | help='Row of surface photo within CSV file') 168 | parser.add_argument('-c', '--csvpath', 169 | default='./geomatch.csv', 170 | help='Path to output CSV file') 171 | parser.add_argument('-l', '--layerpath', 172 | default='./satlayer.tif', 173 | help='Path to output cropped satellite image') 174 | parser.add_argument('-i', '--image', 175 | action='store_true', 176 | help='Flag to output cropped satellite image') 177 | parser.add_argument('-g', '--gpu', 178 | type=int, 179 | default=None, 180 | help='Which GPU to use') 181 | parser.add_argument('-m', '--match', 182 | action='store_true', 183 | help='Flag to include best scene matches in CSV file') 184 | parser.add_argument('-t', '--tensorpath', 185 | default=None, 186 | help='Optional file path to save/reuse overhead image features. Delete this file before running with changed settings.') 187 | parser.add_argument('-a', '--arch', 188 | default='alexnet', 189 | help='Model architecture') 190 | parser.add_argument('-x', '--suffix', 191 | default=None, 192 | help='Suffix of model weights file name') 193 | args = parser.parse_args() 194 | if args.gpu is not None: 195 | cvig.device = torch.device('cuda:' + str(args.gpu)) 196 | device = torch.device('cuda:' + str(args.gpu)) 197 | sweep(args.satpath, args.bounds, args.projection, args.edge, args.offset, 198 | args.photopath, args.row, args.csvpath, args.match, args.tensorpath, 199 | args.arch, args.suffix) 200 | if args.image: 201 | layer(args.satpath, args.bounds, args.layerpath) 202 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /scenes.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | import os 4 | import math 5 | import time 6 | import tqdm 7 | import torch 8 | import torchvision 9 | import numpy as np 10 | import pandas as pd 11 | from PIL import Image 12 | 13 | device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu') 14 | device_parallel = True 15 | device_ids = None 16 | 17 | class OneDataset(torch.utils.data.Dataset): 18 | """ 19 | Dataset for a single view (surface or overhead) 20 | Input file format is: 21 | path[,latitude,longitude[,feature_vector_components]] 22 | where brackets denote optional entries 23 | """ 24 | def __init__(self, input_file, view='surface', zoom=18, rule='cvusa', full=True, transform=None): 25 | self.input_file = input_file 26 | self.view = view # surface, overhead 27 | self.zoom = zoom # 18, 16, 14 28 | self.rule = rule # cvusa, witw, gtcrossview, None 29 | self.transform = transform 30 | fstr = '_full' if full else '' 31 | 32 | # Load entries from input file 33 | if os.path.splitext(self.input_file)[1].lower() \ 34 | in ['.csv', '.txt', '.asc', '.ascii']: 35 | typedict = {0:'string', 1:'string', 2:'string'} 36 | for i in range(3, 3+365): 37 | typedict[i] = 'float32' 38 | self.df = pd.read_csv(self.input_file, header=None, 39 | dtype=typedict, keep_default_na=False) 40 | self.df.rename(columns={0:'path', 1:'lat', 2:'lon'}, inplace=True) 41 | else: 42 | self.df = pd.read_pickle(self.input_file) 43 | if 'lat' not in self.df: 44 | self.df['lat'] = None 45 | if 'lon' not in self.df: 46 | self.df['lon'] = None 47 | 48 | # Create series with true relative file paths 49 | self.input_dir = os.path.split(self.input_file)[0] 50 | self.paths_relative = self.df['path'] 51 | if self.view == 'overhead' and self.rule in ['cvusa', 'cw', 'cgw']: 52 | # Convert CVUSA streetview surface path to overhead path 53 | self.paths_relative = self.paths_relative.str.replace( 54 | 'streetview/cutouts', 'streetview_aerial' + fstr + '/' + str(self.zoom), 55 | n=1, regex=False) 56 | self.paths_relative = self.paths_relative.str.replace( 57 | '_90.jpg', '.jpg', n=1, regex=False) 58 | self.paths_relative = self.paths_relative.str.replace( 59 | '_270.jpg', '.jpg', n=1, regex=False) 60 | # Convert CVUSA flickr surface path to overhead path 61 | self.paths_relative = self.paths_relative.str.replace( 62 | 'flickr', 'flickr_aerial' + fstr + '/' + str(self.zoom), 63 | n=1, regex=False) 64 | self.paths_relative = self.paths_relative.str.replace( 65 | r'[0-9]+@N[0-9]+_[0-9]+_', '', n=1, regex=True) 66 | self.paths_relative = self.paths_relative.str.replace( 67 | '.png', '.jpg', n=1, regex=False) 68 | if self.view == 'overhead' and self.rule in ['witw', 'cw', 'cgw']: 69 | # Convert WITW surface path to overhead path 70 | self.paths_relative = self.paths_relative.str.replace( 71 | 'surface', 'overhead' + fstr, n=1, regex=False) 72 | if self.view == 'overhead' and self.rule in ['gtcrossview', 'cgw']: 73 | # Convert GTCrossView surface path to overhead path 74 | self.paths_relative = self.paths_relative.str.replace( 75 | '.streetview', '.overhead', n=1, regex=False) 76 | 77 | def __len__(self): 78 | return len(self.df) 79 | 80 | def __getitem__(self, idx): 81 | data = {} 82 | data['idx'] = idx 83 | data['path_csv'] = self.input_dir 84 | data['path_listed'] = self.df.iloc[idx]['path'] 85 | data['path_relative'] = self.paths_relative[idx] 86 | data['path_absolute'] = os.path.join(data['path_csv'], 87 | data['path_relative']) 88 | 89 | if len(self.df.columns) > 3: 90 | data['vector'] = torch.tensor(self.df.iloc[idx, 3:].values.astype('float32')) 91 | 92 | data['image'] = Image.open(data['path_absolute']) 93 | if data['image'].mode != 'RGB': 94 | data['image'] = data['image'].convert('RGB') 95 | if self.transform is not None: 96 | data['image'] = self.transform(data['image']) 97 | 98 | return data 99 | 100 | def save(self, output_file): 101 | if os.path.splitext(output_file)[1].lower() \ 102 | in ['.csv', '.txt', '.asc', '.ascii']: 103 | self.df.to_csv(output_file, header=False, index=False) 104 | else: 105 | self.df.to_pickle(output_file) 106 | 107 | def populate_latlon(self): 108 | """ 109 | Populate latitude and longitude columns from path column. 110 | This only works if entries follow format of CVUSA dataset. 111 | """ 112 | def select_fields(s): 113 | l = s.split('_') 114 | if len(l) == 3: 115 | return '_'.join(l[:2]) 116 | if len(l) == 4: 117 | return '_'.join(l[2:]) 118 | else: 119 | raise Exception('! Invalid string in populate_latlon().') 120 | names = self.df['path'].apply(lambda x: os.path.splitext(os.path.split(x)[1])[0]) 121 | strings = names.apply(select_fields) 122 | self.df[['lat', 'lon']] = strings.str.split('_', expand=True) 123 | 124 | 125 | class QuadRotation(object): 126 | def __call__(self, data): 127 | factor = torch.randint(4, ()).item() 128 | data = torch.rot90(data, factor, [-2, -1]) 129 | return data 130 | 131 | 132 | def get_transform_highres(view='surface', preprocess=True, finalprocess=True, augment=False, already_tensor=False): 133 | """ 134 | Return image transform 135 | """ 136 | transforms = [] 137 | if preprocess: 138 | transforms.append(torchvision.transforms.Resize((256,256))) 139 | if finalprocess: 140 | if not augment: 141 | if view == 'surface': 142 | transforms.append(torchvision.transforms.Resize((224,224))) 143 | elif view == 'overhead': 144 | #transforms.append(torchvision.transforms.Resize((800,800))) 145 | transforms.append(torchvision.transforms.CenterCrop(224)) 146 | else: # augmentation 147 | if view == 'surface': 148 | transforms.append(torchvision.transforms.RandomResizedCrop(224)) 149 | elif view == 'overhead': 150 | transforms.append(torchvision.transforms.Resize((800,800))) 151 | transforms.append(torchvision.transforms.CenterCrop(364)) 152 | transforms.append(torchvision.transforms.RandomRotation((0,360), interpolation=torchvision.transforms.InterpolationMode.BILINEAR)) 153 | transforms.append(torchvision.transforms.CenterCrop(256)) 154 | transforms.append(torchvision.transforms.RandomResizedCrop(224, scale=(0.8, 1.))) 155 | transforms.append(torchvision.transforms.RandomHorizontalFlip()) 156 | if not already_tensor: 157 | transforms.append(torchvision.transforms.ToTensor()) 158 | transforms.append(torchvision.transforms.Normalize( 159 | [0.485, 0.456, 0.406], [0.229, 0.224, 0.225])) 160 | transform = torchvision.transforms.Compose(transforms) 161 | return transform 162 | 163 | 164 | def get_transform_lowres(view='surface', preprocess=True, finalprocess=True, augment=False, already_tensor=False): 165 | """ 166 | Return image transform 167 | """ 168 | transforms = [] 169 | if preprocess: 170 | transforms.append(torchvision.transforms.Resize((256,256))) 171 | if finalprocess: 172 | if not augment: 173 | transforms.append(torchvision.transforms.Resize((224,224))) 174 | #transforms.append(torchvision.transforms.CenterCrop(224)) 175 | else: # augmentation 176 | transforms.append(torchvision.transforms.RandomHorizontalFlip()) 177 | if view == 'surface': 178 | transforms.append(torchvision.transforms.RandomResizedCrop(224)) 179 | elif view == 'overhead': 180 | transforms.append(torchvision.transforms.RandomRotation((0,360), interpolation=torchvision.transforms.InterpolationMode.BILINEAR)) 181 | transforms.append(torchvision.transforms.RandomResizedCrop(224, scale=(0.25, 1.))) 182 | if not already_tensor: 183 | transforms.append(torchvision.transforms.ToTensor()) 184 | transforms.append(torchvision.transforms.Normalize( 185 | [0.485, 0.456, 0.406], [0.229, 0.224, 0.225])) 186 | transform = torchvision.transforms.Compose(transforms) 187 | return transform 188 | 189 | 190 | get_transform = get_transform_highres 191 | 192 | 193 | def load_model(view='surface', arch='alexnet', suffix=None): 194 | """ 195 | Based on https://github.com/CSAILVision/places365/blob/master/run_placesCNN_basic.py by Bolei Zhou 196 | """ 197 | model = torchvision.models.__dict__[arch](num_classes=365) 198 | if view is not None: 199 | if suffix is None: 200 | model_path = '../weights/%s_%s.pth.tar' % (arch, view) 201 | else: 202 | model_path = '../weights/%s_%s_%s.pth.tar' % (arch, view, suffix) 203 | checkpoint = torch.load( 204 | model_path, map_location=lambda storage, loc: storage) 205 | state_dict = {str.replace(k,'module.',''): v 206 | for k,v in checkpoint['state_dict'].items()} 207 | if arch == 'densenet161': 208 | state_dict = {str.replace(k,'norm.1','norm1'): v 209 | for k,v in state_dict.items()} 210 | state_dict = {str.replace(k,'norm.2','norm2'): v 211 | for k,v in state_dict.items()} 212 | state_dict = {str.replace(k,'conv.1','conv1'): v 213 | for k,v in state_dict.items()} 214 | state_dict = {str.replace(k,'conv.2','conv2'): v 215 | for k,v in state_dict.items()} 216 | model.load_state_dict(state_dict) 217 | model.eval() 218 | return model 219 | 220 | 221 | def preprocess(input_file, output_dir, view='surface', rule='cvusa', 222 | tar_file=None, tar_delete=None): 223 | """ 224 | Preprocess images (resize and crop, if applicable), 225 | saving output to a new folder. 226 | """ 227 | transform = get_transform(view, preprocess=True, finalprocess=False) 228 | dataset = OneDataset(input_file, view=view, rule=rule, transform=transform) 229 | if tar_file is not None: 230 | import subprocess 231 | Image.MAX_IMAGE_PIXELS = 1000000000 232 | 233 | for idx in tqdm.tqdm(range(len(dataset))): 234 | # Optionally extract images from tar in bunches 235 | if tar_file is not None: 236 | if idx % 1000 == 0: 237 | spaths = ' '.join(dataset.df[idx:idx+1000]['path'].values) 238 | cmd = 'cd ' + os.path.split(input_file)[0] 239 | if tar_delete is not None: 240 | cmd += ' && rm -rfv ' + tar_delete 241 | cmd += ' && tar -xvf ' + tar_file + ' ' + spaths 242 | subprocess.check_output(cmd, shell=True) 243 | 244 | # Preprocess and save images 245 | data = dataset[idx] 246 | output_path = os.path.join(output_dir, data['path_relative']) 247 | output_subdir = os.path.split(output_path)[0] 248 | os.makedirs(output_subdir, exist_ok=True) 249 | data['image'].save(output_path) 250 | 251 | 252 | def extract_features(input_file, output_file, 253 | view='surface', rule='cvusa', arch='alexnet', 254 | batch_size=256, num_workers=12, 255 | populate_latlon=False): 256 | """ 257 | Use the model to generate a feature vector for each image, 258 | saving these in a new CSV file. 259 | """ 260 | transform = get_transform(view, preprocess=False, finalprocess=True) 261 | dataset = OneDataset(input_file, view=view, rule=rule, transform=transform) 262 | if populate_latlon: 263 | dataset.populate_latlon() 264 | loader = torch.utils.data.DataLoader(dataset, batch_size=batch_size, shuffle=False, drop_last=False, num_workers=num_workers) 265 | model = load_model(view, arch).to(device) 266 | if device_parallel and torch.cuda.device_count() > 1: 267 | model = torch.nn.DataParallel(model, device_ids=device_ids) 268 | torch.set_grad_enabled(False) 269 | 270 | # Generate feature vectors 271 | feat_vecs = None 272 | num_batches = len(dataset)//batch_size + (len(dataset)%batch_size > 0) 273 | for batch, data in tqdm.tqdm(enumerate(loader), total=num_batches): 274 | images = data['image'].to(device) 275 | feat_vecs_part = model(images) 276 | if feat_vecs is None: 277 | feat_vecs = feat_vecs_part 278 | else: 279 | feat_vecs = torch.cat((feat_vecs, feat_vecs_part), dim=0) 280 | 281 | # Load feature vectors into DataFrame, and save 282 | feat_vecs_df = pd.DataFrame(feat_vecs.cpu().numpy()) 283 | dataset.df = pd.concat([dataset.df.iloc[:, :3], feat_vecs_df], axis=1) 284 | dataset.save(output_file) 285 | 286 | 287 | def feature_weights(weight_outdoor_manmade=1., 288 | weight_outdoor_natural=1., 289 | weight_indoor=1.): 290 | """ 291 | Return a vector of the importance of each scene class, 292 | based on its Level 1 assignment in the Scenes2 hierarchy. 293 | """ 294 | names = np.array(['outdoor_manmade', 'outdoor_natural', 'indoor']) 295 | weights = np.array([[weight_outdoor_manmade], 296 | [weight_outdoor_natural], 297 | [weight_indoor]]) 298 | memberships = np.array([ 299 | [1,0,0,0,1,1,0,1,1,0,1,0,1,1,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,0,0,1,1,0,0,0,0,0,0,1,1,1,0,0,0,0,1,0,1,0,0,0,1,0,0,0,1,1,1,0,0,1,0,0,0,1,1,1,0,0,1,0,0,1,0,1,1,0,1,0,0,0,1,1,0,1,1,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,1,0,1,0,1,1,1,0,0,1,1,0,0,0,0,1,1,0,0,0,1,0,1,0,1,0,0,0,0,1,0,0,0,1,0,1,0,1,0,1,1,1,1,0,0,0,1,0,0,1,1,1,0,0,1,1,1,0,1,0,0,1,0,1,0,0,0,1,1,0,1,1,1,0,0,1,0,0,1,0,1,1,0,0,0,0,1,0,1,1,1,0,0,0,1,0,1,1,1,0,0,0,0,1,1,0,1,0,0,0,1,1,0,1,0,1,0,1,1,0,1,0,0,1,1,0,1,1,1,0,1,0,0,0,1,0,0,0,0,1,0,0,1,0,1,0,0,0,1,1,0,1,0,1,1,0,1,1,0,0,1,0,1,1,0,1,0,1,0,1,1,0,1,1,0,1,0,0,0,0,1,0,0,1,1,0,0,1,1,1,1,1,0,1,0,0,1,0,1,0,0,1,1,0,1,1,0,1,0,1,1,1,0,1,0,0,1,0,0,0,0,0,0,1,1,0,0,1,0,1,1,1,0,0,0,0,1,1,0,0,0,0,1,0,1,1,1,0,1,0,1,1,0,0,0,0,0,1,1,1,0,1], 300 | [0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,1,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,1,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,1,0,0,0,0,0,0,1,1,0,0,0,0,1,1,0,1,0,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,0,0,0,1,0,0,0,0,1,1,1,1,0,0,0,0,0,0,0,0,0,1,1,0,0,1,0,0,0,0,0,1,0,1,0,0,0,0,1,0,0,0,0,0,1,1,0,0,1,1,0,0,1,0,0,0,0,0,0,0,0,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,1,1,1,0,0,0,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,1,0,0,0,1,0,0,0,0,0,0,1,0,0,1,0,0,1,0,0,0,0,0,1,0,1,0,0,0,0,0,0,0,1,1,1,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,1,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,0,0,0,0,0,0,0,0,1,0,0,0,0,1,1,1,1,1,0,1,1,0,1,0,1,1,0,0,0,0,1,1,1,0,1,1,0,1,0,0], 301 | [0,1,1,1,0,0,1,0,0,1,0,1,0,0,1,1,1,1,0,1,1,1,1,1,0,1,1,1,1,1,0,1,0,0,1,1,0,1,1,1,0,0,0,1,1,1,1,0,0,0,1,1,1,0,1,1,1,0,0,0,1,1,0,1,1,1,0,0,0,1,1,1,1,0,0,1,0,0,0,0,1,0,1,0,0,1,0,0,1,1,1,0,1,1,0,1,1,0,1,1,1,1,1,0,0,0,1,0,0,0,0,0,0,0,1,1,0,0,0,0,1,1,1,0,1,0,1,0,1,1,1,1,0,1,1,1,0,1,0,1,0,0,0,0,0,0,1,1,1,0,0,0,0,0,0,1,1,0,0,0,1,0,1,0,0,1,0,0,1,1,0,0,1,0,0,0,1,1,0,1,0,0,1,0,0,1,0,0,1,0,0,0,0,0,0,1,1,0,1,0,0,0,1,1,0,0,0,0,1,0,1,1,1,0,0,1,0,1,0,1,0,0,1,0,0,1,0,0,1,0,0,0,0,0,0,1,1,0,1,1,1,1,0,0,1,0,1,0,1,0,1,0,0,1,0,1,0,0,0,0,0,1,1,0,1,0,0,1,0,1,0,0,0,0,1,0,0,0,0,0,1,1,1,0,1,1,0,0,0,0,0,0,0,0,0,1,0,1,1,0,1,0,1,1,0,0,0,0,0,0,0,1,0,0,0,1,0,1,1,0,1,1,1,0,0,1,0,0,1,1,0,1,1,0,0,1,1,1,0,0,0,0,0,1,0,0,1,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,1,0] 302 | ]) 303 | vector = np.amax(weights * memberships, axis=0) 304 | return torch.tensor(vector) 305 | 306 | 307 | class TransformWrapper(torch.utils.data.Dataset): 308 | """ 309 | Applies an additional transform to an existing dataset 310 | without internally modifying the dataset. 311 | """ 312 | def __init__(self, dataset, transform=None): 313 | self.dataset = dataset 314 | self.transform = transform 315 | def __len__(self): 316 | return len(self.dataset) 317 | def __getitem__(self, idx): 318 | data = self.dataset[idx] 319 | if self.transform is not None: 320 | data['image'] = self.transform(data['image']) 321 | return data 322 | 323 | 324 | class WeightedPairwiseDistance(torch.nn.Module): 325 | """ 326 | Similar to torch.nn.PairwiseDistance, but with a weight assigned to each 327 | element of the feature vectors. Dimensions: 328 | 'weights': (D) 329 | 'output' and 'target': (N, D) 330 | where N = batch dimension and D = vector dimension 331 | """ 332 | def __init__(self, weights=feature_weights(), normalize=True): 333 | super().__init__() 334 | if normalize: 335 | weights = weights / torch.linalg.vector_norm(weights) 336 | weights = weights.unsqueeze(0) 337 | self.register_buffer('weights', weights) 338 | def forward(self, output, target): 339 | return torch.linalg.vector_norm(self.weights * (output-target), dim=1) 340 | 341 | 342 | def train(input_file, val_file=None, 343 | view='overhead', rule='cvusa', arch='alexnet', 344 | batch_size=32, num_workers=12, 345 | val_quantity=1000, num_epochs=999999): 346 | """ 347 | Train a model to predict a feature vector from corresponding image. 348 | In particular, train a model to predict scene vector from overhead image. 349 | """ 350 | 351 | # Data and transforms 352 | train_transform = get_transform(view, preprocess=False, finalprocess=True, augment=True) 353 | val_transform = get_transform(view, preprocess=False, finalprocess=True, augment=False) 354 | if val_file is None: 355 | dataset = OneDataset(input_file, view=view, rule=rule, transform=None) 356 | train_set, val_set = torch.utils.data.random_split(dataset, [len(dataset) - val_quantity, val_quantity]) 357 | train_set = TransformWrapper(train_set, train_transform) 358 | val_set = TransformWrapper(val_set, val_transform) 359 | else: 360 | train_set = OneDataset(input_file, view=view, rule=rule, transform=train_transform) 361 | val_set = OneDataset(val_file, view=view, rule=rule, transform=val_transform) 362 | train_loader = torch.utils.data.DataLoader(train_set, batch_size=batch_size, shuffle=True, drop_last=True, num_workers=num_workers) 363 | val_loader = torch.utils.data.DataLoader(val_set, batch_size=batch_size, shuffle=False, drop_last=False, num_workers=num_workers) 364 | train_batches = len(train_set) // batch_size 365 | val_batches = -((-len(val_set)) // batch_size) 366 | 367 | # Model, loss, optimizer (Note: Init model w/ surface weights regardless) 368 | model = load_model(view='surface', arch=arch).to(device) 369 | if device_parallel and torch.cuda.device_count() > 1: 370 | model = torch.nn.DataParallel(model, device_ids=device_ids) 371 | loss_func = WeightedPairwiseDistance().to(device) 372 | # optimizer = torch.optim.SGD(model.parameters(), lr=3E-4, 373 | # momentum=0.9, weight_decay=5E-4) 374 | # scheduler = torch.optim.lr_scheduler.StepLR( 375 | # optimizer, step_size=30, gamma=0.1) 376 | optimizer = torch.optim.Adam(model.parameters(), lr=1E-4) 377 | 378 | # Optionally resume training from where it left off 379 | # Note: Add "resume=False" to arguments of train() 380 | # To do: Load checkpoint 381 | # if resume: 382 | # init_epoch = checkpoint['epoch'] 383 | # optimizer.load_state_dict(checkpoint['optimizer_state_dict']) 384 | # else: 385 | # init_epoch = 0 386 | 387 | # Loop through epochs 388 | best_loss = None 389 | for epoch in range(num_epochs): 390 | print('Epoch %d, %s' % (epoch + 1, time.ctime(time.time()))) 391 | 392 | for phase in ['train', 'val']: 393 | running_count = 0 394 | running_loss = 0. 395 | 396 | if phase == 'train': 397 | loader = train_loader 398 | model.train() 399 | elif phase == 'val': 400 | loader = val_loader 401 | model.eval() 402 | 403 | # Loop through batches of data 404 | num_batches = train_batches if phase == 'train' else val_batches 405 | for batch, data in tqdm.tqdm(enumerate(loader), total=num_batches, leave=False): 406 | images = data['image'].to(device) 407 | target_vectors = data['vector'].to(device) 408 | 409 | with torch.set_grad_enabled(phase == 'train'): 410 | 411 | # Forward and loss (train and val) 412 | infer_vectors = model(images) 413 | loss = torch.sum(loss_func(infer_vectors, target_vectors)) 414 | 415 | # Backward and optimization (train only) 416 | if phase == 'train': 417 | optimizer.zero_grad() 418 | loss.backward() 419 | optimizer.step() 420 | 421 | if loss.isnan().item(): 422 | raise Exception('! Loss is not a number.') 423 | 424 | count = target_vectors.size(0) 425 | running_count += count 426 | running_loss += loss.item() 427 | 428 | print(' %5s: avg loss = %f' % (phase, running_loss / running_count)) 429 | 430 | # scheduler.step() 431 | 432 | # Save weights if this is the lowest observed validation loss 433 | if best_loss is None or running_loss / running_count < best_loss: 434 | print('-------> new best') 435 | best_loss = running_loss / running_count 436 | checkpoint_path = '../weights/%s_%s.pth.tar' % (arch, view) 437 | checkpoint = { 438 | 'view': view, 439 | 'arch': arch, 440 | 'epoch': epoch + 1, 441 | 'state_dict': model.state_dict(), 442 | 'optimizer_state_dict': optimizer.state_dict(), 443 | #'scheduler_state_dict': scheduler.state_dict(), 444 | 'val_loss': best_loss, 445 | } 446 | torch.save(checkpoint, checkpoint_path) 447 | 448 | 449 | def metrics(surface_file, overhead_file): 450 | """ 451 | Given a CSV file of surface feature vectors and a CSV file of overhead 452 | feature vectors for the same places in the same order, determine 453 | performance metrics for ranking overhead matches for each surface image. 454 | """ 455 | # Data 456 | surface_dataset = OneDataset(surface_file, view='surface') 457 | surface_vectors = torch.tensor(surface_dataset.df.iloc[:, 3:].values, 458 | device=device, dtype=torch.float32) 459 | surface_dataset = None 460 | overhead_dataset = OneDataset(overhead_file, view='overhead') 461 | overhead_vectors = torch.tensor(overhead_dataset.df.iloc[:, 3:].values, 462 | device=device, dtype=torch.float32) 463 | overhead_dataset = None 464 | 465 | # Metric definition 466 | distance_func = WeightedPairwiseDistance().to(device) 467 | 468 | # Measure performance 469 | count = surface_vectors.size(0) 470 | ranks = np.zeros([count], dtype=int) 471 | for idx in tqdm.tqdm(range(count)): 472 | surface_vector = torch.unsqueeze(surface_vectors[idx], 0) 473 | distances = distance_func(overhead_vectors, surface_vector) 474 | distance = distances[idx] 475 | ranks[idx] = torch.sum(torch.le(distances, distance)).item() 476 | top_one = np.sum(ranks <= 1) / count * 100 477 | top_five = np.sum(ranks <= 5) / count * 100 478 | top_ten = np.sum(ranks <= 10) / count * 100 479 | top_percent = np.sum(ranks * 100 <= count) / count * 100 480 | top_fivepct = np.sum(ranks * 20 <= count) / count * 100 481 | top_tenpct = np.sum(ranks * 10 <= count) / count * 100 482 | mean = np.mean(ranks) 483 | median = np.median(ranks) 484 | 485 | # Print performance 486 | print('Top 1: {:.2f}%'.format(top_one)) 487 | print('Top 5: {:.2f}%'.format(top_five)) 488 | print('Top 10: {:.2f}%'.format(top_ten)) 489 | print('Top 1%: {:.2f}%'.format(top_percent)) 490 | print('Top 5%: {:.2f}%'.format(top_fivepct)) 491 | print('Top10%: {:.2f}%'.format(top_tenpct)) 492 | print('Avg. Rank: {:.2f}'.format(mean)) 493 | print('Med. Rank: {:.2f}'.format(median)) 494 | print('Locations: {}'.format(count)) 495 | 496 | 497 | def score_file(input_file, output_file, ref_file, ref_index, view='surface'): 498 | """ 499 | Given a file of feature vectors, compute their distances from a single 500 | reference feature vector in another file. Save the scores (the negatives 501 | of the distances) in a new file. 502 | """ 503 | # Data 504 | src_dataset = OneDataset(input_file) 505 | src_vectors = torch.tensor(src_dataset.df.iloc[:, 3:].values, 506 | device=device, dtype=torch.float32) 507 | ref_dataset = OneDataset(ref_file) 508 | ref_vector = torch.tensor( 509 | ref_dataset.df.iloc[ref_index:ref_index, 3:].values, 510 | device=device, dtype=torch.float32) 511 | if len(ref_vector) == 0: 512 | # Reference feature vector absent and must be generated from model 513 | transform = get_transform(view, preprocess=False, finalprocess=True) 514 | model = load_model(view).to(device) 515 | image_path = os.path.join( 516 | ref_dataset.input_dir, 517 | ref_dataset.paths_relative.iloc[ref_index]) 518 | image = Image.open(image_path) 519 | if image.mode != 'RGB': 520 | image = image.convert('RGB') 521 | image = transform(image).to(device) 522 | ref_vector = model(image.unsqueeze(0)) 523 | 524 | # Measure distances 525 | distance_func = WeightedPairwiseDistance().to(device) 526 | distances = distance_func(src_vectors, ref_vector) 527 | scores = pd.DataFrame(-distances.cpu().detach().numpy()) 528 | src_dataset.df = pd.concat([src_dataset.df.iloc[:, :3], scores], axis=1) 529 | src_dataset.save(output_file) 530 | 531 | 532 | def example_features(path, view='surface', verbose=True, 533 | names_path='categories_places365.txt'): 534 | transform = get_transform(view, preprocess=False, finalprocess=True) 535 | model = load_model(view) 536 | image = Image.open(path) 537 | batch = transform(image).unsqueeze(0) 538 | torch.set_grad_enabled(False) 539 | logits = model(batch).squeeze() 540 | probs = torch.nn.functional.softmax(logits, 0) 541 | if verbose: 542 | df = pd.read_csv(names_path, sep=' ', header=None, 543 | names=['scene'], usecols=[0]) 544 | df['prob'] = probs.numpy() 545 | df.sort_values('prob', ascending=False, inplace=True) 546 | df.reset_index(drop=True, inplace=True) 547 | print(path) 548 | print(df[:5]) 549 | return logits 550 | 551 | 552 | class Translator(object): 553 | """ 554 | Translate feature vector(s) from one feature space to another by using 555 | a lookup table of pairs of corresponding feature vectors in both spaces. 556 | """ 557 | def __init__(self, domain_file, codomain_file, 558 | dist_func=WeightedPairwiseDistance()): 559 | # Load lookup table 560 | domain_dataset = OneDataset(domain_file) 561 | self.domain_vectors = torch.tensor(domain_dataset.df.iloc[:, 3:].values, device=device, dtype=torch.float32) 562 | domain_dataset = None 563 | codomain_dataset = OneDataset(codomain_file) 564 | self.codomain_vectors = torch.tensor(codomain_dataset.df.iloc[:, 3:].values, device=device, dtype=torch.float32) 565 | codomain_dataset = None 566 | self.dist_func = dist_func.to(device) 567 | 568 | def translate_vector(self, input_vector, n=30): 569 | input_vector = torch.unsqueeze(input_vector, 0).to(device) 570 | distances = self.dist_func(self.domain_vectors, input_vector) 571 | _, closest_idxs = torch.topk(distances, k=n, largest=False) # unsorted 572 | corres_vectors = torch.index_select(self.codomain_vectors, 0, closest_idxs) 573 | output_vector = torch.mean(corres_vectors, 0) 574 | return output_vector 575 | 576 | def translate_file(self, input_file, output_file, n=30, d=device): 577 | # Load data 578 | dataset = OneDataset(input_file) 579 | input_vectors = torch.tensor(dataset.df.iloc[:, 3:].values, device=d, dtype=torch.float32) 580 | output_vectors = torch.zeros([input_vectors.size(0), self.codomain_vectors.size(1)], device=d, dtype=torch.float32) 581 | 582 | # Generate feature vectors 583 | count = input_vectors.size(0) 584 | for idx in tqdm.tqdm(range(count)): 585 | input_vector = input_vectors[idx, :] 586 | output_vector = self.translate_vector(input_vector, n=n) 587 | output_vectors[idx, :] = output_vector.to(d) 588 | 589 | # Load feature vectors into DataFrame, and save 590 | feat_vecs_df = pd.DataFrame(output_vectors.cpu().numpy()) 591 | dataset.df = pd.concat([dataset.df.iloc[:, :3], feat_vecs_df], axis=1) 592 | dataset.save(output_file) 593 | 594 | 595 | if __name__ == '__main__': 596 | pass 597 | --------------------------------------------------------------------------------