jeffrey1963/Cattle-Elk-R5
0
1from PIL import Image2 3def load_and_crop_image(path="Carson_map.png", crop_box=(15, 15, 1000, 950)):4 img = Image.open(path).convert("RGB")5 cropped_img = img.crop(crop_box)6 return cropped_img7 8 9from sklearn.cluster import KMeans10import numpy as np11 12def cluster_image(cropped_img, n_clusters=6):13 img_array = np.array(cropped_img)14 pixels = img_array.reshape(-1, 3)15 kmeans = KMeans(n_clusters=n_clusters, random_state=42).fit(pixels)16 labels = kmeans.labels_.reshape(img_array.shape[:2])17 return labels18 19 20from collections import Counter21import numpy as np22 23def build_parcel_map(clustered_img, grid_size=20):24 height, width = clustered_img.shape25 n_rows = height // grid_size26 n_cols = width // grid_size27 parcel_map = np.zeros((n_rows, n_cols), dtype=int)28 29 for i in range(n_rows):30 for j in range(n_cols):31 patch = clustered_img[i*grid_size:(i+1)*grid_size, j*grid_size:(j+1)*grid_size].flatten()32 dominant = Counter(patch).most_common(1)[0][0]33 parcel_map[i, j] = dominant34 35 return parcel_map, n_rows, n_cols36 37 38import matplotlib.pyplot as plt39import matplotlib.patches as mpatches40from matplotlib.colors import ListedColormap41 42def plot_parcel_map(parcel_map, cluster_labels, land_colors, title="25×25 Land Parcels by Land Type"):43 cmap = ListedColormap(land_colors)44 plt.figure(figsize=(10, 8))45 plt.imshow(parcel_map, cmap=cmap, origin='upper')46 legend_patches = [mpatches.Patch(color=land_colors[i], label=cluster_labels[i]) for i in cluster_labels]47 plt.legend(handles=legend_patches, bbox_to_anchor=(1.05, 1), loc='upper left', title="Land Type")48 plt.title(title)49 plt.axis('off')50 plt.tight_layout()51 plt.show()52 53def plot_parcel_map_to_file(parcel_map, cluster_labels, land_colors, save_path="clustered_map.png", title="25×25 Land Parcels by Land Type"):54 cmap = ListedColormap(land_colors)55 fig, ax = plt.subplots(figsize=(10, 8))56 cax = ax.imshow(parcel_map, cmap=cmap, origin='upper')57 legend_patches = [mpatches.Patch(color=land_colors[i], label=cluster_labels[i]) for i in cluster_labels]58 ax.legend(handles=legend_patches, bbox_to_anchor=(1.05, 1), loc='upper left', title="Land Type")59 ax.set_title(title)60 ax.axis('off')61 plt.tight_layout()62 plt.savefig(save_path)63 plt.close(fig)64 65 66def get_cluster_labels():67 return {68 0: 'Pasture/Desert',69 1: 'Productive Grass',70 2: 'Pasture/Desert',71 3: 'Riparian Sensitive Zone',72 4: 'Rocky Area',73 5: 'Water'74 }75 76 77def get_land_colors():78 return ['#dfb867', '#a0ca76', '#dfb867', '#5b8558', '#888888', '#3a75a8']79 80 81 82 83 84 