Skip to content

Instantly share code, notes, and snippets.

@ChocopieKewpie
Created February 22, 2024 21:31
Show Gist options
  • Save ChocopieKewpie/54a0db2cb7f7b496a8e4fd5e88319d67 to your computer and use it in GitHub Desktop.
Save ChocopieKewpie/54a0db2cb7f7b496a8e4fd5e88319d67 to your computer and use it in GitHub Desktop.
Majority rules raster generation over a vector area
import geopandas as gpd
import rasterio
import numpy as np
from rasterio.transform import from_bounds
# Function to apply majority rule cellular automaton
def majority_rule(array):
# Create a copy of the array to store the updated values
new_array = np.zeros_like(array)
rows, cols = array.shape
# Apply majority rule to each cell
for i in range(1, rows-1):
for j in range(1, cols-1):
# Get the values of the cell and its neighbors
neighbors = array[i-1:i+2, j-1:j+2].flatten()
# Apply majority rule
new_array[i, j] = np.median(neighbors) > 0.5
return new_array
# Open the GeoPackage file using GeoPandas
gpkg_path = 'input.gpkg'
gdf = gpd.read_file(gpkg_path)
# Get the bounding box
minx, miny, maxx, maxy = gdf.total_bounds
# Calculate the number of rows and columns for the raster
cols, rows = 125, 125 # Adjust these values as needed
# Generate a cellular automaton raster
random_array = np.random.randint(2, size=(rows, cols), dtype=np.uint8)
# Apply majority rule cellular automaton
for _ in range(4): # Repeat the majority rule 10 times as an example
random_array = majority_rule(random_array)
# Define the metadata for the output raster
transform = from_bounds(minx, miny, maxx, maxy, cols, rows)
meta = {
'driver': 'GTiff',
'height': rows,
'width': cols,
'count': 1,
'dtype': random_array.dtype,
'crs': gdf.crs,
'transform': transform
}
# Write the output raster
output_raster_path = 'output.tif'
with rasterio.open(output_raster_path, 'w', **meta) as dst:
dst.write(random_array, 1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment