/usr/lib/python3/dist-packages/rasterio/tool.py is in python3-rasterio 0.31.0-2build1.
This file is owned by root:root, with mode 0o644.
The actual contents of the file can be viewed below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 | import code
import collections
import logging
try:
import matplotlib.pyplot as plt
except ImportError:
plt = None
import numpy
import rasterio
from rasterio.five import zip_longest
logger = logging.getLogger('rasterio')
Stats = collections.namedtuple('Stats', ['min', 'max', 'mean'])
# Collect dictionary of functions for use in the interpreter in main()
funcs = locals()
def show(source, cmap='gray'):
"""Show a raster using matplotlib.
The raster may be either an ndarray or a (dataset, bidx)
tuple.
"""
if isinstance(source, tuple):
arr = source[0].read(source[1])
else:
arr = source
if plt is not None:
plt.imshow(arr, cmap=cmap)
plt.show()
else:
raise ImportError("matplotlib could not be imported")
def stats(source):
"""Return a tuple with raster min, max, and mean.
"""
if isinstance(source, tuple):
arr = source[0].read(source[1])
else:
arr = source
return Stats(numpy.min(arr), numpy.max(arr), numpy.mean(arr))
def show_hist(source, bins=10, masked=True, title='Histogram'):
"""
Easily display a histogram with matplotlib.
Parameters
----------
bins : int, optional
Compute histogram across N bins.
data : np.array or rasterio.Band or tuple(dataset, bidx)
Input data to display. The first three arrays in multi-dimensional
arrays are plotted as red, green, and blue.
masked : bool, optional
When working with a `rasterio.Band()` object, specifies if the data
should be masked on read.
title : str, optional
Title for the figure.
"""
if plt is None:
raise ImportError("Could not import matplotlib")
if isinstance(source, (tuple, rasterio.Band)):
arr = source[0].read(source[1], masked=masked)
else:
arr = source
# The histogram is computed individually for each 'band' in the array
# so we need the overall min/max to constrain the plot
rng = arr.min(), arr.max()
if len(arr.shape) is 2:
arr = [arr]
colors = ['gold']
else:
colors = ('red', 'green', 'blue', 'violet', 'gold', 'saddlebrown')
# If a rasterio.Band() is given make sure the proper index is displayed
# in the legend.
if isinstance(source, (tuple, rasterio.Band)):
labels = [str(source[1])]
else:
labels = (str(i + 1) for i in range(len(arr)))
# This loop should add a single plot each band in the input array,
# regardless of if the number of bands exceeds the number of colors.
# The colors slicing ensures that the number of iterations always
# matches the number of bands.
# The goal is to provide a curated set of colors for working with
# smaller datasets and let matplotlib define additional colors when
# working with larger datasets.
for bnd, color, label in zip_longest(arr, colors[:len(arr)], labels):
plt.hist(
bnd.flatten(),
bins=bins,
alpha=0.5,
color=color,
label=label,
range=rng
)
plt.legend(loc="upper right")
plt.title(title, fontweight='bold')
plt.grid(True)
plt.xlabel('DN')
plt.ylabel('Frequency')
plt.show()
def main(banner, dataset, alt_interpreter=None):
""" Main entry point for use with python interpreter """
local = dict(funcs, src=dataset, np=numpy, rio=rasterio, plt=plt)
if not alt_interpreter:
code.interact(banner, local=local)
elif alt_interpreter == 'ipython':
import IPython
IPython.InteractiveShell.banner1 = banner
IPython.start_ipython(argv=[], user_ns=local)
else:
raise ValueError("Unsupported interpreter '%s'" % alt_interpreter)
return 0
|