For the problem I am solving I have lat/lon values in DataFrame and need to check if these values coincide with some of the satellite images I have. This part I managed to solve following this post (How to check given a coordinate (lat,long) if is in a raster image file (tif file) and how to extract it with NXN window?).
Following this I need extract a portion from the image, which needs to be 256×256 pixels with the point at the center. In other words the satellite images I have are quite large and my task is to extract 256×256 image patch from this larger image where the point falls at the center of this 256×256 image.
import rasterio
import pyproj
import pandas as pd
# Lets just consider one image for now
dataset = rasterio.open("path to image")
points = pd.read_csv("path to csv containing gps coordinates")
pp = pyproj.Proj(init = "epsg:32650")
# loop through each row of the dataframe
for i,row in points.iterrows():
#Project lat/lon values to x,y
px,py = pp(row.GPS_X,row.GPS_Y)
#Check if point falls/coincide with the image
if (dataset.bounds.left < px < dataset.bounds.right) and (dataset.bounds.bottom < py < dataset.bounds.top):
# Need some sort of inverse transformation function here to convert px,py or GPS_X,GPS_Y values to pixel values
# Lets calls these corresponding values ppx, ppy
from_row, to_row, from_col, to_col = int(ppx - 128), int(ppx + 128), int(ppy -128) , int(ppy + 128)
# get rgb image values
rgb_img = dataset.read([1,2,3]) #shape : (3, 13044, 11137) for reference
# make a slice of 256x256 surrounding the point
rgb_img_slice = rgb_img[:, from_row:to_row, from_col:to_col]
Any clue how I can achieve this ? What I need is some sort of function that can transform the projected X,Y values to pixel values.
Thanks