After you create the clusters and calculate the average of each one I want to store all hex values in the first line of the txt file as a list. Finally replace all hex values from the rest of the txt file with the corresponding indices from this hex colors list. Modify the code to accommodate these changes and show me the final. Use this python script as base to modify:
from sklearn.cluster import KMeans
import numpy as np
import re
node = hou.pwd()
geo = node.geometry()
filepath = node.parm(‘filepath’).evalAsString()
output = node.parm(‘output’).evalAsString()
clusters = node.parm(‘clusters’).evalAsInt()
def hex_to_rgb(hex_color):
""" Convert hex color to RGB. """
hex_color = hex_color.lstrip(’#’)
return tuple(int(hex_color[i:i+2], 16) for i in (0, 2, 4))
def rgb_to_hex(rgb):
""" Convert RGB to hex color. """
return ’#{:02x}{:02x}{:02x}‘.format(rgb[0], rgb[1], rgb[2])
with open(filepath, ‘r’) as file:
hex_values = file.readlines()
hex_pattern = r”#(?:[0-9a-fA-F]{3}){1,2}”
hex_values_extracted = re.findall(hex_pattern, ”.join(hex_values))
rgb_values = np.array([hex_to_rgb(hex_color) for hex_color in hex_values_extracted])
rgb_values_subset = rgb_values # taking only the first 1000 values for example rgb_values[:1000]
kmeans_subset = KMeans(n_clusters=clusters, random_state=0).fit(rgb_values_subset)
cluster_labels = kmeans_subset.predict(rgb_values)
cluster_centers_rounded_subset = np.rint(kmeans_subset.cluster_centers_).astype(int)
averaged_hex_values_subset = [rgb_to_hex(rgb) for rgb in cluster_centers_rounded_subset]
modified_hex_values = [averaged_hex_values_subset[label] for label in cluster_labels]
split_content = re.split(’(#(?:[0-9a-fA-F]{3}){1,2})’, ”.join(hex_values))
for i in range(1, len(split_content), 2):
split_content[i] = modified_hex_values[(i - 1) // 2]
modified_content = ”.join(split_content)
with open(output, ‘w’) as file:
file.write(modified_content)