Skip to content

Instantly share code, notes, and snippets.

@jkatagi
Created February 22, 2017 09:08
Show Gist options
  • Save jkatagi/7e4b0a97eb794558a1d17d9a543ec64a to your computer and use it in GitHub Desktop.
Save jkatagi/7e4b0a97eb794558a1d17d9a543ec64a to your computer and use it in GitHub Desktop.
#!/usr/bin/env python3
# make patch images.
import subprocess
import argparse
import os
import re
def main():
parser = argparse.ArgumentParser(usage="make patch images from satellite imgase.\n" +
"%(prog)s [img_dir] [out_dir] [size] [center_lat] [center_lon]\n" +
"ex) %(prog)s /path/to/img_dir /path/to/out_dir 10 36.1 140.1")
#parser = argparse.ArgumentParser(description="make patch images from satellite imgase.")
parser.add_argument('img_dir', action='store', type=str,
help='directory where the input images are stored.')
parser.add_argument('out_dir', action='store', type=str,
help='directory whre the output images are stored.')
parser.add_argument('size', action='store', type=int,
help='radius size of the image to cut out. ')
parser.add_argument('center_lat', action='store', type=float,
help='center latitude of the image to cut out. ')
parser.add_argument('center_lon', action='store', type=float,
help='center longitude of the image to cut out. ')
args = parser.parse_args()
# set parameter
img_dir = args.img_dir
out_dir = args.out_dir
size = args.size
center_lat = args.center_lat
center_lon = args.center_lon
# get img list from img_dir
img_list = get_img_list(img_dir)
print("start making patch images ...")
for img_file in img_list:
make_patch_image(img_dir, img_file, out_dir, center_lat, center_lon, size)
print("complete process.")
def get_img_list(imgdir):
""" get tif list from imgdir.(helper functoin.)"""
imgdir_list = os.listdir(imgdir)
img_list = [f for f in imgdir_list if re.match(r'.*tif$', f)]
return img_list
def make_patch_image(img_dir, img_file, out_dir,center_lat, center_lon, size):
""" make patch image using gdal_translate command.
input:
img_dir : img directory.
img_file: img file which you want to cut.
out_dir : save directory.
center_lat: center latitude.
centa_lon: center longitude.
size: (unit:meter)
output:
"""
# assume 1deg=110km; so 1m=9.09e-6
one_meter=9.090909090909091e-06
distance = one_meter * size # unit: degree
# set coordinate.
upper_left_x = str(center_lon - distance)
upper_left_y = str(center_lat + distance)
lower_right_x= str(center_lon + distance)
lower_right_y= str(center_lat - distance)
command = ["gdal_translate", "-projwin",
upper_left_x, upper_left_y,
lower_right_x, lower_right_y,
img_dir + "/" + img_file,
out_dir + "/" + img_file]
# run gdal_command
subprocess.run(command)
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment