To modify the code to display the second and third most frequent modal values along with their percentages, you need to adjust the histogram analysis part of the code to keep track of the top three intensities. This can be accomplished by sorting the histogram frequencies and extracting the required values.
Here’s how you can implement this:
import os
from collections import defaultdict
from PIL import Image
import numpy as np
def analyze_image(image_path):
with Image.open(image_path) as img:
gray_img = img.convert('L')
img_array = np.array(gray_img)
histogram, bin_edges = np.histogram(img_array, bins=256, range=(0, 256))
focus_histogram = histogram[0:61]
# Find the indices of the three highest values in the histogram
top_indices = np.argsort(focus_histogram)[-3:][::-1]
top_values = [(index, focus_histogram[index]) for index in top_indices]
# Calculate the total number of pixels in the 0-60 range
total_in_range = np.sum(focus_histogram)
# Calculate the percentage participation of the top three values
percentages = [(value, (count / total_in_range) * 100) for value, count in top_values]
return image_path, percentages
def process_directory(root_directory):
results = defaultdict(list)
for dirpath, _, filenames in os.walk(root_directory):
for file in filenames:
if file.lower().endswith(('png', 'jpg', 'jpeg', 'bmp', 'gif')):
image_path = os.path.join(dirpath, file)
path, percentages = analyze_image(image_path)
subfolder = os.path.relpath(dirpath, root_directory)
results[subfolder].append((path, percentages))
# Sort images within each subfolder by percentage of the first modal value descending
for subfolder in results:
results[subfolder].sort(key=lambda x: x[1][0][1], reverse=True)
# Display results
for subfolder, images in results.items():
print(f"Subfolder: {subfolder}")
for image in images:
percentages_str = ", ".join([f"Value: {val}, Percentage: {percent:.2f}%" for val, percent in image[1]])
print(f" Image: {image[0]} - {percentages_str}")
print()
# The directory to start processing
root_dir = r'D:\Bilder\Python\1. Input'
process_directory(root_dir)
Key Changes:
- Finding Top Three Values: Use
np.argsort to sort the indices of the histogram's range from 0 to 60 by frequency. Extract the top three indices corresponding to the most frequent values in this range.
- Calculating Percentages: After finding the top three values, calculate their percentages relative to the total number of pixels in the range.
- Results Output: Modify the results output to include the top three values and their percentages for each image.
This code will process each image, find the top three modal values within the 0-60 range, and display those values along with their pixel representation percentages. The images are grouped and listed by subfolder, sorted by the highest percentage of the main modal value.