We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
SemanticSegmentationRasterStore not saving for non-georeferenced imagery
```
root@122d4f0150f4:/opt/data/mar5# rastervision predict spacenet.zip example.jpg out.tif
/usr/local/lib/python3.5/dist-packages/pluginbase.py:439: FutureWarning: Conversion of the second argument of issubdtype from `float` to `np.floating` is deprecated. In future, it will be treated as `np.float64 == np.dtype(float).type`.
  fromlist, level)
2019-03-06 16:59:56.502396: I tensorflow/core/platform/cpu_feature_guard.cc:141] Your CPU supports instructions that this TensorFlow binary was not compiled to use: AVX2 FMA
/usr/local/lib/python3.5/dist-packages/rasterio/__init__.py:217: NotGeoreferencedWarning: Dataset has no geotransform set. The identity matrix may be returned.
  s = DatasetReader(path, driver=driver, **kwargs)
[0, 1, 2]
2019-03-06 16:59:56:rastervision.task.semantic_segmentation: INFO - Making predictions for scene
Traceback (most recent call last):
  File "/usr/lib/python3.5/runpy.py", line 184, in _run_module_as_main
    "__main__", mod_spec)
  File "/usr/lib/python3.5/runpy.py", line 85, in _run_code
    exec(code, run_globals)
  File "/opt/src/rastervision/__main__.py", line 17, in <module>
    rv.main()
  File "/usr/local/lib/python3.5/dist-packages/click/core.py", line 722, in __call__
    return self.main(*args, **kwargs)
  File "/usr/local/lib/python3.5/dist-packages/click/core.py", line 697, in main
    rv = self.invoke(ctx)
  File "/usr/local/lib/python3.5/dist-packages/click/core.py", line 1066, in invoke
    return _process_result(sub_ctx.command.invoke(sub_ctx))
  File "/usr/local/lib/python3.5/dist-packages/click/core.py", line 895, in invoke
    return ctx.invoke(self.callback, **ctx.params)
  File "/usr/local/lib/python3.5/dist-packages/click/core.py", line 535, in invoke
    return callback(*args, **kwargs)
  File "/opt/src/rastervision/cli/main.py", line 241, in predict
    predictor.predict(image_uri, output_uri, export_config)
  File "/opt/src/rastervision/predictor.py", line 144, in predict
    scene.prediction_label_store.save(labels)
  File "/opt/src/rastervision/data/label_store/semantic_segmentation_raster_store.py", line 90, in save
    transform = self.crs_transformer.transform
AttributeError: 'IdentityCRSTransformer' object has no attribute 'transform'
```

--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `rastervision/data/crs_transformer/rasterio_crs_transformer.py`
Content:
```
1 import pyproj
2 
3 from rasterio.transform import (rowcol, xy)
4 
5 from rastervision.data.crs_transformer import (CRSTransformer,
6                                                IdentityCRSTransformer)
7 
8 
9 class RasterioCRSTransformer(CRSTransformer):
10     """Transformer for a RasterioRasterSource."""
11 
12     def __init__(self, transform, image_crs, map_crs='epsg:4326'):
13         """Construct transformer.
14 
15         Args:
16             image_dataset: Rasterio DatasetReader
17             map_crs: CRS code
18         """
19         self.transform = transform
20         self.map_proj = pyproj.Proj(init=map_crs)
21         self.image_proj = pyproj.Proj(init=image_crs)
22 
23         super().__init__(image_crs, map_crs)
24 
25     def map_to_pixel(self, map_point):
26         """Transform point from map to pixel-based coordinates.
27 
28         Args:
29             map_point: (x, y) tuple in map coordinates
30 
31         Returns:
32             (x, y) tuple in pixel coordinates
33         """
34         image_point = pyproj.transform(self.map_proj, self.image_proj,
35                                        map_point[0], map_point[1])
36         pixel_point = rowcol(self.transform, image_point[0], image_point[1])
37         pixel_point = (pixel_point[1], pixel_point[0])
38         return pixel_point
39 
40     def pixel_to_map(self, pixel_point):
41         """Transform point from pixel to map-based coordinates.
42 
43         Args:
44             pixel_point: (x, y) tuple in pixel coordinates
45 
46         Returns:
47             (x, y) tuple in map coordinates
48         """
49         image_point = xy(self.transform, int(pixel_point[1]),
50                          int(pixel_point[0]))
51         map_point = pyproj.transform(self.image_proj, self.map_proj,
52                                      image_point[0], image_point[1])
53         return map_point
54 
55     @classmethod
56     def from_dataset(cls, dataset, map_crs='epsg:4326'):
57         if dataset.crs is None:
58             return IdentityCRSTransformer()
59         transform = dataset.transform
60         image_crs = dataset.crs['init']
61         return cls(transform, image_crs, map_crs)
62 
63     def get_affine_transform(self):
64         return self.transform
65
```

