Modify the code so that instead of Images with more std dev above mean in 40-55 range than in 0-40 it shows images where the modal value between 0 - 40 is 2 standart derivations above the mean and the the modal value bewteen 40 - 55 is also 2 standart derivations above the mean. Code: import os
from collections import defaultdict
from PIL import Image
import numpy as np
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)
result = analyze_image(image_path)
if result:
subfolder = os.path.relpath(dirpath, root_directory)
results[subfolder].append(result)
if result[4] > result[2]: # if std_dev_40_55 > std_dev_0_40
more_40_55_than_0_40.append(result)
return results, more_40_55_than_0_40
def display_image_info(image):
print(f" Image: {image[0]}")
print(f" Modal Value 0-40: {image[1]}, Std Dev above mean 0-40: {image[2]:.2f}")
# Removed Modal Value 0-55 display
print(f" Modal Value 40-55: {image[3]}, Std Dev above mean 40-55: {image[4]:.2f}")
def display_results(results, more_40_55_than_0_40):
for subfolder, images in results.items():
print(f"Subfolder: {subfolder}")
for image in sorted(images, key=lambda x: x[4], reverse=True): # sort by std_dev_40_55
display_image_info(image)
print()
code
if more_40_55_than_0_40:
print("Images with more std dev above mean in 40-55 range than in 0-40:")
for image in more_40_55_than_0_40:
display_image_info(image)
To modify the code so that it identifies images where the modal value in both the 0-40 and 40-55 ranges is greater than 2 standard deviations above the mean, you'll need to change the conditions in the process_directory function and alter the logic in calculate_modal_value_and_std_dev. Here is the modified code:
python
User
Write a code that calculates the mean modal value of all images in a subfolder. Use the same folder as above
Assistant
To calculate the mean modal value of all images in each subfolder, you can modify the existing code structure to aggregate the modal values for each subfolder and then compute their mean. Here’s how you can do that:
python
import os
from collections import defaultdict
from PIL import Image
import numpy as np
def calculate_modal_value(histogram, start, end):
range_histogram = histogram[start:end+1]
if len(range_histogram) > 0:
modal_value = np.argmax(range_histogram) + start
return round(modal_value)
return 0
def analyze_image(image_path):
try:
with Image.open(image_path) as img:
gray_img = img.convert('L')
img_array = np.array(gray_img)
histogram, _ = np.histogram(img_array, bins=256, range=(0, 256))
modal_value_0_40 = calculate_modal_value(histogram, 0, 40)
modal_value_40_55 = calculate_modal_value(histogram, 40, 55)
return image_path, modal_value_0_40, modal_value_40_55
except Exception as e:
print(f"Error processing {image_path}: {str(e)}")
return None
def process_directory(root_directory):
modal_values_per_subfolder = 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)
result = analyze_image(image_path)
if result:
subfolder = os.path.relpath(dirpath, root_directory)
modal_values_per_subfolder[subfolder].append((result[1], result[2]))
return modal_values_per_subfolder
def calculate_mean_modal_values(modal_values_per_subfolder):
mean_modal_values = {}
for subfolder, modal_values in modal_values_per_subfolder.items():
if modal_values:
mean_modal_value_0_40 = np.mean([mv[0] for mv in modal_values])
mean_modal_value_40_55 = np.mean([mv[1] for mv in modal_values])
mean_modal_values[subfolder] = (mean_modal_value_0_40, mean_modal_value_40_55)
return mean_modal_values
def display_mean_modal_values(mean_modal_values):
for subfolder, means in mean_modal_values.items():
print(f"Subfolder: {subfolder}")
print(f" Mean Modal Value 0-40: {means[0]:.2f}")
print(f" Mean Modal Value 40-55: {means[1]:.2f}")
def main():
root_dir = r'D:\Bilder\Python\1. Input'
modal_values_per_subfolder = process_directory(root_dir)
mean_modal_values = calculate_mean_modal_values(modal_values_per_subfolder)
display_mean_modal_values(mean_modal_values)
if __name__ == "__main__":
main()
User
modify so that it calculates the mean modal value between 0 - 55
Assistant
To modify the code to calculate the mean modal value in the range 0-55 for all images in each subfolder, you need to adjust the calculate_modal_value function and ensure that it calculates the modal value over the 0-55 range. Here's how you can do it:
python
import os
from collections import defaultdict
from PIL import Image
import numpy as np
def calculate_modal_value(histogram, start, end):
range_histogram = histogram[start:end+1]
if len(range_histogram) > 0:
modal_value = np.argmax(range_histogram) + start
return round(modal_value)
return 0
def analyze_image(image_path):
try:
with Image.open(image_path) as img:
gray_img = img.convert('L')
img_array = np.array(gray_img)
histogram, _ = np.histogram(img_array, bins=256, range=(0, 256))
# Calculate modal value for the range 0-55
modal_value_0_55 = calculate_modal_value(histogram, 0, 55)
return image_path, modal_value_0_55
except Exception as e:
print(f"Error processing {image_path}: {str(e)}")
return None
def process_directory(root_directory):
modal_values_per_subfolder = 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)
result = analyze_image(image_path)
if result:
subfolder = os.path.relpath(dirpath, root_directory)
modal_values_per_subfolder[subfolder].append(result[1])
return modal_values_per_subfolder
def calculate_mean_modal_values(modal_values_per_subfolder):
mean_modal_values = {}
for subfolder, modal_values in modal_values_per_subfolder.items():
if modal_values:
mean_modal_value_0_55 = np.mean(modal_values)
mean_modal_values[subfolder] = mean_modal_value_0_55
return mean_modal_values
def display_mean_modal_values(mean_modal_values):
for subfolder, mean in mean_modal_values.items():
print(f"Subfolder: {subfolder}")
print(f" Mean Modal Value 0-55: {mean:.2f}")
def main():
root_dir = r'D:\Bilder\Python\1. Input'
modal_values_per_subfolder = process_directory(root_dir)
mean_modal_values = calculate_mean_modal_values(modal_values_per_subfolder)
display_mean_modal_values(mean_modal_values)
if __name__ == "__main__":
main()
User
also list all images (ordered by subfolder) that have a modal value that is 15% different from the other ones in the subfolder
Assistant
To implement functionality that identifies images with a modal value that is 15% different from the average modal value in their respective subfolders, you can follow these steps:
Compute the mean modal value for each subfolder.
Compare each image's modal value against the computed mean and check if the difference exceeds 15%.
Keep track of such images and display them sorted by subfolder.
Here's how you can modify the previous code to achieve this:
python
User
modify the list of all images (ordered by subfolder) that have a modal value that is 15% different from the other ones in the subfolder so that the subfolder is only shown ones like above
Assistant
To modify the code so that the subfolder name is displayed only once, followed by the outliers within that subfolder, you can change the way results are printed. Here's how you can update the display_mean_modal_values_and_outliers function to achieve this:
python
User
instead of 15% use 3 difference of mean
Assistant
To modify the code so that it identifies images with a modal value that differs by more than 3 from the mean modal value in their respective subfolders, you can change the condition in the find_outlier_images function. Here’s the updated code:
python
User
save a copy of the outlier images in this folder: D:\Bilder\Python\2. Output while preserving folder structure
Assistant
To save a copy of the outlier images in a specific output directory while preserving their folder structure, you can follow these steps:
Create a corresponding subdirectory in the output directory for each subfolder containing outliers.
Copy each outlier image to the appropriate subdirectory in the output directory.
Here's how you can modify the code to include this functionality:
python
User
use the following function to determin if the image is grayscale of color. If it is grayscale do a grayscale L convert with pillow. if it is color ignor it (do not do histogramm calculations and so on with it). def is_color_image(
img: np.ndarray,
diff_threshold: int = Config.COLORDIFF_THRESHOLD,
fraction_threshold: float = Config.FRACTION_COLORED_PIXELS_THRESHOLD,
) -> bool:
"""Determine if an image is color based on RGB channel differences."""
# Check if the image has three channels (RGB)
if img.ndim != 3 or img.shape[2] != 3:
return False
code
# Calculate the peak-to-peak (max - min) difference across the RGB channels for each pixel
max_diff = np.ptp(img, axis=2)
# Compute the fraction of pixels where the max difference exceeds the threshold
fraction_colored = np.mean(max_diff > diff_threshold)
# Determine if the image meets or exceeds the required fraction of colored pixels
return fraction_colored >= fraction_threshold
Assistant
To incorporate the is_color_image function into your image processing workflow, you need to check if an image is grayscale or color before proceeding with other operations like histogram calculations. Here's how you can modify the code to include this check:
Use is_color_image to determine the nature of the image.
If the image is grayscale, convert it using Pillow's convert('L') method before performing further operations.
If the image is determined to be color, skip it.
Here's the updated code:
python
User
round all modal values to and integer
Assistant
To ensure that all modal values are rounded to integers, you should check the process of calculating and returning the modal values within the code. Specifically, make sure that when a modal value is computed, it is rounded to an integer before being stored or used in further calculations.
Here's the updated code with rounding applied to the computed modal values:
python
Not yet included in a published release.
import os
from collections import defaultdict
from PIL import Image
import numpy as np
def calculate_modal_value_and_std_dev(histogram, start, end, mean, std_dev):
range_histogram = histogram[start:end+1]
if len(range_histogram) > 0:
modal_value = np.argmax(range_histogram) + start
if std_dev != 0:
std_dev_above_mean = (range_histogram[modal_value - start] - mean) / std_dev
else:
std_dev_above_mean = 0
return round(modal_value), std_dev_above_mean
return 0, 0
def analyze_image(image_path):
try:
with Image.open(image_path) as img:
gray_img = img.convert('L')
img_array = np.array(gray_img)
histogram, _ = np.histogram(img_array, bins=256, range=(0, 256))
# Calculate mean and std dev for this image in the range 0-55
range_histogram = histogram[0:56]
mean = np.mean(range_histogram)
std_dev = np.std(range_histogram)
modal_value_0_40, std_dev_0_40 = calculate_modal_value_and_std_dev(histogram, 0, 40, mean, std_dev)
modal_value_40_55, std_dev_40_55 = calculate_modal_value_and_std_dev(histogram, 40, 55, mean, std_dev)
return image_path, modal_value_0_40, std_dev_0_40, modal_value_40_55, std_dev_40_55
except Exception as e:
print(f"Error processing {image_path}: {str(e)}")
return None
def process_directory(root_directory):
results = defaultdict(list)
two_std_dev_above_mean = []
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)
result = analyze_image(image_path)
if result:
subfolder = os.path.relpath(dirpath, root_directory)
results[subfolder].append(result)
if result[2] > 2 and result[4] > 2: # if both are more than 2 std deviations above the mean
two_std_dev_above_mean.append(result)
return results, two_std_dev_above_mean
def display_image_info(image):
print(f" Image: {image[0]}")
print(f" Modal Value 0-40: {image[1]}, Std Dev above mean 0-40: {image[2]:.2f}")
print(f" Modal Value 40-55: {image[3]}, Std Dev above mean 40-55: {image[4]:.2f}")
def display_results(results, two_std_dev_above_mean):
for subfolder, images in results.items():
print(f"Subfolder: {subfolder}")
for image in sorted(images, key=lambda x: x[4], reverse=True): # sort by std_dev_40_55
display_image_info(image)
print()
if two_std_dev_above_mean:
print("Images with modal values more than 2 std dev above the mean in both 0-40 and 40-55 ranges:")
for image in two_std_dev_above_mean:
display_image_info(image)
def main():
root_dir = r'D:\Bilder\Python\1. Input'
results, two_std_dev_above_mean = process_directory(root_dir)
display_results(results, two_std_dev_above_mean)
if __name__ == "__main__":
main()
Key Changes:
Condition Change: In the process_directory function, updated the condition to check if both std_dev_0_40 and std_dev_40_55 are greater than 2. This identifies images where the modal values for the specified ranges are more than 2 standard deviations above the mean.
Variable Renaming: Changed more_40_55_than_0_40 to two_std_dev_above_mean to reflect the new criteria being tested.
This adaptation scans images in a directory and identifies those that meet the specified conditions regarding the standard deviation and modal values over the two ranges.
Key Components:
Modal Value Calculation: The calculate_modal_value function computes the modal value for specified histogram ranges.
Aggregation by Subfolder: Modal values are stored in modal_values_per_subfolder, grouped by subfolder.
Mean Calculation: The calculate_mean_modal_values function computes mean modal values for each subfolder.
Display: The results are printed for each subfolder with the mean modal values for the 0-40 and 40-55 value ranges.
This implementation computes the mean modal value for each subfolder's images separately for the ranges 0-40 and 40-55 and displays the results.
Key Modifications:
Calculate Modal Value for 0-55: Changed analyze_image to calculate the modal value over the entire 0-55 range.
Data Structure: Simplified the list to append only the 0-55 modal value in modal_values_per_subfolder.
Mean Calculation: The calculate_mean_modal_values function now averages these modal values for each subfolder.
This updated script processes each image in the specified directory, calculates the modal value for the pixel intensity range of 0-55, and then computes the average for each subfolder. Finally, it prints the mean modal value for each subfolder.
import os
from collections import defaultdict
from PIL import Image
import numpy as np
def calculate_modal_value(histogram, start, end):
range_histogram = histogram[start:end+1]
if len(range_histogram) > 0:
modal_value = np.argmax(range_histogram) + start
return round(modal_value)
return 0
def analyze_image(image_path):
try:
with Image.open(image_path) as img:
gray_img = img.convert('L')
img_array = np.array(gray_img)
histogram, _ = np.histogram(img_array, bins=256, range=(0, 256))
# Calculate modal value for the range 0-55
modal_value_0_55 = calculate_modal_value(histogram, 0, 55)
return image_path, modal_value_0_55
except Exception as e:
print(f"Error processing {image_path}: {str(e)}")
return None
def process_directory(root_directory):
modal_values_per_subfolder = 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)
result = analyze_image(image_path)
if result:
subfolder = os.path.relpath(dirpath, root_directory)
modal_values_per_subfolder[subfolder].append(result)
return modal_values_per_subfolder
def calculate_mean_modal_values(modal_values_per_subfolder):
mean_modal_values = {}
for subfolder, modal_values in modal_values_per_subfolder.items():
if modal_values:
modal_value_0_55_list = [mv[1] for mv in modal_values]
mean_modal_value_0_55 = np.mean(modal_value_0_55_list)
mean_modal_values[subfolder] = mean_modal_value_0_55
return mean_modal_values
def find_outlier_images(modal_values_per_subfolder, mean_modal_values):
outlier_images = []
for subfolder, modal_values in modal_values_per_subfolder.items():
mean_modal_value = mean_modal_values[subfolder]
for image_path, modal_value in modal_values:
if abs(modal_value - mean_modal_value) > 0.15 * mean_modal_value:
outlier_images.append((subfolder, image_path, modal_value))
return outlier_images
def display_mean_modal_values_and_outliers(mean_modal_values, outlier_images):
print("Mean Modal Values:")
for subfolder, mean in mean_modal_values.items():
print(f"Subfolder: {subfolder}")
print(f" Mean Modal Value 0-55: {mean:.2f}")
print("\nOutlier Images:")
for subfolder, image_path, modal_value in outlier_images:
print(f"Subfolder: {subfolder}")
print(f" Image: {image_path}, Modal Value 0-55: {modal_value}")
def main():
root_dir = r'D:\Bilder\Python\1. Input'
modal_values_per_subfolder = process_directory(root_dir)
mean_modal_values = calculate_mean_modal_values(modal_values_per_subfolder)
outlier_images = find_outlier_images(modal_values_per_subfolder, mean_modal_values)
display_mean_modal_values_and_outliers(mean_modal_values, outlier_images)
if __name__ == "__main__":
main()
Explanation of Key Changes:
Modal Values Collection: Store the modal values for each image in modal_values_per_subfolder.
Calculate Mean Modal Values: Compute the average modal value for each subfolder.
Identify Outliers: Compare each image's modal value to the mean. If an image's modal value differs from the mean by more than 15%, it is considered an outlier.
Display Results: Print the mean modal values and list images that are outliers, organizing them by subfolder.
This script helps identify images that significantly deviate from the typical modal value within their subfolder, thus allowing quick insight into anomalies or distinct images.
import os
from collections import defaultdict
from PIL import Image
import numpy as np
def calculate_modal_value(histogram, start, end):
range_histogram = histogram[start:end+1]
if len(range_histogram) > 0:
modal_value = np.argmax(range_histogram) + start
return round(modal_value)
return 0
def analyze_image(image_path):
try:
with Image.open(image_path) as img:
gray_img = img.convert('L')
img_array = np.array(gray_img)
histogram, _ = np.histogram(img_array, bins=256, range=(0, 256))
# Calculate modal value for the range 0-55
modal_value_0_55 = calculate_modal_value(histogram, 0, 55)
return image_path, modal_value_0_55
except Exception as e:
print(f"Error processing {image_path}: {str(e)}")
return None
def process_directory(root_directory):
modal_values_per_subfolder = 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)
result = analyze_image(image_path)
if result:
subfolder = os.path.relpath(dirpath, root_directory)
modal_values_per_subfolder[subfolder].append(result)
return modal_values_per_subfolder
def calculate_mean_modal_values(modal_values_per_subfolder):
mean_modal_values = {}
for subfolder, modal_values in modal_values_per_subfolder.items():
if modal_values:
modal_value_0_55_list = [mv[1] for mv in modal_values]
mean_modal_value_0_55 = np.mean(modal_value_0_55_list)
mean_modal_values[subfolder] = mean_modal_value_0_55
return mean_modal_values
def find_outlier_images(modal_values_per_subfolder, mean_modal_values):
outlier_images = defaultdict(list)
for subfolder, modal_values in modal_values_per_subfolder.items():
mean_modal_value = mean_modal_values[subfolder]
for image_path, modal_value in modal_values:
if abs(modal_value - mean_modal_value) > 0.15 * mean_modal_value:
outlier_images[subfolder].append((image_path, modal_value))
return outlier_images
def display_mean_modal_values_and_outliers(mean_modal_values, outlier_images):
print("Mean Modal Values:")
for subfolder, mean in mean_modal_values.items():
print(f"Subfolder: {subfolder}")
print(f" Mean Modal Value 0-55: {mean:.2f}")
print("\nOutlier Images:")
for subfolder, images in outlier_images.items():
if images:
print(f"Subfolder: {subfolder}")
for image_path, modal_value in images:
print(f" Image: {image_path}, Modal Value 0-55: {modal_value}")
def main():
root_dir = r'D:\Bilder\Python\1. Input'
modal_values_per_subfolder = process_directory(root_dir)
mean_modal_values = calculate_mean_modal_values(modal_values_per_subfolder)
outlier_images = find_outlier_images(modal_values_per_subfolder, mean_modal_values)
display_mean_modal_values_and_outliers(mean_modal_values, outlier_images)
if __name__ == "__main__":
main()
Key Changes:
Dictionary for Outliers: Use a defaultdict of lists to group outliers by subfolder.
Simplified Display Loop: The display_mean_modal_values_and_outliers function prints the subfolder name once and then lists all outlier images within that subfolder, ensuring that the subfolder header is only displayed once.
This approach ensures that the output is organized and easy to read, with each subfolder's outliers presented together.
import os
from collections import defaultdict
from PIL import Image
import numpy as np
def calculate_modal_value(histogram, start, end):
range_histogram = histogram[start:end+1]
if len(range_histogram) > 0:
modal_value = np.argmax(range_histogram) + start
return round(modal_value)
return 0
def analyze_image(image_path):
try:
with Image.open(image_path) as img:
gray_img = img.convert('L')
img_array = np.array(gray_img)
histogram, _ = np.histogram(img_array, bins=256, range=(0, 256))
# Calculate modal value for the range 0-55
modal_value_0_55 = calculate_modal_value(histogram, 0, 55)
return image_path, modal_value_0_55
except Exception as e:
print(f"Error processing {image_path}: {str(e)}")
return None
def process_directory(root_directory):
modal_values_per_subfolder = 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)
result = analyze_image(image_path)
if result:
subfolder = os.path.relpath(dirpath, root_directory)
modal_values_per_subfolder[subfolder].append(result)
return modal_values_per_subfolder
def calculate_mean_modal_values(modal_values_per_subfolder):
mean_modal_values = {}
for subfolder, modal_values in modal_values_per_subfolder.items():
if modal_values:
modal_value_0_55_list = [mv[1] for mv in modal_values]
mean_modal_value_0_55 = np.mean(modal_value_0_55_list)
mean_modal_values[subfolder] = mean_modal_value_0_55
return mean_modal_values
def find_outlier_images(modal_values_per_subfolder, mean_modal_values):
outlier_images = defaultdict(list)
for subfolder, modal_values in modal_values_per_subfolder.items():
mean_modal_value = mean_modal_values[subfolder]
for image_path, modal_value in modal_values:
if abs(modal_value - mean_modal_value) > 3: # Change this line
outlier_images[subfolder].append((image_path, modal_value))
return outlier_images
def display_mean_modal_values_and_outliers(mean_modal_values, outlier_images):
print("Mean Modal Values:")
for subfolder, mean in mean_modal_values.items():
print(f"Subfolder: {subfolder}")
print(f" Mean Modal Value 0-55: {mean:.2f}")
print("\nOutlier Images:")
for subfolder, images in outlier_images.items():
if images:
print(f"Subfolder: {subfolder}")
for image_path, modal_value in images:
print(f" Image: {image_path}, Modal Value 0-55: {modal_value}")
def main():
root_dir = r'D:\Bilder\Python\1. Input'
modal_values_per_subfolder = process_directory(root_dir)
mean_modal_values = calculate_mean_modal_values(modal_values_per_subfolder)
outlier_images = find_outlier_images(modal_values_per_subfolder, mean_modal_values)
display_mean_modal_values_and_outliers(mean_modal_values, outlier_images)
if __name__ == "__main__":
main()
Key Change:
Outlier Condition: Updated the condition in find_outlier_images to detect outliers based on a difference of more than 3 from the mean (if abs(modal_value - mean_modal_value) > 3).
This code now identifies images whose modal value deviates by more than 3 units from the mean modal value in their respective subfolders. The output lists the mean modal values for each subfolder and then displays any outlier images, grouped by subfolder.
import os
import shutil
from collections import defaultdict
from PIL import Image
import numpy as np
def calculate_modal_value(histogram, start, end):
range_histogram = histogram[start:end+1]
if len(range_histogram) > 0:
modal_value = np.argmax(range_histogram) + start
return round(modal_value)
return 0
def analyze_image(image_path):
try:
with Image.open(image_path) as img:
gray_img = img.convert('L')
img_array = np.array(gray_img)
histogram, _ = np.histogram(img_array, bins=256, range=(0, 256))
# Calculate modal value for the range 0-55
modal_value_0_55 = calculate_modal_value(histogram, 0, 55)
return image_path, modal_value_0_55
except Exception as e:
print(f"Error processing {image_path}: {str(e)}")
return None
def process_directory(root_directory):
modal_values_per_subfolder = 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)
result = analyze_image(image_path)
if result:
subfolder = os.path.relpath(dirpath, root_directory)
modal_values_per_subfolder[subfolder].append(result)
return modal_values_per_subfolder
def calculate_mean_modal_values(modal_values_per_subfolder):
mean_modal_values = {}
for subfolder, modal_values in modal_values_per_subfolder.items():
if modal_values:
modal_value_0_55_list = [mv[1] for mv in modal_values]
mean_modal_value_0_55 = np.mean(modal_value_0_55_list)
mean_modal_values[subfolder] = mean_modal_value_0_55
return mean_modal_values
def find_outlier_images(modal_values_per_subfolder, mean_modal_values):
outlier_images = defaultdict(list)
for subfolder, modal_values in modal_values_per_subfolder.items():
mean_modal_value = mean_modal_values[subfolder]
for image_path, modal_value in modal_values:
if abs(modal_value - mean_modal_value) > 3: # 3 units difference
outlier_images[subfolder].append((image_path, modal_value))
return outlier_images
def copy_outlier_images(outlier_images, input_root, output_root):
for subfolder, images in outlier_images.items():
if images:
# Create the corresponding output subfolder
output_subfolder = os.path.join(output_root, subfolder)
os.makedirs(output_subfolder, exist_ok=True)
for image_path, _ in images:
# Determine the destination path
rel_path = os.path.relpath(image_path, input_root)
dest_path = os.path.join(output_root, rel_path)
# Copy the image
shutil.copy(image_path, dest_path)
def display_mean_modal_values_and_outliers(mean_modal_values, outlier_images):
print("Mean Modal Values:")
for subfolder, mean in mean_modal_values.items():
print(f"Subfolder: {subfolder}")
print(f" Mean Modal Value 0-55: {mean:.2f}")
print("\nOutlier Images:")
for subfolder, images in outlier_images.items():
if images:
print(f"Subfolder: {subfolder}")
for image_path, modal_value in images:
print(f" Image: {image_path}, Modal Value 0-55: {modal_value}")
def main():
input_root_dir = r'D:\Bilder\Python\1. Input'
output_root_dir = r'D:\Bilder\Python\2. Output'
modal_values_per_subfolder = process_directory(input_root_dir)
mean_modal_values = calculate_mean_modal_values(modal_values_per_subfolder)
outlier_images = find_outlier_images(modal_values_per_subfolder, mean_modal_values)
# Display results
display_mean_modal_values_and_outliers(mean_modal_values, outlier_images)
# Copy outlier images
copy_outlier_images(outlier_images, input_root_dir, output_root_dir)
if __name__ == "__main__":
main()
Key Additions:
Copy Functionality: A new function copy_outlier_images is added. It creates subdirectories in the output path as necessary and copies outlier images.
Preserve Directory Structure: By using os.path.relpath, the script preserves the directory structure of the input folder within the output folder.
This updated code will identify outlier images based on the specified deviation criteria and save copies of those images into the specified output directory, maintaining their original folder structure.
import os
import shutil
from collections import defaultdict
from PIL import Image
import numpy as np
# Mocking the configuration values initially
class Config:
COLORDIFF_THRESHOLD = 10
FRACTION_COLORED_PIXELS_THRESHOLD = 0.05
def is_color_image(
img: np.ndarray,
diff_threshold: int = Config.COLORDIFF_THRESHOLD,
fraction_threshold: float = Config.FRACTION_COLORED_PIXELS_THRESHOLD,
) -> bool:
"""Determine if an image is color based on RGB channel differences."""
# Check if the image has three channels (RGB)
if img.ndim != 3 or img.shape[2] != 3:
return False
# Calculate the peak-to-peak (max - min) difference across the RGB channels for each pixel
max_diff = np.ptp(img, axis=2)
# Compute the fraction of pixels where the max difference exceeds the threshold
fraction_colored = np.mean(max_diff > diff_threshold)
# Determine if the image meets or exceeds the required fraction of colored pixels
return fraction_colored >= fraction_threshold
def calculate_modal_value(histogram, start, end):
range_histogram = histogram[start:end+1]
if len(range_histogram) > 0:
modal_value = np.argmax(range_histogram) + start
return round(modal_value)
return 0
def analyze_image(image_path):
try:
with Image.open(image_path) as img:
img_array = np.array(img)
# Check if the image is grayscale or color
if is_color_image(img_array):
# If the image is color, skip processing
print(f"Skipped color image: {image_path}")
return None
# Convert image to grayscale
gray_img = img.convert('L')
img_array_gray = np.array(gray_img)
histogram, _ = np.histogram(img_array_gray, bins=256, range=(0, 256))
# Calculate modal value for the range 0-55
modal_value_0_55 = calculate_modal_value(histogram, 0, 55)
return image_path, modal_value_0_55
except Exception as e:
print(f"Error processing {image_path}: {str(e)}")
return None
def process_directory(root_directory):
modal_values_per_subfolder = 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)
result = analyze_image(image_path)
if result:
subfolder = os.path.relpath(dirpath, root_directory)
modal_values_per_subfolder[subfolder].append(result)
return modal_values_per_subfolder
def calculate_mean_modal_values(modal_values_per_subfolder):
mean_modal_values = {}
for subfolder, modal_values in modal_values_per_subfolder.items():
if modal_values:
modal_value_0_55_list = [mv[1] for mv in modal_values]
mean_modal_value_0_55 = np.mean(modal_value_0_55_list)
mean_modal_values[subfolder] = mean_modal_value_0_55
return mean_modal_values
def find_outlier_images(modal_values_per_subfolder, mean_modal_values):
outlier_images = defaultdict(list)
for subfolder, modal_values in modal_values_per_subfolder.items():
mean_modal_value = mean_modal_values[subfolder]
for image_path, modal_value in modal_values:
if abs(modal_value - mean_modal_value) > 3:
outlier_images[subfolder].append((image_path, modal_value))
return outlier_images
def copy_outlier_images(outlier_images, input_root, output_root):
for subfolder, images in outlier_images.items():
if images:
output_subfolder = os.path.join(output_root, subfolder)
os.makedirs(output_subfolder, exist_ok=True)
for image_path, _ in images:
rel_path = os.path.relpath(image_path, input_root)
dest_path = os.path.join(output_root, rel_path)
shutil.copy(image_path, dest_path)
def display_mean_modal_values_and_outliers(mean_modal_values, outlier_images):
print("Mean Modal Values:")
for subfolder, mean in mean_modal_values.items():
print(f"Subfolder: {subfolder}")
print(f" Mean Modal Value 0-55: {mean:.2f}")
print("\nOutlier Images:")
for subfolder, images in outlier_images.items():
if images:
print(f"Subfolder: {subfolder}")
for image_path, modal_value in images:
print(f" Image: {image_path}, Modal Value 0-55: {modal_value}")
def main():
input_root_dir = r'D:\Bilder\Python\1. Input'
output_root_dir = r'D:\Bilder\Python\2. Output'
modal_values_per_subfolder = process_directory(input_root_dir)
mean_modal_values = calculate_mean_modal_values(modal_values_per_subfolder)
outlier_images = find_outlier_images(modal_values_per_subfolder, mean_modal_values)
# Display results
display_mean_modal_values_and_outliers(mean_modal_values, outlier_images)
# Copy outlier images
copy_outlier_images(outlier_images, input_root_dir, output_root_dir)
if __name__ == "__main__":
main()
Key Changes:
Image Nature Check: Added the is_color_image function to determine the nature of the image.
Conditional Processing: Within analyze_image, it checks if the image is colored. If it's colored, it skips further processing; otherwise, it converts the image to grayscale.
This ensures that only grayscale images are processed for histogram calculations and copying, while color images are identified and skipped from these operations.
import os
import shutil
from collections import defaultdict
from PIL import Image
import numpy as np
# Mocking the configuration values initially
class Config:
COLORDIFF_THRESHOLD = 10
FRACTION_COLORED_PIXELS_THRESHOLD = 0.05
def is_color_image(
img: np.ndarray,
diff_threshold: int = Config.COLORDIFF_THRESHOLD,
fraction_threshold: float = Config.FRACTION_COLORED_PIXELS_THRESHOLD,
) -> bool:
"""Determine if an image is color based on RGB channel differences."""
# Check if the image has three channels (RGB)
if img.ndim != 3 or img.shape[2] != 3:
return False
# Calculate the peak-to-peak (max - min) difference across the RGB channels for each pixel
max_diff = np.ptp(img, axis=2)
# Compute the fraction of pixels where the max difference exceeds the threshold
fraction_colored = np.mean(max_diff > diff_threshold)
# Determine if the image meets or exceeds the required fraction of colored pixels
return fraction_colored >= fraction_threshold
def calculate_modal_value(histogram, start, end):
range_histogram = histogram[start:end+1]
if len(range_histogram) > 0:
modal_value = np.argmax(range_histogram) + start
return int(round(modal_value)) # Ensure the modal value is rounded to an integer
return 0
def analyze_image(image_path):
try:
with Image.open(image_path) as img:
img_array = np.array(img)
# Check if the image is grayscale or color
if is_color_image(img_array):
# If the image is color, skip processing
print(f"Skipped color image: {image_path}")
return None
# Convert image to grayscale
gray_img = img.convert('L')
img_array_gray = np.array(gray_img)
histogram, _ = np.histogram(img_array_gray, bins=256, range=(0, 256))
# Calculate modal value for the range 0-55
modal_value_0_55 = calculate_modal_value(histogram, 0, 55)
return image_path, modal_value_0_55
except Exception as e:
print(f"Error processing {image_path}: {str(e)}")
return None
def process_directory(root_directory):
modal_values_per_subfolder = 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)
result = analyze_image(image_path)
if result:
subfolder = os.path.relpath(dirpath, root_directory)
modal_values_per_subfolder[subfolder].append(result)
return modal_values_per_subfolder
def calculate_mean_modal_values(modal_values_per_subfolder):
mean_modal_values = {}
for subfolder, modal_values in modal_values_per_subfolder.items():
if modal_values:
modal_value_0_55_list = [mv[1] for mv in modal_values]
mean_modal_value_0_55 = np.mean(modal_value_0_55_list)
mean_modal_values[subfolder] = round(mean_modal_value_0_55) # Ensure rounding to integer
return mean_modal_values
def find_outlier_images(modal_values_per_subfolder, mean_modal_values):
outlier_images = defaultdict(list)
for subfolder, modal_values in modal_values_per_subfolder.items():
mean_modal_value = mean_modal_values[subfolder]
for image_path, modal_value in modal_values:
if abs(modal_value - mean_modal_value) > 3:
outlier_images[subfolder].append((image_path, modal_value))
return outlier_images
def copy_outlier_images(outlier_images, input_root, output_root):
for subfolder, images in outlier_images.items():
if images:
output_subfolder = os.path.join(output_root, subfolder)
os.makedirs(output_subfolder, exist_ok=True)
for image_path, _ in images:
rel_path = os.path.relpath(image_path, input_root)
dest_path = os.path.join(output_root, rel_path)
shutil.copy(image_path, dest_path)
def display_mean_modal_values_and_outliers(mean_modal_values, outlier_images):
print("Mean Modal Values:")
for subfolder, mean in mean_modal_values.items():
print(f"Subfolder: {subfolder}")
print(f" Mean Modal Value 0-55: {mean}")
print("\nOutlier Images:")
for subfolder, images in outlier_images.items():
if images:
print(f"Subfolder: {subfolder}")
for image_path, modal_value in images:
print(f" Image: {image_path}, Modal Value 0-55: {modal_value}")
def main():
input_root_dir = r'D:\Bilder\Python\1. Input'
output_root_dir = r'D:\Bilder\Python\2. Output'
modal_values_per_subfolder = process_directory(input_root_dir)
mean_modal_values = calculate_mean_modal_values(modal_values_per_subfolder)
outlier_images = find_outlier_images(modal_values_per_subfolder, mean_modal_values)
# Display results
display_mean_modal_values_and_outliers(mean_modal_values, outlier_images)
# Copy outlier images
copy_outlier_images(outlier_images, input_root_dir, output_root_dir)
if __name__ == "__main__":
main()
Key Modifications:
Rounding: The calculate_modal_value function ensures the modal value is an integer using int(round(modal_value)).
Mean Rounding: When calculating the mean modal value for each subfolder, uses round() to ensure the mean remains an integer.
These simple changes ensure that both the individual modal values and the average per subfolder are rounded to the nearest integers. This helps maintain consistency and interpretability of image processing outputs.