Ejemplo n.º 1
0
def height_map_error(self, image_id):
  
  import numpy as np

  import vpgl_adaptor_boxm2_batch as vpgl_adaptor
  
  from vsi.io.image import imread, GdalReader
  
  from voxel_globe.meta import models
  import voxel_globe.tools
  from voxel_globe.tools.celery import Popen

  from vsi.tools.file_util import lncp

  tie_points_yxz = []
  control_points_yxz = []

  image = models.Image.objects.get(id=image_id)

  height_reader =  GdalReader(image.filename_path, autoload=True)
  transform = height_reader.object.GetGeoTransform()
  height = height_reader.raster()
  del height_reader

  tie_points = image.tiepoint_set.all()

  for tie_point in tie_points:
    lla_xyz = tie_point.control_point.point.coords
    control_points_yxz.append([lla_xyz[x] for x in [1,0,2]])
    tie_points_yxz.append([transform[4]*(tie_point.point.coords[0]+0.5) + transform[5]*(tie_point.point.coords[1]+0.5) + transform[3],
                           transform[1]*(tie_point.point.coords[0]+0.5) + transform[2]*(tie_point.point.coords[1]+0.5) + transform[0],
                           height[tie_point.point.coords[1], tie_point.point.coords[0]]])

  origin_yxz = np.mean(np.array(control_points_yxz), axis=0)
  tie_points_local = []
  control_points_local = []
  lvcs = vpgl_adaptor.create_lvcs(origin_yxz[0], origin_yxz[1], origin_yxz[2], 'wgs84')

  for tie_point in tie_points_yxz:
    tie_points_local.append(vpgl_adaptor.convert_to_local_coordinates2(lvcs, *tie_point))

  for control_point in control_points_yxz:
    control_points_local.append(vpgl_adaptor.convert_to_local_coordinates2(lvcs, *control_point))

  error = np.linalg.norm(np.array(tie_points_local)-np.array(control_points_local), axis=0)/(len(tie_points_local)**0.5)

  result={}
  result['error'] = list(error)
  result['horizontal_accuracy'] = 2.4477*0.5*(error[0]+error[1])
  result['vertical_accuracy'] = 1.96*error[2]

  return result
Ejemplo n.º 2
0
def get_point_cloud(point_cloud_id, number_points=None):
  from voxel_globe.meta import models
  from vpgl_adaptor_boxm2_batch import convert_local_to_global_coordinates_array, create_lvcs
  import os
  import numpy as np
  from plyfile import PlyData

  point_cloud = models.PointCloud.objects.get(id=point_cloud_id)

  lvcs = create_lvcs(point_cloud.origin[1], point_cloud.origin[0], point_cloud.origin[2], 'wgs84')

  ply = PlyData.read(str(point_cloud.filename_path))

  data = ply.elements[0].data

  if number_points:
    try:
      import heapq
      data = np.array(heapq.nlargest(number_points, ply.elements[0].data, 
                                     key=lambda x:x['prob']))
    except IndexError: #not a correctly formated ply file. HACK A CODE!
      #This is a hack-a-code for Tom's ply file
      data = ply.elements[0].data.astype([('x', '<f4'), ('y', '<f4'), 
          ('z', '<f4'), ('red', 'u1'), ('green', 'u1'), ('blue', 'u1'), 
          ('prob', '<f4')])
      import copy
      blah = copy.deepcopy(data['y'])
      data['y'] = data['z']
      data['z'] = -blah

      data['prob'] = abs(data['x'] - 10 - sum(data['x'])/len(data['x'])) \
                   + abs(data['y'] + 30 - sum(data['y'])/len(data['y'])) \
                   + abs(data['z'] - sum(data['z'])/len(data['z']))
      data['prob'] = max(data['prob']) - data['prob']

      data = np.array(heapq.nlargest(number_points, data, 
                                     key=lambda x:x['prob']))
      print data['prob']



  
  lla = convert_local_to_global_coordinates_array(lvcs, data['x'].tolist(), data['y'].tolist(), data['z'].tolist())

  latitude = np.array(lla[0])
  longitude = np.array(lla[1])
  altitude = np.array(lla[2])
  color = map(lambda r,g,b:'#%02x%02x%02x' % (r, g, b), data['red'], data['green'], data['blue'])

  return_data = {"latitude": latitude, "longitude": longitude,
                 "altitude": altitude, "color": color}

  try:
    return_data['le'] = data['le']
  except ValueError:
    return_data['le'] = (-np.ones(len(latitude))).tolist()
  try:
    return_data['ce'] = data['ce']
  except ValueError:
    return_data['ce'] = (-np.ones(len(latitude))).tolist()

  return return_data
Ejemplo n.º 3
0
def create_scene_xml(gpu_device, refinements, gsd,
                     lla1=None, lla2=None, lvcs1=None, lvcs2=None,
                     origin=None, output_file=sys.stdout, model_dir = ".",
                     appearance_models=None, number_bins=1,
                     n_bytes_gpu=None):
  ''' Create a scene xml file based off of input parameters

      Required arguments:
      gpu_device - The GPU device used for the block size calculation. The
      scene will be made to fit specifically on that gpu device
      refinements - Number of refinement passes. Max should be 3, even if you
      refine more times than 3 times. gsd - The desired voxel size. This is in
      meters when using lla notation

      Mutually exclusive arguments:
      lla1,lla2 - The min and max (in order) longitude, latitude, altitude
      coordinates for bounding box of the scene. Will be expanded to the next
      sublock
      lvcs1, lvcs2 - The min and max (in order) x, y, z coordinates for
      bounding box of the scene. Will be expanded to the next sublock

      Optional arguments:
      origin - Origin of scene. Default: lla1 or (0,0,0) if lvcs1 is used
      output_file - Output file object. Must support .write.
      Default: sys.stdout
      model_dir - The model dir used. is_model_local="true" is always used
      Default: "."
      appearance_models - Tuple of appearance models to be used.
      Default: ('boxm2_mog3_grey','boxm2_num_obs')
      number_bins - Sets the num_illumination_bins. Default: 1
      n_bytes_gpu - Optional override gpu_device memory size. Useful for CPU
      OpenCL
      '''

  #impose mutually exclusive constraint
  assert(lla1 is None or lvcs1 is None)
  assert(lla2 is None or lvcs2 is None)

  if origin is None:
    if lla1 is None:
      origin = (0,0,0)
    else:
      origin = lla1


  if lvcs1 is None or lvcs2 is None:
    lvcs = vpgl_adaptor.create_lvcs(lat=origin[1], lon=origin[0], el=origin[2],
                                    csname="wgs84")

  # transform the coordinate system from lat/lon/height to a lvcs (meters) with
  # the origin at one corner of the scene
  if lvcs1 is None:
    lvcs1 = vpgl_adaptor.convert_to_local_coordinates2(lvcs,
        lla1[1], lla1[0], lla1[2])

  if lvcs2 is None:
    lvcs2 = vpgl_adaptor.convert_to_local_coordinates2(lvcs,
        lla2[1], lla2[0], lla2[2])

  lvcs_size = map(lambda x,y:y-x, lvcs1, lvcs2)

  if n_bytes_gpu==None:
    n_bytes_gpu = gpu_memory(gpu_device)

  (n_blocks, n_subblocks, subblock_len) = calculate_block_parameters(
      n_bytes_gpu, refinements, gsd, lvcs_size)

  generate_scene_xml(output_file, model_dir,
      num_blocks=n_blocks, num_subblocks=n_subblocks,
      subblock_size=subblock_len, appearance_models=appearance_models,
      num_bins=number_bins, max_level=refinements+1, lvcs_og=origin,
      local_og=lvcs1)
Ejemplo n.º 4
0
def tiepoint_registration(self, image_set_id, camera_set_id):
  from PIL import Image
  import numpy as np

  from django.contrib.gis.geos import Point

  import vpgl_adaptor_boxm2_batch as vpgl_adaptor

  from vsi.io.krt import Krt

  from voxel_globe.meta import models
  import voxel_globe.tools
  from voxel_globe.tools.camera import get_krt, save_krt
  from voxel_globe.tools.celery import Popen

  from voxel_globe.tools.xml_dict import load_xml
  
  self.update_state(state='INITIALIZE', meta={'id':image_set_id})

  image_set = models.ImageSet.objects.get(id=image_set_id)

  control_points = {}

  for fr,image in enumerate(image_set.images.all()):
    tiepoints = image.tiepoint_set.all() 
    for tiepoint in tiepoints:
      #demoware code hack!
      if 'error' in tiepoint.control_point.name.lower():
        continue
      if tiepoint.control_point.id not in control_points:
        control_points[tiepoint.control_point.id] = {'tiepoints':{}}
      control_points[tiepoint.control_point.id]['tiepoints'][fr] = list(tiepoint.point)
      lla_xyz = tiepoint.control_point.point.coords
      control_points[tiepoint.control_point.id]['3d'] = [lla_xyz[x] for x in [1,0,2]]

  #filter only control points with more than 1 tiepoint
  control_points = {k:v for k,v in control_points.iteritems() if len(v['tiepoints'].keys()) > 1}

  origin_yxz = np.mean([v['3d'] for k,v in control_points.iteritems()], axis=0)
  lvcs = vpgl_adaptor.create_lvcs(origin_yxz[0], origin_yxz[1], origin_yxz[2], 'wgs84')
  for control_point in control_points:
    control_points[control_point]['lvcs'] = vpgl_adaptor.convert_to_local_coordinates2(lvcs, *control_points[control_point]['3d'])

  images = {}

  with voxel_globe.tools.task_dir('tiepoint_registration', cd=True) as processing_dir:
    dummy_imagename = os.path.join(processing_dir, 'blank.jpg')
    img = Image.fromarray(np.empty([1,1], dtype=np.uint8))
    img.save(dummy_imagename)
    #Thank you stupid site file
      
    for fr,image in enumerate(image_set.images.all()):
      (K,R,T,o) = get_krt(image, camera_set_id)
      images[fr] = image.id

      with open(os.path.join(processing_dir, 'frame_%05d.txt' % fr), 'w') as fid:
        print >>fid, (("%0.18f "*3+"\n")*3) % (K[0,0], K[0,1], K[0,2], 
            K[1,0], K[1,1], K[1,2], K[2,0], K[2,1], K[2,2])
        print >>fid, (("%0.18f "*3+"\n")*3) % (R[0,0], R[0,1], R[0,2], 
            R[1,0], R[1,1], R[1,2], R[2,0], R[2,1], R[2,2])
        print >>fid, ("%0.18f "*3+"\n") % (T[0,0], T[1,0], T[2,0])
    site_in_name = os.path.join(processing_dir, 'site.xml')
    site_out_name = os.path.join(processing_dir, 'site2.xml')
    with open(site_in_name, 'w') as fid:
      fid.write('''<BWM_VIDEO_SITE name="Triangulation">
  <videoSiteDir path="%s">
  </videoSiteDir>
  <videoPath path="%s">
  </videoPath>
  <cameraPath path="%s/*.txt">
  </cameraPath>
  <Objects>
  </Objects>ve
  <Correspondences>\n''' % (processing_dir, dummy_imagename, processing_dir))
      for control_point_index, control_point_id in enumerate(control_points):
        fid.write('<Correspondence id="%d">\n' % control_point_index)
        for fr, tie_point in control_points[control_point_id]['tiepoints'].iteritems():
          fid.write('<CE fr="%d" u="%f" v="%f"/>\n' % (fr, tie_point[0], tie_point[1]))
        fid.write('</Correspondence>\n')
        control_points[control_point_id]['id'] = control_point_index
      fid.write('''</Correspondences>
  </BWM_VIDEO_SITE>\n''')
    
    #triangulate the points
    Popen(['bwm_triangulate_2d_corrs', '-site', site_in_name, '-out', site_out_name], logger=logger).wait()

    #Read in the result, and load into points_triangulate structure
    xml = load_xml(site_out_name)
    points_triangulate = {'id':[], 'x':[], 'y':[], 'z':[]}
    for correspondence in xml['Correspondences']['Correspondence']:
      points_triangulate['id'].append(int(correspondence.at['id']))
      points_triangulate['x'].append(float(correspondence['corr_world_point'].at['X']))
      points_triangulate['y'].append(float(correspondence['corr_world_point'].at['Y']))
      points_triangulate['z'].append(float(correspondence['corr_world_point'].at['Z']))
      
    #Read the points out of the control points structure, but make sure they are 
    #in the same order (check id == point_id
    points_orig = {'x':[], 'y':[], 'z':[]}
    for point_id in points_triangulate['id']:
      point = [v['lvcs'] for k,v in control_points.iteritems() if v['id'] == point_id]
      points_orig['x'].append(point[0][0])
      points_orig['y'].append(point[0][1])
      points_orig['z'].append(point[0][2])
    new_cameras = os.path.join(processing_dir, 'new_cameras')
    os.mkdir(new_cameras)
    
    #Make transformation
    transform, scale = vpgl_adaptor.compute_transformation(points_triangulate['x'], points_triangulate['y'], points_triangulate['z'],
                                        points_orig['x'],points_orig['y'],points_orig['z'],
                                        processing_dir, new_cameras)

    #calculate the new bounding box
    bbox_min, bbox_max = vpgl_adaptor.compute_transformed_box(list(image_set.scene.bbox_min), list(image_set.scene.bbox_max), transform)
    
    #calculate the new voxel size
    default_voxel_size=Point(*(x*scale for x in image_set.scene.default_voxel_size))
    
    scene = models.Scene(name="Tie Point Registered %s" % (image_set.scene.name,), 
                         service_id=self.request.id,
                         origin=Point(origin_yxz[1], origin_yxz[0], origin_yxz[2]),
                         bbox_min=Point(*bbox_min),
                         bbox_max=Point(*bbox_max),
                         default_voxel_size=default_voxel_size,
                         geolocated=True)
    scene.save()
    image_set.scene=scene
    image_set.save()

    camera_set=voxel_globe.meta.models.CameraSet(\
        name="%s" % (image_set.scene.name,),
        images=image_set, service_id=self.request.id)
    camera_set.save()

    for fr, image_id in images.iteritems():
      krt = Krt.load(os.path.join(new_cameras, 'frame_%05d.txt' % fr))
      image = models.Image.objects.get(id=image_id)
      camera = save_krt(self.request.id, image, krt.k, krt.r, krt.t, [origin_yxz[x] for x in [1,0,2]], srid=4326)
      camera_set.cameras.add(camera)
Ejemplo n.º 5
0
def tiepoint_error_calculation(self, image_set_id, camera_set_id, scene_id):
  from PIL import Image
  import numpy as np

  import vpgl_adaptor_boxm2_batch as vpgl_adaptor

  from voxel_globe.meta import models
  import voxel_globe.tools
  from voxel_globe.tools.camera import get_krt
  from voxel_globe.tools.celery import Popen

  from voxel_globe.tools.xml_dict import load_xml, XmlListConfig, XmlList

  self.update_state(state='INITIALIZE', meta={'id':image_set_id, 'scene':scene_id})

  image_set = models.ImageSet.objects.get(id=image_set_id)

  control_points = {}

  for fr,image in enumerate(image_set.images.all()):
    tiepoints = image.tiepoint_set.all() 
    for tiepoint in tiepoints:
      #demoware code hack!
      if tiepoint.control_point.id not in control_points:
        control_points[tiepoint.control_point.id] = {'tiepoints':{}}
      control_points[tiepoint.control_point.id]['tiepoints'][fr] = list(tiepoint.point)
      lla_xyz = tiepoint.control_point.point.coords
      control_points[tiepoint.control_point.id]['3d'] = [lla_xyz[x] for x in [1,0,2]]

  #filter only control points with more than 1 tiepoint
  control_points = {k:v for k,v in control_points.iteritems() if len(v['tiepoints'].keys()) > 1}

  origin_xyz = list(models.Scene.objects.get(id=scene_id).origin)
  lvcs = vpgl_adaptor.create_lvcs(origin_xyz[1], origin_xyz[0], origin_xyz[2], 'wgs84')
  for control_point in control_points:
    control_points[control_point]['lvcs'] = vpgl_adaptor.convert_to_local_coordinates2(lvcs, *control_points[control_point]['3d'])

  with voxel_globe.tools.task_dir('tiepoint_error_calculation', cd=True) as processing_dir:
    dummy_imagename = os.path.join(processing_dir, 'blank.jpg')
    img = Image.fromarray(np.empty([1,1], dtype=np.uint8))
    img.save(dummy_imagename)
    #Thank you stupid site file
      
    for fr,image in enumerate(image_set.images.all()):
      (K,R,T,o) = get_krt(image, camera_set_id)

      with open(os.path.join(processing_dir, 'frame_%05d.txt' % fr), 'w') as fid:
        print >>fid, (("%0.18f "*3+"\n")*3) % (K[0,0], K[0,1], K[0,2], 
            K[1,0], K[1,1], K[1,2], K[2,0], K[2,1], K[2,2])
        print >>fid, (("%0.18f "*3+"\n")*3) % (R[0,0], R[0,1], R[0,2], 
            R[1,0], R[1,1], R[1,2], R[2,0], R[2,1], R[2,2])
        print >>fid, ("%0.18f "*3+"\n") % (T[0,0], T[1,0], T[2,0])
    site_in_name = os.path.join(processing_dir, 'site.xml')
    site_out_name = os.path.join(processing_dir, 'site2.xml')
    with open(site_in_name, 'w') as fid:
      fid.write('''<BWM_VIDEO_SITE name="Triangulation">
<videoSiteDir path="%s">
</videoSiteDir>
<videoPath path="%s">
</videoPath>
<cameraPath path="%s/*.txt">
</cameraPath>
<Objects>
</Objects>
<Correspondences>\n''' % (processing_dir, dummy_imagename, processing_dir))
      for control_point_index, control_point_id in enumerate(control_points):
        fid.write('<Correspondence id="%d">\n' % control_point_index)
        for fr, tie_point in control_points[control_point_id]['tiepoints'].iteritems():
          fid.write('<CE fr="%d" u="%f" v="%f"/>\n' % (fr, tie_point[0], tie_point[1]))
        fid.write('</Correspondence>\n')
        control_points[control_point_id]['id'] = control_point_index
      fid.write('''</Correspondences>
</BWM_VIDEO_SITE>\n''')
    
    #triangulate the points
    Popen(['bwm_triangulate_2d_corrs', '-site', site_in_name, '-out', site_out_name], logger=logger).wait()

    #Read in the result, and load into points_triangulate structure
    xml = load_xml(site_out_name)
    points_triangulate_id=[]
    points_triangulate=[]
    correspondences = xml['Correspondences']['Correspondence']
    if not isinstance(correspondences, XmlListConfig) and not isinstance(correspondences, XmlList):
      correspondences = [correspondences]
    for correspondence in correspondences:
      points_triangulate_id.append(int(correspondence.at['id']))
      points_triangulate.append((float(correspondence['corr_world_point'].at['X']),
                                 float(correspondence['corr_world_point'].at['Y']),
                                 float(correspondence['corr_world_point'].at['Z'])))
      
    #Read the points out of the control points structure, but make sure they are 
    #in the same order (check id == point_id
    points_orig = []
    for point_id in points_triangulate_id:
      point = [v['lvcs'] for k,v in control_points.iteritems() if v['id'] == point_id]
      points_orig.append(point[0])  

  points_orig = np.array(points_orig)
  points_triangulate = np.array(points_triangulate)
  error = np.linalg.norm((points_orig-points_triangulate), axis=0)/(points_orig.shape[0]**0.5)

  result={}
  result['error'] = list(error)
  result['horizontal_accuracy'] = 2.4477*0.5*(error[0]+error[1])
  result['vertical_accuracy'] = 1.96*error[2]

  return result
Ejemplo n.º 6
0
def get_point_cloud(point_cloud_id, number_points=None):
    from voxel_globe.meta import models
    from vpgl_adaptor_boxm2_batch import convert_local_to_global_coordinates_array, create_lvcs
    import os
    import numpy as np
    from plyfile import PlyData

    point_cloud = models.PointCloud.objects.get(id=point_cloud_id)

    lvcs = create_lvcs(point_cloud.origin[1], point_cloud.origin[0],
                       point_cloud.origin[2], 'wgs84')

    ply = PlyData.read(str(point_cloud.filename_path))

    data = ply.elements[0].data

    if number_points:
        try:
            import heapq
            data = np.array(
                heapq.nlargest(number_points,
                               ply.elements[0].data,
                               key=lambda x: x['prob']))
        except IndexError:  #not a correctly formated ply file. HACK A CODE!
            #This is a hack-a-code for Tom's ply file
            data = ply.elements[0].data.astype([('x', '<f4'), ('y', '<f4'),
                                                ('z', '<f4'), ('red', 'u1'),
                                                ('green', 'u1'),
                                                ('blue', 'u1'),
                                                ('prob', '<f4')])
            import copy
            blah = copy.deepcopy(data['y'])
            data['y'] = data['z']
            data['z'] = -blah

            data['prob'] = abs(data['x'] - 10 - sum(data['x'])/len(data['x'])) \
                         + abs(data['y'] + 30 - sum(data['y'])/len(data['y'])) \
                         + abs(data['z'] - sum(data['z'])/len(data['z']))
            data['prob'] = max(data['prob']) - data['prob']

            data = np.array(
                heapq.nlargest(number_points, data, key=lambda x: x['prob']))
            print data['prob']

    lla = convert_local_to_global_coordinates_array(lvcs, data['x'].tolist(),
                                                    data['y'].tolist(),
                                                    data['z'].tolist())

    latitude = np.array(lla[0])
    longitude = np.array(lla[1])
    altitude = np.array(lla[2])
    color = map(lambda r, g, b: '#%02x%02x%02x' % (r, g, b), data['red'],
                data['green'], data['blue'])

    return_data = {
        "latitude": latitude,
        "longitude": longitude,
        "altitude": altitude,
        "color": color
    }

    try:
        return_data['le'] = data['le']
    except ValueError:
        return_data['le'] = (-np.ones(len(latitude))).tolist()
    try:
        return_data['ce'] = data['ce']
    except ValueError:
        return_data['ce'] = (-np.ones(len(latitude))).tolist()

    return return_data
