xdenisx

get_coord_from_GeoTIFF

Sep 2nd, 2013
127
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 6.18 KB | None | 0 0
  1. # -*- coding: utf-8 -*-
  2. from osgeo import osr, gdal
  3. import sys
  4. import shapefile as sf
  5. import math
  6. import psycopg2
  7.  
  8. # 2013/09/03
  9.  
  10. # USAGE:
  11. # python get_coord.py ps_RS2_20130829_072059_0076_SCWA_HHHV_SGF_279190_9158_8821989.zip.tif 20130829-20130830.txt
  12.  
  13. def create_table():
  14.     try:
  15.         conn = psycopg2.connect(database='gis', user='gisuser')
  16.         curs = conn.cursor()
  17.         # Try create db for IAPB data
  18.         curs.execute("""CREATE TABLE my_drift (id integer, date1 date, date2 date, geom1 geometry, geom2 geometry)""")
  19.         conn.commit()  
  20.         conn.close()
  21.     except:
  22.         print 'The table already exist or could not be created!'
  23.  
  24. def insert_data(iid,idate1,idate2,ilon1,ilat1,ilon2,ilat2):
  25.     ''' Insert data into DB '''
  26.     try:
  27.         conn = psycopg2.connect(database='gis', user='gisuser')
  28.         curs = conn.cursor()
  29.         sql = "INSERT INTO my_drift (id,date1,date2,geom1,geom2) VALUES (%s,\'%s\',\'%s\',ST_GeomFromText(%s),ST_GeomFromText(%s));" % \
  30.         (iid,idate1,idate2,'\'POINT( %s %s )\'' % (ilon1,ilat1),'\'POINT( %s %s )\'' % (ilon2,ilat2))
  31.         #params = [int(id),dt_str,'POINT( %s %s )' % (lon,lat)]
  32.         #print sql
  33.         curs.execute(sql)
  34.         conn.commit()
  35.         conn.close()
  36.         print 'OK! Data inserted!'
  37.     except:
  38.         print 'Insert error!'  
  39.  
  40. def big_circle(llat1,llong1,llat2,llong2):
  41.     #pi - число pi, rad - радиус сферы (Земли)
  42.     rad = 6372795
  43.  
  44.     #в радианах
  45.     lat1 = llat1*math.pi/180.
  46.     lat2 = llat2*math.pi/180.
  47.     long1 = llong1*math.pi/180.
  48.     long2 = llong2*math.pi/180.
  49.  
  50.     #косинусы и синусы широт и разницы долгот
  51.     cl1 = math.cos(lat1)
  52.     cl2 = math.cos(lat2)
  53.     sl1 = math.sin(lat1)
  54.     sl2 = math.sin(lat2)
  55.     delta = long2 - long1
  56.     cdelta = math.cos(delta)
  57.     sdelta = math.sin(delta)
  58.  
  59.     #вычисления длины большого круга
  60.     y = math.sqrt(math.pow(cl2*sdelta,2)+math.pow(cl1*sl2-sl1*cl2*cdelta,2))
  61.     x = sl1*sl2+cl1*cl2*cdelta
  62.     ad = math.atan2(y,x)
  63.     dist = (ad*rad) #/1000. [m]
  64.  
  65.     #вычисление начального азимута
  66.     x = (cl1*sl2) - (sl1*cl2*cdelta)
  67.     y = sdelta*cl2
  68.     z = math.degrees(math.atan(-y/x))
  69.  
  70.     if (x < 0):
  71.         z = z+180.
  72.  
  73.     z2 = (z+180.) % 360. - 180.
  74.     z2 = - math.radians(z2)
  75.     anglerad2 = z2 - ((2*math.pi)*math.floor((z2/(2*math.pi))) )
  76.     angledeg = (anglerad2*180.)/math.pi
  77.  
  78.     print 'Distance >> %.2f' % dist, ' [km]'
  79.     print 'Initial bearing >> %.0f ' % angledeg, '[degrees]\n'
  80.     return '%.0f' % dist, '%.0f' % angledeg
  81.  
  82. def read_res_file(res_file):
  83.     ''' Readlines of out file with vectors '''
  84.     ff = open(res_file)
  85.     lines = ff.readlines()
  86.     # Exclude 1st str
  87.     lines = lines[1:]
  88.  
  89.     # Start make shape here
  90.     shp_name = res_file.split('.')[0]
  91.     shp_filename = "shp/" + shp_name
  92.     #create the shapefile
  93.     w = sf.Writer(sf.POLYLINE)
  94.     w.field('vector_num','C','40')
  95.     w.field('Magnitude','C','40')
  96.     w.field('Azimuth','C','40')
  97.     i = 0
  98.     # Create txt file
  99.     ff_txt = open('txt/%s.txt' % shp_name,'w')
  100.     for line in lines:
  101.         xx1 = line.split()[0]
  102.         yy1 = line.split()[1]
  103.         xx2 = line.split()[2]
  104.         yy2 = line.split()[3]
  105.        
  106.         print 'x1: %s' % xx1
  107.         print 'y1: %s' % yy1
  108.         x1 = gt[0] + float(xx1)*pixelWidth
  109.         y1 = gt[3] + float(yy1)*pixelHeight
  110.         latlon = transform.TransformPoint(float(x1),float(y1))
  111.         print latlon
  112.         lon1 = latlon[0]
  113.         lat1 = latlon[1]
  114.  
  115.         print 'x2: %s' % xx2
  116.         print 'y2: %s' % yy2
  117.         x2 = gt[0] + float(xx2)*pixelWidth
  118.         y2 = gt[3] + float(yy2)*pixelHeight
  119.         latlon = transform.TransformPoint(float(x2),float(y2))
  120.         print latlon
  121.         # Length in [meters]
  122.         length = math.hypot(x2-x1,y2-y1)
  123.         print 'Length: %.2f [km]' % (math.hypot(x2-x1,y2-y1)/1000.)        
  124.         lon2 = latlon[0]
  125.         lat2 = latlon[1]
  126.  
  127.         w.line(parts=[[[lon1, lat1],[lon2, lat2]]])
  128.  
  129.         # Big circle length
  130.         mag, az = big_circle(float(lat1),float(lon1),float(lat2),float(lon2))
  131.  
  132.         w.record(str(i),str(mag),str(az))
  133.  
  134.         ff_txt.write('%5.2f %5.2f %5.2f %5.2f\n' % (lon1,lat1,lon2,lat2))
  135.  
  136.         # 2DB
  137.         idate1 = res_file.split('.')[0][0:4] + '-' + res_file.split('.')[0][4:6] + '-' + res_file.split('.')[0][6:8]
  138.         idate2 = (res_file.split('.')[0]).split('-')[-1][0:4] + '-' + (res_file.split('.')[0][4:6]).split('-')[-1] + '-' + (res_file.split('.')[0]).split('-')[-1][6:8]
  139.         insert_data(i,idate1,idate2,lon1,lat1,lon2,lat2)
  140.  
  141.         i = i + 1
  142.     ff.close()
  143.     ff_txt.close()
  144.  
  145.     # Save shape
  146.     w.save(shp_filename)
  147.     # create the PRJ file
  148.     prjfn = shp_filename[:]
  149.     prj = open("%s.prj" % prjfn, "w")
  150.     epsg = 'GEOGCS["WGS 84",DATUM["WGS_1984",SPHEROID["WGS 84",6378137,298.257223563]],PRIMEM["Greenwich",0],UNIT["degree",0.0174532925199433]]'
  151.     prj.write(epsg)
  152.     prj.close()
  153.  
  154.     return latlon
  155.  
  156. # get the existing coordinate system
  157. in_file = sys.argv[1]
  158. res_file = sys.argv[2]
  159.  
  160. ds = gdal.Open(in_file)
  161. old_cs= osr.SpatialReference()
  162. old_cs.ImportFromWkt(ds.GetProjectionRef())
  163.  
  164. # create the new coordinate system
  165. wgs84_wkt = """
  166. GEOGCS["WGS 84",
  167.    DATUM["WGS_1984",
  168.        SPHEROID["WGS 84",6378137,298.257223563,
  169.            AUTHORITY["EPSG","7030"]],
  170.        AUTHORITY["EPSG","6326"]],
  171.    PRIMEM["Greenwich",0,
  172.        AUTHORITY["EPSG","8901"]],
  173.    UNIT["degree",0.01745329251994328,
  174.        AUTHORITY["EPSG","9122"]],
  175.    AUTHORITY["EPSG","4326"]]"""
  176. new_cs = osr.SpatialReference()
  177. new_cs.ImportFromWkt(wgs84_wkt)
  178.  
  179. # create a transform object to convert between coordinate systems
  180. transform = osr.CoordinateTransformation(old_cs,new_cs)
  181.  
  182. #get the point to transform, pixel (0,0) in this case
  183. width = ds.RasterXSize
  184. height = ds.RasterYSize
  185. gt = ds.GetGeoTransform()
  186.  
  187. originX = gt[0]
  188. originY = gt[3]
  189. pixelWidth = gt[1]
  190. pixelHeight = gt[5]
  191.  
  192.  
  193. minx = gt[0]
  194. miny = gt[3] + width*gt[4] + height*gt[5]
  195.  
  196. #get the coordinates in lat long
  197.  
  198. latlon=read_res_file(res_file)
  199.  
  200. #latlong = transform.TransformPoint(3725,32)
Advertisement
Add Comment
Please, Sign In to add comment