Path: `rastervision/data/crs_transformer/crs_transformer.py`
Content:
```
1 class CRSTransformer(object):
2     """Transforms map points in some CRS into pixel coordinates.
3 
4     Each transformer is associated with a particular RasterSource."""
5 
6     def __init__(self, image_crs=None, map_crs=None):
7         self.image_crs = image_crs
8         self.map_crs = map_crs
9 
10     def map_to_pixel(self, map_point):
11         """Transform point from map to pixel-based coordinates.
12 
13         Args:
14             map_point: (x, y) tuple in map coordinates (eg. lon/lat)
15 
16         Returns:
17             (x, y) tuple in pixel coordinates
18         """
19         pass
20 
21     def pixel_to_map(self, pixel_point):
22         """Transform point from pixel to map-based coordinates.
23 
24         Args:
25             pixel_point: (x, y) tuple in pixel coordinates
26 
27         Returns:
28             (x, y) tuple in map coordinates (eg. lon/lat)
29         """
30         pass
31 
32     def get_image_crs(self):
33         return self.image_crs
34 
35     def get_map_crs(self):
36         return self.map_crs
37 
38     def get_affine_transform(self):
39         raise NotImplementedError()
40
```

Path: `rastervision/data/label_store/semantic_segmentation_raster_store.py`
Content:
```
1 import numpy as np
2 import rasterio
3 
4 import rastervision as rv
5 from rastervision.utils.files import (get_local_path, make_dir, upload_or_copy,
6                                       file_exists)
7 from rastervision.data.label import SemanticSegmentationLabels
8 from rastervision.data.label_store import LabelStore
9 from rastervision.data.label_source import SegmentationClassTransformer
10 
11 
12 class SemanticSegmentationRasterStore(LabelStore):
13     """A prediction label store for segmentation raster files.
14     """
15 
16     def __init__(self,
17                  uri,
18                  extent,
19                  crs_transformer,
20                  tmp_dir,
21                  vector_output=None,
22                  class_map=None):
23         """Constructor.
24 
25         Args:
26             uri: (str) URI of GeoTIFF file used for storing predictions as RGB values
27             extent: (Box) The extent of the scene
28             crs_transformer: (CRSTransformer)
29             tmp_dir: (str) temp directory to use
30             vector_output: (None or array of dicts) containing vectorifiction
31                 configuration information
32             class_map: (ClassMap) with color values used to convert class ids to
33                 RGB values
34 
35         """
36         self.uri = uri
37         self.vector_output = vector_output
38         self.extent = extent
39         self.crs_transformer = crs_transformer
40         self.tmp_dir = tmp_dir
41         # Note: can't name this class_transformer due to Python using that attribute
42         if class_map:
43             self.class_trans = SegmentationClassTransformer(class_map)
44         else:
45             self.class_trans = None
46 
47         self.source = None
48         if file_exists(uri):
49             self.source = rv.RasterSourceConfig.builder(rv.GEOTIFF_SOURCE) \
50                                                .with_uri(self.uri) \
51                                                .build() \
52                                                .create_source(self.tmp_dir)
53 
54     def _subcomponents_to_activate(self):
55         if self.source is not None:
56             return [self.source]
57         return []
58 
59     def get_labels(self, chip_size=1000):
60         """Get all labels.
61 
62         Returns:
63             SemanticSegmentationLabels with windows of size chip_size covering the
64                 scene with no overlap.
65         """
66 
67         def label_fn(window):
68             raw_labels = self.source.get_raw_chip(window)
69             if self.class_trans:
70                 labels = self.class_trans.rgb_to_class(raw_labels)
71             else:
72                 labels = np.squeeze(raw_labels)
73             return labels
74 
75         extent = self.source.get_extent()
76         windows = extent.get_windows(chip_size, chip_size)
77         return SemanticSegmentationLabels(windows, label_fn)
78 
79     def save(self, labels):
80         """Save.
81 
82         Args:
83             labels - (SemanticSegmentationLabels) labels to be saved
84         """
85         local_path = get_local_path(self.uri, self.tmp_dir)
86         make_dir(local_path, use_dirname=True)
87 
88         # TODO: this only works if crs_transformer is RasterioCRSTransformer.
89         # Need more general way of computing transform for the more general case.
90         transform = self.crs_transformer.transform
91         crs = self.crs_transformer.get_image_crs()
92 
93         band_count = 1
94         dtype = np.uint8
95         if self.class_trans:
96             band_count = 3
97 
98         if self.vector_output:
99             # We need to store the whole output mask to run feature extraction.
100             # If the raster is large, this will result in running out of memory, so
101             # more work will be needed to get this to work in a scalable way. But this
102             # is complicated because of the need to merge features that are split
103             # across windows.
104             mask = np.zeros(
105                 (self.extent.ymax, self.extent.xmax), dtype=np.uint8)
106         else:
107             mask = None
108 
109         # https://github.com/mapbox/rasterio/blob/master/docs/quickstart.rst
110         # https://rasterio.readthedocs.io/en/latest/topics/windowed-rw.html
111         with rasterio.open(
112                 local_path,
113                 'w',
114                 driver='GTiff',
115                 height=self.extent.ymax,
116                 width=self.extent.xmax,
117                 count=band_count,
118                 dtype=dtype,
119                 transform=transform,
120                 crs=crs) as dataset:
121             for window in labels.get_windows():
122                 class_labels = labels.get_label_arr(
123                     window, clip_extent=self.extent)
124                 clipped_window = ((window.ymin,
125                                    window.ymin + class_labels.shape[0]),
126                                   (window.xmin,
127                                    window.xmin + class_labels.shape[1]))
128                 if mask is not None:
129                     mask[clipped_window[0][0]:clipped_window[0][1],
130                          clipped_window[1][0]:clipped_window[1][
131                              1]] = class_labels
132                 if self.class_trans:
133                     rgb_labels = self.class_trans.class_to_rgb(class_labels)
134                     for chan in range(3):
135                         dataset.write_band(
136                             chan + 1,
137                             rgb_labels[:, :, chan],
138                             window=clipped_window)
139                 else:
140                     img = class_labels.astype(dtype)
141                     dataset.write_band(1, img, window=clipped_window)
142 
143         upload_or_copy(local_path, self.uri)
144 
145         if self.vector_output:
146             import mask_to_polygons.vectorification as vectorification
147             import mask_to_polygons.processing.denoise as denoise
148 
149             for vo in self.vector_output:
150                 denoise_radius = vo['denoise']
151                 uri = vo['uri']
152                 mode = vo['mode']
153                 class_id = vo['class_id']
154                 class_mask = np.array(mask == class_id, dtype=np.uint8)
155                 local_geojson_path = get_local_path(uri, self.tmp_dir)
156 
157                 def transform(x, y):
158                     return self.crs_transformer.pixel_to_map((x, y))
159 
160                 if denoise_radius > 0:
161                     class_mask = denoise.denoise(class_mask, denoise_radius)
162 
163                 if uri and mode == 'buildings':
164                     options = vo['building_options']
165                     geojson = vectorification.geojson_from_mask(
166                         mask=class_mask,
167                         transform=transform,
168                         mode=mode,
169                         min_aspect_ratio=options['min_aspect_ratio'],
170                         min_area=options['min_area'],
171                         width_factor=options['element_width_factor'],
172                         thickness=options['element_thickness'])
173                 elif uri and mode == 'polygons':
174                     geojson = vectorification.geojson_from_mask(
175                         mask=class_mask, transform=transform, mode=mode)
176 
177                 if local_geojson_path:
178                     with open(local_geojson_path, 'w') as file_out:
179                         file_out.write(geojson)
180                         upload_or_copy(local_geojson_path, uri)
181 
182     def empty_labels(self):
183         """Returns an empty SemanticSegmentationLabels object."""
184         return SemanticSegmentationLabels()
185
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/rastervision/data/crs_transformer/crs_transformer.py b/rastervision/data/crs_transformer/crs_transformer.py
--- a/rastervision/data/crs_transformer/crs_transformer.py
+++ b/rastervision/data/crs_transformer/crs_transformer.py
@@ -3,9 +3,10 @@
 
     Each transformer is associated with a particular RasterSource."""
 
-    def __init__(self, image_crs=None, map_crs=None):
+    def __init__(self, image_crs=None, map_crs=None, transform=None):
         self.image_crs = image_crs
         self.map_crs = map_crs
+        self.transform = transform
 
     def map_to_pixel(self, map_point):
         """Transform point from map to pixel-based coordinates.
@@ -36,4 +37,4 @@
         return self.map_crs
 
     def get_affine_transform(self):
-        raise NotImplementedError()
+        return self.transform
diff --git a/rastervision/data/crs_transformer/rasterio_crs_transformer.py b/rastervision/data/crs_transformer/rasterio_crs_transformer.py
--- a/rastervision/data/crs_transformer/rasterio_crs_transformer.py
+++ b/rastervision/data/crs_transformer/rasterio_crs_transformer.py
@@ -16,11 +16,10 @@
             image_dataset: Rasterio DatasetReader
             map_crs: CRS code
         """
-        self.transform = transform
         self.map_proj = pyproj.Proj(init=map_crs)
         self.image_proj = pyproj.Proj(init=image_crs)
 
-        super().__init__(image_crs, map_crs)
+        super().__init__(image_crs, map_crs, transform)
 
     def map_to_pixel(self, map_point):
         """Transform point from map to pixel-based coordinates.
diff --git a/rastervision/data/label_store/semantic_segmentation_raster_store.py b/rastervision/data/label_store/semantic_segmentation_raster_store.py
--- a/rastervision/data/label_store/semantic_segmentation_raster_store.py
+++ b/rastervision/data/label_store/semantic_segmentation_raster_store.py
@@ -85,9 +85,7 @@
         local_path = get_local_path(self.uri, self.tmp_dir)
         make_dir(local_path, use_dirname=True)
 
-        # TODO: this only works if crs_transformer is RasterioCRSTransformer.
-        # Need more general way of computing transform for the more general case.
-        transform = self.crs_transformer.transform
+        transform = self.crs_transformer.get_affine_transform()
         crs = self.crs_transformer.get_image_crs()
 
         band_count = 1

{"golden_diff": "diff --git a/rastervision/data/crs_transformer/crs_transformer.py b/rastervision/data/crs_transformer/crs_transformer.py\n--- a/rastervision/data/crs_transformer/crs_transformer.py\n+++ b/rastervision/data/crs_transformer/crs_transformer.py\n@@ -3,9 +3,10 @@\n \n     Each transformer is associated with a particular RasterSource.\"\"\"\n \n-    def __init__(self, image_crs=None, map_crs=None):\n+    def __init__(self, image_crs=None, map_crs=None, transform=None):\n         self.image_crs = image_crs\n         self.map_crs = map_crs\n+        self.transform = transform\n \n     def map_to_pixel(self, map_point):\n         \"\"\"Transform point from map to pixel-based coordinates.\n@@ -36,4 +37,4 @@\n         return self.map_crs\n \n     def get_affine_transform(self):\n-        raise NotImplementedError()\n+        return self.transform\ndiff --git a/rastervision/data/crs_transformer/rasterio_crs_transformer.py b/rastervision/data/crs_transformer/rasterio_crs_transformer.py\n--- a/rastervision/data/crs_transformer/rasterio_crs_transformer.py\n+++ b/rastervision/data/crs_transformer/rasterio_crs_transformer.py\n@@ -16,11 +16,10 @@\n             image_dataset: Rasterio DatasetReader\n             map_crs: CRS code\n         \"\"\"\n-        self.transform = transform\n         self.map_proj = pyproj.Proj(init=map_crs)\n         self.image_proj = pyproj.Proj(init=image_crs)\n \n-        super().__init__(image_crs, map_crs)\n+        super().__init__(image_crs, map_crs, transform)\n \n     def map_to_pixel(self, map_point):\n         \"\"\"Transform point from map to pixel-based coordinates.\ndiff --git a/rastervision/data/label_store/semantic_segmentation_raster_store.py b/rastervision/data/label_store/semantic_segmentation_raster_store.py\n--- a/rastervision/data/label_store/semantic_segmentation_raster_store.py\n+++ b/rastervision/data/label_store/semantic_segmentation_raster_store.py\n@@ -85,9 +85,7 @@\n         local_path = get_local_path(self.uri, self.tmp_dir)\n         make_dir(local_path, use_dirname=True)\n \n-        # TODO: this only works if crs_transformer is RasterioCRSTransformer.\n-        # Need more general way of computing transform for the more general case.\n-        transform = self.crs_transformer.transform\n+        transform = self.crs_transformer.get_affine_transform()\n         crs = self.crs_transformer.get_image_crs()\n \n         band_count = 1\n", "issue": "SemanticSegmentationRasterStore not saving for non-georeferenced imagery\n```\r\nroot@122d4f0150f4:/opt/data/mar5# rastervision predict spacenet.zip example.jpg out.tif\r\n/usr/local/lib/python3.5/dist-packages/pluginbase.py:439: FutureWarning: Conversion of the second argument of issubdtype from `float` to `np.floating` is deprecated. In future, it will be treated as `np.float64 == np.dtype(float).type`.\r\n  fromlist, level)\r\n2019-03-06 16:59:56.502396: I tensorflow/core/platform/cpu_feature_guard.cc:141] Your CPU supports instructions that this TensorFlow binary was not compiled to use: AVX2 FMA\r\n/usr/local/lib/python3.5/dist-packages/rasterio/__init__.py:217: NotGeoreferencedWarning: Dataset has no geotransform set. The identity matrix may be returned.\r\n  s = DatasetReader(path, driver=driver, **kwargs)\r\n[0, 1, 2]\r\n2019-03-06 16:59:56:rastervision.task.semantic_segmentation: INFO - Making predictions for scene\r\nTraceback (most recent call last):\r\n  File \"/usr/lib/python3.5/runpy.py\", line 184, in _run_module_as_main\r\n    \"__main__\", mod_spec)\r\n  File \"/usr/lib/python3.5/runpy.py\", line 85, in _run_code\r\n    exec(code, run_globals)\r\n  File \"/opt/src/rastervision/__main__.py\", line 17, in <module>\r\n    rv.main()\r\n  File \"/usr/local/lib/python3.5/dist-packages/click/core.py\", line 722, in __call__\r\n    return self.main(*args, **kwargs)\r\n  File \"/usr/local/lib/python3.5/dist-packages/click/core.py\", line 697, in main\r\n    rv = self.invoke(ctx)\r\n  File \"/usr/local/lib/python3.5/dist-packages/click/core.py\", line 1066, in invoke\r\n    return _process_result(sub_ctx.command.invoke(sub_ctx))\r\n  File \"/usr/local/lib/python3.5/dist-packages/click/core.py\", line 895, in invoke\r\n    return ctx.invoke(self.callback, **ctx.params)\r\n  File \"/usr/local/lib/python3.5/dist-packages/click/core.py\", line 535, in invoke\r\n    return callback(*args, **kwargs)\r\n  File \"/opt/src/rastervision/cli/main.py\", line 241, in predict\r\n    predictor.predict(image_uri, output_uri, export_config)\r\n  File \"/opt/src/rastervision/predictor.py\", line 144, in predict\r\n    scene.prediction_label_store.save(labels)\r\n  File \"/opt/src/rastervision/data/label_store/semantic_segmentation_raster_store.py\", line 90, in save\r\n    transform = self.crs_transformer.transform\r\nAttributeError: 'IdentityCRSTransformer' object has no attribute 'transform'\r\n```\n", "before_files": [{"content": "import pyproj\n\nfrom rasterio.transform import (rowcol, xy)\n\nfrom rastervision.data.crs_transformer import (CRSTransformer,\n                                               IdentityCRSTransformer)\n\n\nclass RasterioCRSTransformer(CRSTransformer):\n    \"\"\"Transformer for a RasterioRasterSource.\"\"\"\n\n    def __init__(self, transform, image_crs, map_crs='epsg:4326'):\n        \"\"\"Construct transformer.\n\n        Args:\n            image_dataset: Rasterio DatasetReader\n            map_crs: CRS code\n        \"\"\"\n        self.transform = transform\n        self.map_proj = pyproj.Proj(init=map_crs)\n        self.image_proj = pyproj.Proj(init=image_crs)\n\n        super().__init__(image_crs, map_crs)\n\n    def map_to_pixel(self, map_point):\n        \"\"\"Transform point from map to pixel-based coordinates.\n\n        Args:\n            map_point: (x, y) tuple in map coordinates\n\n        Returns:\n            (x, y) tuple in pixel coordinates\n        \"\"\"\n        image_point = pyproj.transform(self.map_proj, self.image_proj,\n                                       map_point[0], map_point[1])\n        pixel_point = rowcol(self.transform, image_point[0], image_point[1])\n        pixel_point = (pixel_point[1], pixel_point[0])\n        return pixel_point\n\n    def pixel_to_map(self, pixel_point):\n        \"\"\"Transform point from pixel to map-based coordinates.\n\n        Args:\n            pixel_point: (x, y) tuple in pixel coordinates\n\n        Returns:\n            (x, y) tuple in map coordinates\n        \"\"\"\n        image_point = xy(self.transform, int(pixel_point[1]),\n                         int(pixel_point[0]))\n        map_point = pyproj.transform(self.image_proj, self.map_proj,\n                                     image_point[0], image_point[1])\n        return map_point\n\n    @classmethod\n    def from_dataset(cls, dataset, map_crs='epsg:4326'):\n        if dataset.crs is None:\n            return IdentityCRSTransformer()\n        transform = dataset.transform\n        image_crs = dataset.crs['init']\n        return cls(transform, image_crs, map_crs)\n\n    def get_affine_transform(self):\n        return self.transform\n", "path": "rastervision/data/crs_transformer/rasterio_crs_transformer.py"}, {"content": "class CRSTransformer(object):\n    \"\"\"Transforms map points in some CRS into pixel coordinates.\n\n    Each transformer is associated with a particular RasterSource.\"\"\"\n\n    def __init__(self, image_crs=None, map_crs=None):\n        self.image_crs = image_crs\n        self.map_crs = map_crs\n\n    def map_to_pixel(self, map_point):\n        \"\"\"Transform point from map to pixel-based coordinates.\n\n        Args:\n            map_point: (x, y) tuple in map coordinates (eg. lon/lat)\n\n        Returns:\n            (x, y) tuple in pixel coordinates\n        \"\"\"\n        pass\n\n    def pixel_to_map(self, pixel_point):\n        \"\"\"Transform point from pixel to map-based coordinates.\n\n        Args:\n            pixel_point: (x, y) tuple in pixel coordinates\n\n        Returns:\n            (x, y) tuple in map coordinates (eg. lon/lat)\n        \"\"\"\n        pass\n\n    def get_image_crs(self):\n        return self.image_crs\n\n    def get_map_crs(self):\n        return self.map_crs\n\n    def get_affine_transform(self):\n        raise NotImplementedError()\n", "path": "rastervision/data/crs_transformer/crs_transformer.py"}, {"content": "import numpy as np\nimport rasterio\n\nimport rastervision as rv\nfrom rastervision.utils.files import (get_local_path, make_dir, upload_or_copy,\n                                      file_exists)\nfrom rastervision.data.label import SemanticSegmentationLabels\nfrom rastervision.data.label_store import LabelStore\nfrom rastervision.data.label_source import SegmentationClassTransformer\n\n\nclass SemanticSegmentationRasterStore(LabelStore):\n    \"\"\"A prediction label store for segmentation raster files.\n    \"\"\"\n\n    def __init__(self,\n                 uri,\n                 extent,\n                 crs_transformer,\n                 tmp_dir,\n                 vector_output=None,\n                 class_map=None):\n        \"\"\"Constructor.\n\n        Args:\n            uri: (str) URI of GeoTIFF file used for storing predictions as RGB values\n            extent: (Box) The extent of the scene\n            crs_transformer: (CRSTransformer)\n            tmp_dir: (str) temp directory to use\n            vector_output: (None or array of dicts) containing vectorifiction\n                configuration information\n            class_map: (ClassMap) with color values used to convert class ids to\n                RGB values\n\n        \"\"\"\n        self.uri = uri\n        self.vector_output = vector_output\n        self.extent = extent\n        self.crs_transformer = crs_transformer\n        self.tmp_dir = tmp_dir\n        # Note: can't name this class_transformer due to Python using that attribute\n        if class_map:\n            self.class_trans = SegmentationClassTransformer(class_map)\n        else:\n            self.class_trans = None\n\n        self.source = None\n        if file_exists(uri):\n            self.source = rv.RasterSourceConfig.builder(rv.GEOTIFF_SOURCE) \\\n                                               .with_uri(self.uri) \\\n                                               .build() \\\n                                               .create_source(self.tmp_dir)\n\n    def _subcomponents_to_activate(self):\n        if self.source is not None:\n            return [self.source]\n        return []\n\n    def get_labels(self, chip_size=1000):\n        \"\"\"Get all labels.\n\n        Returns:\n            SemanticSegmentationLabels with windows of size chip_size covering the\n                scene with no overlap.\n        \"\"\"\n\n        def label_fn(window):\n            raw_labels = self.source.get_raw_chip(window)\n            if self.class_trans:\n                labels = self.class_trans.rgb_to_class(raw_labels)\n            else:\n                labels = np.squeeze(raw_labels)\n            return labels\n\n        extent = self.source.get_extent()\n        windows = extent.get_windows(chip_size, chip_size)\n        return SemanticSegmentationLabels(windows, label_fn)\n\n    def save(self, labels):\n        \"\"\"Save.\n\n        Args:\n            labels - (SemanticSegmentationLabels) labels to be saved\n        \"\"\"\n        local_path = get_local_path(self.uri, self.tmp_dir)\n        make_dir(local_path, use_dirname=True)\n\n        # TODO: this only works if crs_transformer is RasterioCRSTransformer.\n        # Need more general way of computing transform for the more general case.\n        transform = self.crs_transformer.transform\n        crs = self.crs_transformer.get_image_crs()\n\n        band_count = 1\n        dtype = np.uint8\n        if self.class_trans:\n            band_count = 3\n\n        if self.vector_output:\n            # We need to store the whole output mask to run feature extraction.\n            # If the raster is large, this will result in running out of memory, so\n            # more work will be needed to get this to work in a scalable way. But this\n            # is complicated because of the need to merge features that are split\n            # across windows.\n            mask = np.zeros(\n                (self.extent.ymax, self.extent.xmax), dtype=np.uint8)\n        else:\n            mask = None\n\n        # https://github.com/mapbox/rasterio/blob/master/docs/quickstart.rst\n        # https://rasterio.readthedocs.io/en/latest/topics/windowed-rw.html\n        with rasterio.open(\n                local_path,\n                'w',\n                driver='GTiff',\n                height=self.extent.ymax,\n                width=self.extent.xmax,\n                count=band_count,\n                dtype=dtype,\n                transform=transform,\n                crs=crs) as dataset:\n            for window in labels.get_windows():\n                class_labels = labels.get_label_arr(\n                    window, clip_extent=self.extent)\n                clipped_window = ((window.ymin,\n                                   window.ymin + class_labels.shape[0]),\n                                  (window.xmin,\n                                   window.xmin + class_labels.shape[1]))\n                if mask is not None:\n                    mask[clipped_window[0][0]:clipped_window[0][1],\n                         clipped_window[1][0]:clipped_window[1][\n                             1]] = class_labels\n                if self.class_trans:\n                    rgb_labels = self.class_trans.class_to_rgb(class_labels)\n                    for chan in range(3):\n                        dataset.write_band(\n                            chan + 1,\n                            rgb_labels[:, :, chan],\n                            window=clipped_window)\n                else:\n                    img = class_labels.astype(dtype)\n                    dataset.write_band(1, img, window=clipped_window)\n\n        upload_or_copy(local_path, self.uri)\n\n        if self.vector_output:\n            import mask_to_polygons.vectorification as vectorification\n            import mask_to_polygons.processing.denoise as denoise\n\n            for vo in self.vector_output:\n                denoise_radius = vo['denoise']\n                uri = vo['uri']\n                mode = vo['mode']\n                class_id = vo['class_id']\n                class_mask = np.array(mask == class_id, dtype=np.uint8)\n                local_geojson_path = get_local_path(uri, self.tmp_dir)\n\n                def transform(x, y):\n                    return self.crs_transformer.pixel_to_map((x, y))\n\n                if denoise_radius > 0:\n                    class_mask = denoise.denoise(class_mask, denoise_radius)\n\n                if uri and mode == 'buildings':\n                    options = vo['building_options']\n                    geojson = vectorification.geojson_from_mask(\n                        mask=class_mask,\n                        transform=transform,\n                        mode=mode,\n                        min_aspect_ratio=options['min_aspect_ratio'],\n                        min_area=options['min_area'],\n                        width_factor=options['element_width_factor'],\n                        thickness=options['element_thickness'])\n                elif uri and mode == 'polygons':\n                    geojson = vectorification.geojson_from_mask(\n                        mask=class_mask, transform=transform, mode=mode)\n\n                if local_geojson_path:\n                    with open(local_geojson_path, 'w') as file_out:\n                        file_out.write(geojson)\n                        upload_or_copy(local_geojson_path, uri)\n\n    def empty_labels(self):\n        \"\"\"Returns an empty SemanticSegmentationLabels object.\"\"\"\n        return SemanticSegmentationLabels()\n", "path": "rastervision/data/label_store/semantic_segmentation_raster_store.py"}], "after_files": [{"content": "import pyproj\n\nfrom rasterio.transform import (rowcol, xy)\n\nfrom rastervision.data.crs_transformer import (CRSTransformer,\n                                               IdentityCRSTransformer)\n\n\nclass RasterioCRSTransformer(CRSTransformer):\n    \"\"\"Transformer for a RasterioRasterSource.\"\"\"\n\n    def __init__(self, transform, image_crs, map_crs='epsg:4326'):\n        \"\"\"Construct transformer.\n\n        Args:\n            image_dataset: Rasterio DatasetReader\n            map_crs: CRS code\n        \"\"\"\n        self.map_proj = pyproj.Proj(init=map_crs)\n        self.image_proj = pyproj.Proj(init=image_crs)\n\n        super().__init__(image_crs, map_crs, transform)\n\n    def map_to_pixel(self, map_point):\n        \"\"\"Transform point from map to pixel-based coordinates.\n\n        Args:\n            map_point: (x, y) tuple in map coordinates\n\n        Returns:\n            (x, y) tuple in pixel coordinates\n        \"\"\"\n        image_point = pyproj.transform(self.map_proj, self.image_proj,\n                                       map_point[0], map_point[1])\n        pixel_point = rowcol(self.transform, image_point[0], image_point[1])\n        pixel_point = (pixel_point[1], pixel_point[0])\n        return pixel_point\n\n    def pixel_to_map(self, pixel_point):\n        \"\"\"Transform point from pixel to map-based coordinates.\n\n        Args:\n            pixel_point: (x, y) tuple in pixel coordinates\n\n        Returns:\n            (x, y) tuple in map coordinates\n        \"\"\"\n        image_point = xy(self.transform, int(pixel_point[1]),\n                         int(pixel_point[0]))\n        map_point = pyproj.transform(self.image_proj, self.map_proj,\n                                     image_point[0], image_point[1])\n        return map_point\n\n    @classmethod\n    def from_dataset(cls, dataset, map_crs='epsg:4326'):\n        if dataset.crs is None:\n            return IdentityCRSTransformer()\n        transform = dataset.transform\n        image_crs = dataset.crs['init']\n        return cls(transform, image_crs, map_crs)\n\n    def get_affine_transform(self):\n        return self.transform\n", "path": "rastervision/data/crs_transformer/rasterio_crs_transformer.py"}, {"content": "class CRSTransformer(object):\n    \"\"\"Transforms map points in some CRS into pixel coordinates.\n\n    Each transformer is associated with a particular RasterSource.\"\"\"\n\n    def __init__(self, image_crs=None, map_crs=None, transform=None):\n        self.image_crs = image_crs\n        self.map_crs = map_crs\n        self.transform = transform\n\n    def map_to_pixel(self, map_point):\n        \"\"\"Transform point from map to pixel-based coordinates.\n\n        Args:\n            map_point: (x, y) tuple in map coordinates (eg. lon/lat)\n\n        Returns:\n            (x, y) tuple in pixel coordinates\n        \"\"\"\n        pass\n\n    def pixel_to_map(self, pixel_point):\n        \"\"\"Transform point from pixel to map-based coordinates.\n\n        Args:\n            pixel_point: (x, y) tuple in pixel coordinates\n\n        Returns:\n            (x, y) tuple in map coordinates (eg. lon/lat)\n        \"\"\"\n        pass\n\n    def get_image_crs(self):\n        return self.image_crs\n\n    def get_map_crs(self):\n        return self.map_crs\n\n    def get_affine_transform(self):\n        return self.transform\n", "path": "rastervision/data/crs_transformer/crs_transformer.py"}, {"content": "import numpy as np\nimport rasterio\n\nimport rastervision as rv\nfrom rastervision.utils.files import (get_local_path, make_dir, upload_or_copy,\n                                      file_exists)\nfrom rastervision.data.label import SemanticSegmentationLabels\nfrom rastervision.data.label_store import LabelStore\nfrom rastervision.data.label_source import SegmentationClassTransformer\n\n\nclass SemanticSegmentationRasterStore(LabelStore):\n    \"\"\"A prediction label store for segmentation raster files.\n    \"\"\"\n\n    def __init__(self,\n                 uri,\n                 extent,\n                 crs_transformer,\n                 tmp_dir,\n                 vector_output=None,\n                 class_map=None):\n        \"\"\"Constructor.\n\n        Args:\n            uri: (str) URI of GeoTIFF file used for storing predictions as RGB values\n            extent: (Box) The extent of the scene\n            crs_transformer: (CRSTransformer)\n            tmp_dir: (str) temp directory to use\n            vector_output: (None or array of dicts) containing vectorifiction\n                configuration information\n            class_map: (ClassMap) with color values used to convert class ids to\n                RGB values\n\n        \"\"\"\n        self.uri = uri\n        self.vector_output = vector_output\n        self.extent = extent\n        self.crs_transformer = crs_transformer\n        self.tmp_dir = tmp_dir\n        # Note: can't name this class_transformer due to Python using that attribute\n        if class_map:\n            self.class_trans = SegmentationClassTransformer(class_map)\n        else:\n            self.class_trans = None\n\n        self.source = None\n        if file_exists(uri):\n            self.source = rv.RasterSourceConfig.builder(rv.GEOTIFF_SOURCE) \\\n                                               .with_uri(self.uri) \\\n                                               .build() \\\n                                               .create_source(self.tmp_dir)\n\n    def _subcomponents_to_activate(self):\n        if self.source is not None:\n            return [self.source]\n        return []\n\n    def get_labels(self, chip_size=1000):\n        \"\"\"Get all labels.\n\n        Returns:\n            SemanticSegmentationLabels with windows of size chip_size covering the\n                scene with no overlap.\n        \"\"\"\n\n        def label_fn(window):\n            raw_labels = self.source.get_raw_chip(window)\n            if self.class_trans:\n                labels = self.class_trans.rgb_to_class(raw_labels)\n            else:\n                labels = np.squeeze(raw_labels)\n            return labels\n\n        extent = self.source.get_extent()\n        windows = extent.get_windows(chip_size, chip_size)\n        return SemanticSegmentationLabels(windows, label_fn)\n\n    def save(self, labels):\n        \"\"\"Save.\n\n        Args:\n            labels - (SemanticSegmentationLabels) labels to be saved\n        \"\"\"\n        local_path = get_local_path(self.uri, self.tmp_dir)\n        make_dir(local_path, use_dirname=True)\n\n        transform = self.crs_transformer.get_affine_transform()\n        crs = self.crs_transformer.get_image_crs()\n\n        band_count = 1\n        dtype = np.uint8\n        if self.class_trans:\n            band_count = 3\n\n        if self.vector_output:\n            # We need to store the whole output mask to run feature extraction.\n            # If the raster is large, this will result in running out of memory, so\n            # more work will be needed to get this to work in a scalable way. But this\n            # is complicated because of the need to merge features that are split\n            # across windows.\n            mask = np.zeros(\n                (self.extent.ymax, self.extent.xmax), dtype=np.uint8)\n        else:\n            mask = None\n\n        # https://github.com/mapbox/rasterio/blob/master/docs/quickstart.rst\n        # https://rasterio.readthedocs.io/en/latest/topics/windowed-rw.html\n        with rasterio.open(\n                local_path,\n                'w',\n                driver='GTiff',\n                height=self.extent.ymax,\n                width=self.extent.xmax,\n                count=band_count,\n                dtype=dtype,\n                transform=transform,\n                crs=crs) as dataset:\n            for window in labels.get_windows():\n                class_labels = labels.get_label_arr(\n                    window, clip_extent=self.extent)\n                clipped_window = ((window.ymin,\n                                   window.ymin + class_labels.shape[0]),\n                                  (window.xmin,\n                                   window.xmin + class_labels.shape[1]))\n                if mask is not None:\n                    mask[clipped_window[0][0]:clipped_window[0][1],\n                         clipped_window[1][0]:clipped_window[1][\n                             1]] = class_labels\n                if self.class_trans:\n                    rgb_labels = self.class_trans.class_to_rgb(class_labels)\n                    for chan in range(3):\n                        dataset.write_band(\n                            chan + 1,\n                            rgb_labels[:, :, chan],\n                            window=clipped_window)\n                else:\n                    img = class_labels.astype(dtype)\n                    dataset.write_band(1, img, window=clipped_window)\n\n        upload_or_copy(local_path, self.uri)\n\n        if self.vector_output:\n            import mask_to_polygons.vectorification as vectorification\n            import mask_to_polygons.processing.denoise as denoise\n\n            for vo in self.vector_output:\n                denoise_radius = vo['denoise']\n                uri = vo['uri']\n                mode = vo['mode']\n                class_id = vo['class_id']\n                class_mask = np.array(mask == class_id, dtype=np.uint8)\n                local_geojson_path = get_local_path(uri, self.tmp_dir)\n\n                def transform(x, y):\n                    return self.crs_transformer.pixel_to_map((x, y))\n\n                if denoise_radius > 0:\n                    class_mask = denoise.denoise(class_mask, denoise_radius)\n\n                if uri and mode == 'buildings':\n                    options = vo['building_options']\n                    geojson = vectorification.geojson_from_mask(\n                        mask=class_mask,\n                        transform=transform,\n                        mode=mode,\n                        min_aspect_ratio=options['min_aspect_ratio'],\n                        min_area=options['min_area'],\n                        width_factor=options['element_width_factor'],\n                        thickness=options['element_thickness'])\n                elif uri and mode == 'polygons':\n                    geojson = vectorification.geojson_from_mask(\n                        mask=class_mask, transform=transform, mode=mode)\n\n                if local_geojson_path:\n                    with open(local_geojson_path, 'w') as file_out:\n                        file_out.write(geojson)\n                        upload_or_copy(local_geojson_path, uri)\n\n    def empty_labels(self):\n        \"\"\"Returns an empty SemanticSegmentationLabels object.\"\"\"\n        return SemanticSegmentationLabels()\n", "path": "rastervision/data/label_store/semantic_segmentation_raster_store.py"}]}