from PIL import Image def count_pixels_by_hex(image_path): hex_codes = { "#0D0D0D": lambda ind_i: ind_i <= -0.5, "#BFBFBF": lambda ind_i: -0.5 < ind_i <= -0.2, "#DBDBDB": lambda ind_i: -0.2 < ind_i <= -0.1, "#EBEBEB": lambda ind_i: -0.1 < ind_i <= 0, "#FEFACA": lambda ind_i: 0 < ind_i <= 0.025, "#EEE8B6": lambda ind_i: 0.025 < ind_i <= 0.05, "#DEDA9D": lambda ind_i: 0.05 < ind_i <= 0.075, "#CDC084": lambda ind_i: 0.075 < ind_i <= 0.1, "#BFB76C": lambda ind_i: 0.1 < ind_i <= 0.125, "#AFC362": lambda ind_i: 0.125 < ind_i <= 0.15, "#A4CD57": lambda ind_i: 0.15 < ind_i <= 0.175, "#7FB347": lambda ind_i: 0.175 < ind_i <= 0.2, "#6FA140": lambda ind_i: 0.2 < ind_i <= 0.25, "#609636": lambda ind_i: 0.25 < ind_i <= 0.3, "#4F8A2E": lambda ind_i: 0.3 < ind_i <= 0.35, "#417D25": lambda ind_i: 0.35 < ind_i <= 0.4, "#306E1B": lambda ind_i: 0.4 < ind_i <= 0.45, "#226013": lambda ind_i: 0.45 < ind_i <= 0.5, "#0F5369": lambda ind_i: 0.5 < ind_i <= 0.55, "#024500": lambda ind_i: ind_i > 0.55 } with Image.open(image_path) as img: pixels = img.load() width, height = img.size counts = {hex_code: 0 for hex_code in hex_codes.keys()} total_pixels = 0 for y in range(height): for x in range(width): r, g, b,a = pixels[x, y] ind_i = (r + g + b) / 3 / 255 total_pixels+=1 for hex_code, condition in hex_codes.items(): if condition(ind_i): counts[hex_code] += 1 return total_pixels, counts image_path = "Downloads/ndvi_cmap2.png" total_pixels, pixel_counts = count_pixels_by_hex(image_path) print(f"Total number of pixels: {total_pixels}") for hex_code, count in pixel_counts.items(): print(f"Hex Code: {hex_code}, Pixel Count: {count}")