Skip to content

Instantly share code, notes, and snippets.

@Seagor
Created April 25, 2016 20:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Seagor/9414b69ce4278b8ecc58e36c0d9adbbb to your computer and use it in GitHub Desktop.
Save Seagor/9414b69ce4278b8ecc58e36c0d9adbbb to your computer and use it in GitHub Desktop.
import os
import rasterio
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
def render_array(arr1, arr2=None, width=7, height=7, cmap=plt.cm.jet):
if arr2 is None:
fig, ax = plt.subplots(1, figsize=(width,height), facecolor='white')
ax.axis('off')
plt.imshow(arr1, cmap=cmap)
plt.show()
else:
fig, (ax1, ax2) = plt.subplots(nrows=1, ncols=2)
fig.set_size_inches(width, height)
ax1.imshow(arr2)
ax1.axis('off')
ax2.imshow(arr1)
ax2.axis('off')
def xy_from_coords(x_coord, y_coord, ul, lr, width, height):
x0, x1 = ul[0], lr[0]
y0, y1 = ul[1], lr[1]
x_diff = x1 - x0
y_diff = y0 - y1
xpx = ((x1 - x_coord) / x_diff) * width
if y0 - y_coord == 0.0:
ypx = height
elif y_diff != 0:
ypx = (y0 - y_coord) / y_diff * height
else:
ypx = 0
return int(abs(xpx-width)), int(ypx)
def clip_image(bbox, filepath):
with rasterio.drivers():
with rasterio.open(filepath) as src:
bounds = src.bounds
ul, lr = [bounds.left, bounds.top], [bounds.right, bounds.bottom]
r, g, b, a = src.read()
np_img = np.dstack((r, g, b, a))
ul_px = xy_from_coords(bbox[0], bbox[3], ul, lr, src.width, src.height)
lr_px = xy_from_coords(bbox[2], bbox[1], ul, lr, src.width, src.height)
return np_img[ul_px[0]:lr_px[0], ul_px[1]:lr_px[1], :]
def clip_directory(data_dir, bbox):
files = os.listdir(data_dir)
return [clip_image(bbox, os.path.join( data_dir, f )) for f in files]
bbox = [483275.7009112152, 3610083.6489744713, 486785.39847831125, 3613762.760762966]
data_dir = './san_diego_4_11_16/visual/'
clipped = clip_directory(data_dir, bbox)
fig, ax = plt.subplots(1, figsize=(5,5), facecolor='white')
ax.axis('off')
imgplot = plt.imshow(clipped[-1])
plt.show()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment