def get_image_location_value_list(imagepath, x, y, xy_srs): """ get the image value of given location(x,y) of all bands Args: imagepath:the image path which the information query x:x value y:y value xy_srs:the coordinate system of (x,y), the value is :pixel ,prj or lon_lat_wgs84 Returns: a list containing values (string format) of all the bands """ coordinate = '' if xy_srs == 'pixel': coordinate = ' ' elif xy_srs == 'prj': coordinate = ' -geoloc ' elif xy_srs == 'lon_lat_wgs84': coordinate = ' -wgs84 ' else: basic.outputlogMessage('input error: %s is not right' % xy_srs) assert False command_str = 'gdallocationinfo -valonly ' + coordinate \ + ' '+imagepath + ' ' + str(x) +' '+ str(y) result = basic.exec_command_string_output_string(command_str) if result == "": raise ValueError('the command output is empty') return result.split('\n')
def get_image_proj_extent(imagepath): """ get the extent of a image Args: imagepath:image path Returns:(ulx:Upper Left X,uly: Upper Left Y,lrx: Lower Right X,lry: Lower Right Y) """ ulx = False uly = False lrx = False lry = False CommandString = 'gdalinfo -json ' + imagepath imginfo = basic.exec_command_string_output_string(CommandString) if imginfo is False: return False imginfo_obj = json.loads(imginfo) # print imginfo_obj # print type(imginfo_obj) # print imginfo_obj.keys() try: cornerCoordinates = imginfo_obj['cornerCoordinates'] upperLeft_value = cornerCoordinates['upperLeft'] lowerRight_value = cornerCoordinates['lowerRight'] ulx = upperLeft_value[0] uly = upperLeft_value[1] lrx = lowerRight_value[0] lry = lowerRight_value[1] except KeyError: basic.outputlogMessage(str(KeyError)) pass return (ulx, uly, lrx, lry)
def get_image_max_min_value(imagepath): """ get image first band max vlaue and min value Args: imagepath: image path Returns:(max value list, min value list) is successful, (False,False) otherwise """ max_value = [] min_value = [] CommandString = 'gdalinfo -json -stats ' + imagepath imginfo = basic.exec_command_string_output_string(CommandString) if imginfo is False: return False imginfo_obj = json.loads(imginfo) try: bands_info = imginfo_obj['bands'] for band_info in bands_info: max_value.append(band_info['maximum']) min_value.append(band_info['minimum']) return (max_value, min_value) except KeyError: basic.outputlogMessage(str(KeyError)) pass return (False, False)
def get_image_location_value(imagepath, x, y, xy_srs, bandindex): """ get the image value of given location(x,y) in bandindex Args: imagepath:the image path which the information query x:x value y:y value xy_srs:the coordinate system of (x,y), the value is :pixel ,prj or lon_lat_wgs84 bandindex:the bandindex of image want to query Returns:the certain value (float) of given location """ coordinate = '' if xy_srs == 'pixel': coordinate = ' ' elif xy_srs == 'prj': coordinate = ' -geoloc ' elif xy_srs == 'lon_lat_wgs84': coordinate = ' -wgs84 ' else: basic.outputlogMessage('input error: %s is not right' % xy_srs) assert False command_str = 'gdallocationinfo -valonly ' + ' -b ' +str(bandindex) + coordinate \ + ' '+imagepath + ' ' + str(x) +' '+ str(y) result = basic.exec_command_string_output_string(command_str) if result == "": raise ValueError('the command output is empty') try: result = float(result) except ValueError: raise ValueError('cannot convert: %s to float' % result) return result
def get_hisogram_of_oneband_raster(image_path): if io_function.is_file_exist(image_path) is False: return False CommandString = 'gdalinfo -json -hist -mm ' + image_path imginfo = basic.exec_command_string_output_string(CommandString) if imginfo is False: return False imginfo_obj = json.loads(imginfo) try: bands_info = imginfo_obj['bands'] band_info = bands_info[0] # only care band one (suppose only have one band) histogram_info = band_info["histogram"] hist_count = histogram_info["count"] hist_min = histogram_info["min"] hist_max = histogram_info["max"] hist_buckets = histogram_info["buckets"] return (hist_count,hist_min,hist_max,hist_buckets) except KeyError: basic.outputlogMessage(str(KeyError)) pass return (False, False,False,False) pass
def list_ItemTypes(): # Each class of imagery is identified by its "ItemType". # e.g., "PSOrthoTile" - Images taken by PlanetScope satellites in the OrthoTile format. # e.g., "REOrthoTile" - Images taken by RapidEye satellites in the OrthoTile format. command_str = "curl -L -H \"Authorization: api-key $PL_API_KEY\" \'https://api.planet.com/data/v1/item-types\' | jq \'.item_types[].id\'" out_str = basic.exec_command_string_output_string(command_str) print(out_str) return out_str
def get_remote_file_list(pattern): command = 'ssh ' + server + ' ls ' + pattern result = basic.exec_command_string_output_string(command) # result = os.system(command) # print('result',type(result)) if "No such file or directory" in result: basic.outputlogMessage(result) return False else: file_list = result.split('\n') return file_list
def get_asset_type(item_type,item_id): url = 'https://api.planet.com/data/v1/item-types/%s/items/%s/assets'%(item_type,item_id) command_str = "curl -L -H \"Authorization: api-key $PL_API_KEY\" " + url out_str = basic.exec_command_string_output_string(command_str) asset_types = json.loads(out_str) # print(out_str) # test for key in asset_types.keys(): # print(key) print(asset_types[key]) return list(asset_types.keys())
def activation_a_item(item_id, item_type, asset_type): ''' activate a item :param item_id: :param item_type: :param asset_type: :return: ''' session = requests.Session() session.auth = (os.environ['PL_API_KEY'], '') # request an item item = session.get( ("https://api.planet.com/data/v1/item-types/" + "{}/items/{}/assets/").format(item_type, item_id)) # extract the activation url from the item for the desired asset item_activation_url = item.json()[asset_type]["_links"]["activate"] # request activation response = session.post(item_activation_url) #A response of 202 means that the request has been accepted and the activation will begin shortly. # A 204 code indicates that the asset is already active and no further action is needed. # A 401 code means the user does not have permissions to download this file. if response.status_code == 204: # success, return location url = 'https://api.planet.com/data/v1/item-types/%s/items/%s/assets'%(item_type,item_id) command_str = "curl -L -H \"Authorization: api-key $PL_API_KEY\" " + url out_str = basic.exec_command_string_output_string(command_str) tmp_dict = json.loads(out_str) print(tmp_dict[asset_type]['location']) return tmp_dict[asset_type]['location'] print (response.status_code)
def get_image_histogram_oneband(image_path, band_idx=1): """ get historgram of one band Args: image_path: image path band_idx: band index, start from 1 Returns: hist_count (bucket count) ,hist_min, hist_max,hist_buckets """ # -stats: Force computation if no statistics are stored in an image # -mm: Force computation of the actual min/max values for each band in the dataset. CommandString = 'gdalinfo -json -hist -mm -stats ' + image_path imginfo = basic.exec_command_string_output_string(CommandString) if imginfo is False: return False imginfo_obj = json.loads(imginfo) try: bands_info = imginfo_obj['bands'] band_info = bands_info[band_idx - 1] # only care one band one histogram_info = band_info["histogram"] hist_count = histogram_info["count"] hist_min = histogram_info["min"] hist_max = histogram_info["max"] hist_buckets = histogram_info["buckets"] return hist_count, hist_min, hist_max, hist_buckets # hist_array = np.array(hist_buckets) # hist_x = np.linspace(hist_min, hist_max, hist_count) # hist_percent = 100.0 * hist_array / np.sum(hist_array) # # print(np.sum(hist_array)) except KeyError: raise KeyError('parse keys failed')
def draw_image_histogram_oneband(image_path,output): CommandString = 'gdalinfo -json -hist -mm ' + image_path imginfo = basic.exec_command_string_output_string(CommandString) if imginfo is False: return False imginfo_obj = json.loads(imginfo) try: bands_info = imginfo_obj['bands'] band_info = bands_info[0] # only care band one (suppose only have one band) histogram_info = band_info["histogram"] hist_count = histogram_info["count"] hist_min = histogram_info["min"] hist_max = histogram_info["max"] hist_buckets = histogram_info["buckets"] hist_array = np.array(hist_buckets) hist_x = np.linspace(hist_min,hist_max,hist_count) hist_percent = 100.0*hist_array/np.sum(hist_array) print(np.sum(hist_array)) # print(hist_percent) # matplotlib build-in color # b: blue # g: green # r: red # c: cyan # m: magenta # y: yellow # k: black # w: white # plt.figure(figsize=(12, 8)) # color_used_count = 5 # line_color = ['w', 'k'] #['b', 'g', 'r', 'c', 'm', 'y', 'k'] # # linestyle = ['-','--','-.'] # # linestyle = ['*', '+', 's', 'h', 'x', 'd', 'p', 'H', 'D'] # ncount = hist_count # # # plot line # plt.ylim(0,2) plt.plot(list(hist_x), list(hist_percent), 'b-', label="label", linewidth=1.5) print(hist_x) print(hist_percent) # plt.xlabel("Distance (meter)") # plt.ylabel("Average Offset Of One Year (meter)") # plt.title("Offset meters Per Year of Jakobshavn glacier") # plt.ylim(0, 15000) # plt.legend() # plt.show() plt.savefig(output) except KeyError: basic.outputlogMessage(str(KeyError)) pass return (False, False) pass