instead of the center of the largest cluster what else could i use? Code: import os from…
- User
instead of the center of the largest cluster what else could i use? Code: import os from PIL import Image import numpy as np from sklearn.cluster import KMeans
def find_black_value(image_path, n_clusters=5): # Open the image and convert to grayscale with Image.open(image_path).convert('L') as img: # Convert image to numpy array img_array = np.array(img)
# Reshape the image to a 2D array of pixels pixels = img_array.reshape((-1, 1)) # Filter pixels to only include those in the range 0 - 55 filtered_pixels = pixels[pixels <= 55].reshape(-1, 1) if len(filtered_pixels) == 0: # Handle case where no pixels are in the specified range return None # Perform k-means clustering kmeans = KMeans(n_clusters=n_clusters, n_init=10) kmeans.fit(filtered_pixels) # Get the cluster centers and labels centers = kmeans.cluster_centers_.flatten() labels = kmeans.labels_ # Get the size of each cluster unique, counts = np.unique(labels, return_counts=True) cluster_sizes = dict(zip(unique, counts)) # Find the largest cluster largest_cluster_index = max(cluster_sizes, key=cluster_sizes.get) # Get the center for the largest cluster black_value = centers[largest_cluster_index] return int(black_value)def process_directory(directory): results = {} for root, dirs, files in os.walk(directory): for file in files: if file.lower().endswith(('.png', '.jpg', '.jpeg', '.tiff', '.bmp', '.gif')): image_path = os.path.join(root, file) try: black_value = find_black_value(image_path) if black_value is not None: results[image_path] = black_value except Exception as e: print(f"Error processing {image_path}: {str(e)}") return results
Use the specified directory
directory_path = r"D:\Bilder\Python\1. Input" black_values = process_directory(directory_path)
Print results
for image_path, black_value in black_values.items(): print(f"Image: {image_path}") print(f"Estimated black value: {black_value}") print()
Save results to a file
output_file = os.path.join(directory_path, 'black_values_results.txt') with open(output_file, 'w') as f: for image_path, black_value in black_values.items(): f.write(f"Image: {image_path}\n") f.write(f"Estimated black value: {black_value}\n") f.write("\n")
print(f"Results have been saved to: {output_file}")
- Assistant
If you want to use an alternative method to find a representative 'black value' rather than using the center of the largest cluster, here are a few options you could consider:
-
Median of the Cluster Centers: Instead of taking the center of the largest cluster, consider the median of all cluster centers. This could provide a more central 'black value' that isn't overly influenced by any single cluster.
black_value = int(np.median(centers)) -
Weighted Mean of the Cluster Centers: Compute a weighted mean of the cluster centers based on the cluster sizes. This method accounts for the relative sizes of the clusters to get a balanced value.
-