Ejemplo n.º 7
0
def update_geometry_polygon(request):
    import voxel_globe.meta.models as models
    from django.contrib.gis.geos import Point, Polygon, GEOSGeometry
    import numpy as np
    import brl_init
    import vpgl_adaptor_boxm2_batch as vpgl_adaptor

    image_id = int(request.POST['image_id'])
    points = GEOSGeometry(request.POST['points'])
    sattelgeometryobject_id = int(request.POST['sattelgeometryobject_id'])
    site_id = int(request.POST['site_id'])
    projection_mode = request.POST['projection_mode']

    site = models.SattelSite.objects.get(id=site_id)
    image = models.Image.objects.get(id=image_id)
    camera = image.camera_set.filter(
        cameraset=site.camera_set).select_subclasses('rpccamera')[0]
    sattelgeometryobject = models.SattelGeometryObject.objects.get(
        id=sattelgeometryobject_id)

    vpgl_camera = vpgl_adaptor.load_rational_camera_from_txt(camera.rpc_path)
    initial_guess = np.mean(image.attributes['planet_rest_response']
                            ['geometry']['coordinates'][0][0:4],
                            axis=0)
    initial_guess = np.hstack((initial_guess, 0))  #elevation guess is 0

    lvcs_points = []

    gps_points = []

    if projection_mode == "z-plane":
        projection_height = float(request.POST['height'])

        for point in points.coords[0]:
            point = vpgl_adaptor.get_rpc_backprojected_ray(
                vpgl_camera, point[0], point[1], projection_height,
                initial_guess[0], initial_guess[1], initial_guess[2])
            gps_points.append(point)

    origin = np.array(gps_points).mean(axis=0)

    lvcs = vpgl_adaptor.create_lvcs(origin[1], origin[0], origin[2], "wgs84")
    origin = Point(*origin)

    for point in gps_points:
        point = vpgl_adaptor.convert_to_local_coordinates2(
            lvcs, point[1], point[0], point[2])

        lvcs_points.append(point)

    print sattelgeometryobject.geometry_path

    if sattelgeometryobject.geometry_path and os.path.exists(
            sattelgeometryobject.geometry_path):
        os.remove(sattelgeometryobject.geometry_path)

    geometry_filepath = write_ply_file(lvcs_points)
    sattelgeometryobject.geometry_path = geometry_filepath
    sattelgeometryobject.origin = origin
    sattelgeometryobject.geometry = Polygon(gps_points + gps_points[0:1])
    sattelgeometryobject.save()
    from django.shortcuts import HttpResponse
    return HttpResponse('{}', content_type="application/json")
Ejemplo n.º 8
0
def height_map_error(self, image_id):

    import numpy as np

    import vpgl_adaptor_boxm2_batch as vpgl_adaptor

    from vsi.io.image import imread, GdalReader

    from voxel_globe.meta import models
    import voxel_globe.tools
    from voxel_globe.tools.celery import Popen

    from vsi.tools.file_util import lncp

    tie_points_yxz = []
    control_points_yxz = []

    image = models.Image.objects.get(id=image_id)

    height_reader = GdalReader(image.filename_path, autoload=True)
    transform = height_reader.object.GetGeoTransform()
    height = height_reader.raster()
    del height_reader

    tie_points = image.tiepoint_set.all()

    for tie_point in tie_points:
        lla_xyz = tie_point.control_point.point.coords
        control_points_yxz.append([lla_xyz[x] for x in [1, 0, 2]])
        tie_points_yxz.append([
            transform[4] * (tie_point.point.coords[0] + 0.5) + transform[5] *
            (tie_point.point.coords[1] + 0.5) + transform[3],
            transform[1] * (tie_point.point.coords[0] + 0.5) + transform[2] *
            (tie_point.point.coords[1] + 0.5) + transform[0],
            height[tie_point.point.coords[1], tie_point.point.coords[0]]
        ])

    origin_yxz = np.mean(np.array(control_points_yxz), axis=0)
    tie_points_local = []
    control_points_local = []
    lvcs = vpgl_adaptor.create_lvcs(origin_yxz[0], origin_yxz[1],
                                    origin_yxz[2], 'wgs84')

    for tie_point in tie_points_yxz:
        tie_points_local.append(
            vpgl_adaptor.convert_to_local_coordinates2(lvcs, *tie_point))

    for control_point in control_points_yxz:
        control_points_local.append(
            vpgl_adaptor.convert_to_local_coordinates2(lvcs, *control_point))

    error = np.linalg.norm(
        np.array(tie_points_local) - np.array(control_points_local),
        axis=0) / (len(tie_points_local)**0.5)

    result = {}
    result['error'] = list(error)
    result['horizontal_accuracy'] = 2.4477 * 0.5 * (error[0] + error[1])
    result['vertical_accuracy'] = 1.96 * error[2]

    return result
Ejemplo n.º 9
0
def update_geometry_polygon(request):
  import voxel_globe.meta.models as models
  from django.contrib.gis.geos import Point, Polygon, GEOSGeometry
  import numpy as np
  import brl_init
  import vpgl_adaptor_boxm2_batch as vpgl_adaptor

  image_id = int(request.POST['image_id'])
  points = GEOSGeometry(request.POST['points'])
  sattelgeometryobject_id = int(request.POST['sattelgeometryobject_id'])
  site_id = int(request.POST['site_id'])
  projection_mode = request.POST['projection_mode']

  site = models.SattelSite.objects.get(id=site_id)
  image = models.Image.objects.get(id=image_id)
  camera = image.camera_set.filter(cameraset=site.camera_set).select_subclasses('rpccamera')[0]
  sattelgeometryobject = models.SattelGeometryObject.objects.get(id=sattelgeometryobject_id)

  vpgl_camera = vpgl_adaptor.load_rational_camera_from_txt(camera.rpc_path)
  initial_guess = np.mean(image.attributes['planet_rest_response']['geometry']['coordinates'][0][0:4], axis=0)
  initial_guess = np.hstack((initial_guess, 0)) #elevation guess is 0

  lvcs_points = []

  gps_points = []

  if projection_mode == "z-plane":
    projection_height = float(request.POST['height'])

    for point in points.coords[0]:
      point = vpgl_adaptor.get_rpc_backprojected_ray(vpgl_camera, 
                                                     point[0], point[1], 
                                                     projection_height,
                                                     initial_guess[0], 
                                                     initial_guess[1], 
                                                     initial_guess[2])
      gps_points.append(point)


  origin = np.array(gps_points).mean(axis=0)

  lvcs = vpgl_adaptor.create_lvcs(origin[1], origin[0], origin[2], "wgs84")
  origin = Point(*origin)

  for point in gps_points:
    point = vpgl_adaptor.convert_to_local_coordinates2(lvcs, point[1], point[0], point[2])

    lvcs_points.append(point)

  print sattelgeometryobject.geometry_path

  if sattelgeometryobject.geometry_path and os.path.exists(sattelgeometryobject.geometry_path):
    os.remove(sattelgeometryobject.geometry_path)

  geometry_filepath = write_ply_file(lvcs_points)
  sattelgeometryobject.geometry_path=geometry_filepath
  sattelgeometryobject.origin = origin
  sattelgeometryobject.geometry = Polygon(gps_points+gps_points[0:1])
  sattelgeometryobject.save()
  from django.shortcuts import HttpResponse
  return HttpResponse('{}', content_type="application/json")