The following python script uses a HSV conversion and counting hues to determine if a image is color or grayscale. Modify the code so that it uses scribt two instead for determining if an image is color or not. Only print the parts in the code that need to be changed. Code 1: import ctypes
import logging
import os
import shutil
import subprocess
import threading
import time
import tkinter as tk
from collections import defaultdict
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path
from queue import Queue
from tkinter import filedialog
from tkinter import ttk
from typing import Dict, List, Tuple, Set
from dataclasses import dataclass, field
import numpy as np
from PIL import Image, ImageOps
def log_error(message: str):
"""Log an error message to the shared state queue."""
shared_state.log_message_queue.put(f"- {message}")
def clear_console():
"""Clear the console screen."""
os.system('cls' if os.name == 'nt' else 'clear')
def count_image_files(folder: Path) -> int:
"""Count the number of image files in a folder and its subfolders."""
return sum(1 for path in folder.rglob('*') if path.is_file() and path.suffix.lower() in Config.IMAGE_EXTENSIONS)
Assistant
def is_valid_image(path: Path) -> bool:
"""Check if the given path is a valid image file."""
try:
with Image.open(path):
return True
except (OSError, ValueError) as e:
log_error(f"Error reading image {path}: {e}")
return False
def open_and_convert_image(path: Path) -> Image.Image:
with Image.open(path) as img:
if img.mode == 'P': # Palette mode (indexed)
return img.convert('L') # Convert to true grayscale
elif img.mode in ['L', 'RGB', 'RGBA']:
return img.copy() # Return a copy of the image
else:
return img.convert('RGB') # Convert other modes to RGB
def create_temp_folder():
"""Create a temporary folder for processing."""
temp_dir = Config.OUTPUT_FOLDER / f"temp_{int(time.time())}"
temp_dir.mkdir(parents=True, exist_ok=True)
return temp_dir
def cleanup_temp_folder(temp_folder):
"""Remove the temporary folder and its contents."""
shutil.rmtree(temp_folder, ignore_errors=True)
def check_imagemagick():
"""Check if ImageMagick is available in the system."""
if not shutil.which(str(Config.IMAGEMAGICK)):
raise FileNotFoundError(f"- ImageMagick executable not found at: {Config.IMAGEMAGICK}")
def check_ffmpeg():
"""Check if FFmpeg is available in the system."""
if not shutil.which(str(Config.FFMPEG)):
raise FileNotFoundError(f"- FFmpeg executable not found at: {Config.FFMPEG}")
def update_elapsed_time(start_time, total_files, stop_event):
"""Continuously update the elapsed time until the stop event is set."""
while not stop_event.is_set():
update_status(start_time, shared_state.processed_files_count, total_files)
time.sleep(1)
def start_elapsed_time_thread(start_time, total_files, stop_event):
"""Start a thread to update the elapsed time."""
elapsed_time_thread = threading.Thread(target=update_elapsed_time, args=(start_time, total_files, stop_event))
elapsed_time_thread.start()
return elapsed_time_thread
def run_with_thread_pool(tasks, process_func, *args):
shared_state.processed_files_count = 0
shared_state.total_files_count = len(tasks) # Set total files count
start_time = time.time()
total = len(tasks)
app.update_progress(0)
stop_event = threading.Event()
elapsed_time_thread = start_elapsed_time_thread(start_time, total, stop_event)
try:
with ThreadPoolExecutor() as executor:
futures = [executor.submit(process_func, task, *args) for task in tasks]
for i, future in enumerate(futures):
if shared_state.stop_event.is_set():
for f in futures:
f.cancel()
break
try:
future.result()
except Exception as e:
log_error(f"Error during processing: {e}")
finally:
progress = (i + 1) / total * 100
app.update_progress(progress)
finally:
stop_event.set()
elapsed_time_thread.join()
return total
--- Color Adjustment ---
def is_grayscale_image(hue: np.ndarray) -> bool:
"""Determine if an image is grayscale based on its hue values."""
return np.unique(hue).size <= 20
def process_grayscale_image(img: np.ndarray, path: Path, image_processor: 'ImageProcessor', temp_folder: Path) -> Tuple[Path, int, int]:
"""Process a grayscale image, adjusting its values and saving the result."""
try:
adjusted, modal_black, modal_white = adjust_values(img)
def analyze_images(image_processor: 'ImageProcessor'):
"""Analyze images in the input folder for color properties."""
image_processor.reset_results()
tasks = [path for path in Config.INPUT_FOLDER.rglob('*')
if path.is_file() and path.suffix.lower() in Config.IMAGE_EXTENSIONS]
if not tasks:
log_error(f"No image files found in '{Config.INPUT_FOLDER}'")
return
def process_task(path, start_time, total):
analyze_file(path)
with shared_state.processed_files_lock:
shared_state.processed_files_count += 1
update_status(start_time, shared_state.processed_files_count, total)
run_with_thread_pool(tasks, process_task, time.time(), len(tasks))
def analyze_file(path):
"""Analyze a single image file."""
if is_valid_image(path):
try:
img = np.array(open_and_convert_image(path))
if img.ndim == 2 or (img.ndim == 3 and img.shape[2] == 1):
adjusted, modal_black, modal_white = adjust_values(img)
subfolder = str(path.parent.relative_to(Config.INPUT_FOLDER))
filename = path.name
if modal_black:
image_processor.black_results[subfolder].append((filename, modal_black))
if modal_white != 255:
image_processor.white_results[subfolder].append((filename, modal_white))
else:
hsv = Image.fromarray(img).convert("HSV")
hue = np.array(hsv)[:, :, 0]
subfolder = str(path.parent.relative_to(Config.INPUT_FOLDER))
filename = path.name
if not is_grayscale_image(hue):
image_processor.color_results[subfolder].append(filename)
else:
adjusted, modal_black, modal_white = adjust_values(img)
if modal_black:
image_processor.black_results[subfolder].append((filename, modal_black))
if modal_white != 255:
image_processor.white_results[subfolder].append((filename, modal_white))
except (OSError, ValueError) as e:
log_error(f"Error processing image {path}: {e}")
def find_color_images(image_processor: 'ImageProcessor'):
"""Find and move color images to the output folder."""
image_processor.reset_results()
tasks = [path for path in Config.INPUT_FOLDER.rglob('*')
if path.is_file() and path.suffix.lower() in Config.IMAGE_EXTENSIONS]
if not tasks:
log_error(f"No image files found in '{Config.INPUT_FOLDER}'")
return
run_with_thread_pool(tasks, move_color_image_file, time.time(), len(tasks), image_processor)
def move_color_image_file(path, start_time, total_files, image_processor: 'ImageProcessor'):
"""Move a color image file to the output folder."""
if is_valid_image(path):
try:
img = np.array(open_and_convert_image(path))
if img.ndim == 3 and img.shape[2] == 3:
hsv = Image.fromarray(img).convert("HSV")
hue = np.array(hsv)[:, :, 0]
if not is_grayscale_image(hue):
rel_path = path.relative_to(Config.INPUT_FOLDER)
out_path = Config.OUTPUT_FOLDER / rel_path
out_path.parent.mkdir(parents=True, exist_ok=True)
shutil.move(str(path), str(out_path))
subfolder = str(path.parent.relative_to(Config.INPUT_FOLDER))
filename = path.name
image_processor.color_results[subfolder].append(filename)
except (OSError, ValueError) as e:
log_error(f"Error processing image {path}: {e}")
with shared_state.processed_files_lock:
shared_state.processed_files_count += 1
update_status(start_time, shared_state.processed_files_count, total_files)
--- Corrupted Files ---
def check_file_for_corruption(file_path: Path, error_queue):
"""Check a file for corruption using FFmpeg."""
try:
file_extension = file_path.suffix.lower()
if file_extension in Config.VIDEO_EXTENSIONS | Config.AUDIO_EXTENSIONS | Config.IMAGE_EXTENSIONS:
base_command = [str(Config.FFMPEG), '-v', 'error', '-i', str(file_path)]
if file_extension in Config.VIDEO_EXTENSIONS:
command = base_command + ['-map', '0:a:0', '-f', 'null', '-']
else:
command = base_command + ['-f', 'null', '-']
process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
output, error = process.communicate()
combined_output = output.decode('utf-8', errors='ignore') + error.decode('utf-8', errors='ignore')
error_messages = [line.strip() for line in combined_output.split('\n') if 'error' in line.lower()]
if error_messages:
error_queue.put((file_path.resolve(), error_messages))
except Exception as e:
error_queue.put((file_path.resolve(), [f"Error processing file {file_path}: {str(e)}"]))
def check_for_corrupted_files():
"""Check for corrupted files in the input folder."""
image_processor.reset_results()
try:
check_ffmpeg()
except FileNotFoundError as e:
log_error(str(e))
return
tasks = [file_path for file_path in Config.INPUT_FOLDER.rglob('*')
if file_path.is_file() and file_path.suffix.lower() in
Config.VIDEO_EXTENSIONS | Config.AUDIO_EXTENSIONS | Config.IMAGE_EXTENSIONS]
if not tasks:
log_error(f"No valid media files found in '{Config.INPUT_FOLDER}'")
return
error_queue = Queue()
def process_task(file_path, error_queue, start_time, total_files):
check_file_for_corruption(file_path, error_queue)
with shared_state.processed_files_lock:
shared_state.processed_files_count += 1
update_status(start_time, shared_state.processed_files_count, total_files)
total_files = run_with_thread_pool(tasks, process_task, error_queue, time.time(), len(tasks))
log_errors(error_queue)
--- Images ---
def convert_png_to_jpg(input_path: Path, output_path: Path):
"""Convert a PNG image to JPG format."""
try:
with Image.open(input_path) as img:
jpg_path = output_path.with_suffix('.jpg')
img.save(jpg_path, 'JPEG', quality=80, subsampling=0)
os.remove(input_path)
except Exception as e:
log_error(f"Error converting {input_path} to JPG: {e}")
def resize_image(input_path: Path, output_path: Path):
"""Resize an image using ImageMagick."""
output_path = output_path.with_suffix('.png')
def resize_images(input_folder: Path, output_folder: Path, image_processor: 'ImageProcessor'):
"""Resize images in the input folder and save them to the output folder."""
try:
check_imagemagick()
except FileNotFoundError as e:
log_error(str(e))
return
tasks = [input_path for input_path in input_folder.rglob('*')
if input_path.is_file() and input_path.suffix.lower() in Config.IMAGE_EXTENSIONS]
if not tasks:
log_error(f"No image files found in '{input_folder}'")
return
temp_folder = create_temp_folder()
try:
run_with_thread_pool(tasks, process_file, time.time(), len(tasks), image_processor, temp_folder, True)
finally:
try:
cleanup_temp_folder(temp_folder)
except Exception as e:
log_error(f"Error removing temporary folder {temp_folder}: {e}")
def process_file(path: Path, start_time, total_files, image_processor: 'ImageProcessor', temp_folder: Path, resize=False, auto_correct_and_resize=False) -> None:
"""Process a single image file."""
if shared_state.stop_event.is_set():
return
def process_folder(folder: Path, image_processor: 'ImageProcessor', auto_correct_and_resize=False) -> None:
"""Process all images in a folder."""
image_processor.reset_results()
if auto_correct_and_resize:
try:
check_imagemagick()
except FileNotFoundError as e:
log_error(str(e))
return
tasks = [path for path in folder.rglob('*')
if path.is_file() and path.suffix.lower() in Config.IMAGE_EXTENSIONS]
if not tasks:
log_error(f"No image files found in '{folder}'")
return
temp_folder = create_temp_folder()
try:
run_with_thread_pool(tasks, process_file, time.time(), len(tasks), image_processor, temp_folder, False, auto_correct_and_resize)
finally:
try:
cleanup_temp_folder(temp_folder)
except Exception as e:
log_error(f"Error removing temporary folder {temp_folder}: {e}")
--- Logging ---
def log_errors(error_queue):
"""Log errors from the error queue."""
error_dict = defaultdict(list)
while not error_queue.empty():
file_path, error_messages = error_queue.get()
error_dict[file_path].extend(error_messages)
if error_dict:
shared_state.log_message_queue.put("UPDATE_LOG")
for file_path in sorted(error_dict.keys()):
shared_state.log_message_queue.put(f"{file_path.resolve()}")
shared_state.log_message_queue.put("")
for error_message in sorted(error_dict[file_path]):
log_error(error_message)
shared_state.log_message_queue.put("")
def log_and_execute(choice: str, label: str, function: callable, *args):
"""Log the execution of a function and run it in a separate thread."""
def run_in_thread():
start_time = time.time()
separator = '-' * Config.SEPARATOR_LENGTH
shared_state.log_message_queue.put(f"{separator}\n{label}\n{separator}\n")
try:
total_files = function(*args) # Assuming the function returns the total file count
except FileNotFoundError as e:
log_error(str(e))
total_files = 0
except (OSError, ValueError) as e:
log_error(f"An error occurred during '{label}': {e}")
total_files = 0
end_time = time.time()
execution_time = end_time - start_time
shared_state.log_message_queue.put("")
image_processor.write_results_to_files(Config.OUTPUT_FOLDER, choice)
app.after(0, app.update_final_status, execution_time)
app.after(0, app.update_text_area)
thread = threading.Thread(target=run_in_thread)
thread.start()
class ImageProcessor:
"""Class to handle image processing results."""
def init(self):
self.white_results = defaultdict(list)
self.black_results = defaultdict(list)
self.color_results = defaultdict(list)
def write_results_to_files(self, output_folder: Path, choice: str):
"""Write processing results to files."""
results_map = {
'2': ("2. Analyze Images", "Modal Value Black", "Modal Value White"),
'3': ("3. Find Color Images", "Filename"),
'5': ("5. Automatic Color Correction", "Modal Value Black", "Modal Value White"),
'6': ("6. Automatic Color Correction + Resize", "Modal Value Black", "Modal Value White")
}
headers = results_map.get(choice)
if headers:
if choice == '3':
self._write_results("Color", self.color_results, headers[0], headers[1])
else:
self._write_results("Black", self.black_results, headers[0], headers[1])
self._write_results("White", self.white_results, headers[0], headers[2])
self._write_results("Color", self.color_results, headers[0], "Filename")
def _write_results(self, file_path: str, results: Dict[str, List[Tuple[str, int]]], header: str,
value_name: str):
"""Write results to a specific file."""
separator = '-' * Config.SEPARATOR_LENGTH
content = f"{separator}\n{header}\n{separator}\n"
if results:
for subfolder, subfolder_results in sorted(results.items()):
full_subfolder_path = Config.INPUT_FOLDER / subfolder
content += f"\n{full_subfolder_path}\n\n"
if value_name == "Filename":
subfolder_results.sort()
content += '\n'.join(f" - {filename}" for filename in subfolder_results)
else:
subfolder_results.sort(key=lambda x: x[1], reverse=True)
content += '\n'.join(
f" - {filename}, {value_name}: {value}" for filename, value in subfolder_results)
content += "\n"
shared_state.tab_messages[file_path].append(content)
def reset_results(self):
"""Reset all results."""
self.white_results = defaultdict(list)
self.black_results = defaultdict(list)
self.color_results = defaultdict(list)
diff_threshold = 5 # Threshold for color difference between channels
fraction_colored_pixels_threshold = 0.05 # Threshold to consider an image as color
Create the output folder if it doesn't exist
if not os.path.exists(output_folder):
os.makedirs(output_folder)
Walk through all subdirectories and files in the input_folder
for root, dirs, files in os.walk(input_folder):
for filename in files:
# Check if the file is an image
if filename.lower().endswith(('.png', '.jpg', '.jpeg', '.bmp', '.gif')):
# Full path of the image file
image_path = os.path.join(root, filename)
try:
# Open the image and convert it to RGB
image = Image.open(image_path).convert('RGB')
except Exception as e:
print(f"Error opening image {image_path}: {e}")
continue # Skip files that cannot be opened as images
# Convert the image to a NumPy array
image_np = np.array(image)
total_pixels = image_np.shape[0] * image_np.shape[1]
# Separate the RGB channels
R = image_np[:, :, 0].astype(np.int16)
G = image_np[:, :, 1].astype(np.int16)
B = image_np[:, :, 2].astype(np.int16)
# Compute the absolute differences between each pair of RGB channels
diff_RG = np.abs(R - G)
diff_RB = np.abs(R - B)
diff_GB = np.abs(G - B)
# Find the maximum difference among the three pairs for each pixel
max_diff = np.maximum(np.maximum(diff_RG, diff_RB), diff_GB)
# Count the number of pixels where the maximum difference exceeds the threshold
num_colored_pixels = np.sum(max_diff > diff_threshold)
fraction_colored_pixels = num_colored_pixels / total_pixels
# Check if the image is a color image
if fraction_colored_pixels >= fraction_colored_pixels_threshold:
# It's a color image - move it to the output folder, maintaining subdirectory structure
# Get the relative path of the image file with respect to the input folder
relative_path = os.path.relpath(image_path, input_folder)
# Compute the destination path
destination_path = os.path.join(output_folder, relative_path)
# Ensure the destination directory exists
destination_dir = os.path.dirname(destination_path)
if not os.path.exists(destination_dir):
os.makedirs(destination_dir)
# Move the image file
shutil.move(image_path, destination_path)
print(f"Moved color image: {relative_path}")
else:
# Image is not a color image, do nothing
print(f"Skipped non-color image: {os.path.relpath(image_path, input_folder)}")
To modify Code 1 to use the color determination method from Code 2 instead of the HSV-based approach, you'll need to update the following parts of Code 1:
Replace the is_grayscale_image Function:
Remove the existing is_grayscale_image function that relies on hue values and replace it with a new function that uses RGB channel differences to determine if an image is color or grayscale.
Update the process_color_image Function:
Modify the process_color_image function to utilize the new RGB-based color detection method.
Adjust the analyze_file Function (if necessary):
Ensure that the analyze_file function correctly integrates with the new color determination logic.
Below are the specific code snippets that need to be changed:
1. Replace the is_grayscale_image Function
Remove the existing HSV-based function:
def is_grayscale_image(hue: np.ndarray) -> bool:
"""Determine if an image is grayscale based on its hue values."""
return np.unique(hue).size <= 20
Add the new RGB-based color detection function:
def is_color_image(img: np.ndarray, diff_threshold: int = 5, fraction_threshold: float = 0.05) -> bool:
"""
Determine if an image is color based on RGB channel differences.
Args:
img (np.ndarray): The image array in RGB format.
diff_threshold (int): Threshold for color difference between channels.
fraction_threshold (float): Fraction of pixels that must exceed the threshold to be considered color.
Returns:
bool: True if the image is color, False if grayscale.
"""
# Ensure the image has three channels
if img.ndim != 3 or img.shape[2] != 3:
return False
# Convert channels to int16 to prevent overflow/underflow
R = img[:, :, 0].astype(np.int16)
G = img[:, :, 1].astype(np.int16)
B = img[:, :, 2].astype(np.int16)
# Compute absolute differences between channels
diff_RG = np.abs(R - G)
diff_RB = np.abs(R - B)
diff_GB = np.abs(G - B)
# Find the maximum difference per pixel
max_diff = np.maximum(np.maximum(diff_RG, diff_RB), diff_GB)
# Count pixels where max difference exceeds the threshold
num_colored_pixels = np.sum(max_diff > diff_threshold)
total_pixels = img.shape[0] * img.shape[1]
fraction_colored_pixels = num_colored_pixels / total_pixels
# Determine if the fraction exceeds the threshold
return fraction_colored_pixels >= fraction_threshold
Updated process_color_image using RGB differences:
def process_color_image(img: np.ndarray, path: Path, image_processor: 'ImageProcessor', temp_folder: Path,
diff_threshold: int = 5, fraction_threshold: float = 0.05) -> Tuple[Path, bool]:
"""
Process a color image, determining if it's color or grayscale based on RGB differences.
Args:
img (np.ndarray): The image array in RGB format.
path (Path): Path to the image file.
image_processor (ImageProcessor): The image processor instance.
temp_folder (Path): Temporary folder for processing.
diff_threshold (int): Threshold for color difference between channels.
fraction_threshold (float): Fraction of pixels that must exceed the threshold to be considered color.
Returns:
Tuple[Path, bool]: The output path and a boolean indicating if modal black was adjusted.
"""
try:
if is_color_image(img, diff_threshold, fraction_threshold):
# It's a color image - save it as is
rel_path = path.relative_to(Config.INPUT_FOLDER)
out_path = temp_folder / rel_path.with_suffix('.png')
out_path.parent.mkdir(parents=True, exist_ok=True)
Image.fromarray(img).save(out_path, format='PNG', compress_level=5)
subfolder = str(path.parent.relative_to(Config.INPUT_FOLDER))
filename = path.name
image_processor.color_results[subfolder].append(filename)
return out_path, False
else:
# It's a grayscale image - process accordingly
gray = ImageOps.grayscale(Image.fromarray(img))
out_path, modal_black, modal_white = process_grayscale_image(np.array(gray), path, image_processor, temp_folder)
return out_path, modal_black != 0
except (OSError, ValueError) as e:
log_error(f"Error processing color image {path}: {e}")
return path, False
3. (Optional) Update the analyze_file Function
Original analyze_file Function:
def analyze_file(path):
"""Analyze a single image file."""
if is_valid_image(path):
try:
img = np.array(open_and_convert_image(path))
if img.ndim == 2 or (img.ndim == 3 and img.shape[2] == 1):
adjusted, modal_black, modal_white = adjust_values(img)
subfolder = str(path.parent.relative_to(Config.INPUT_FOLDER))
filename = path.name
if modal_black:
image_processor.black_results[subfolder].append((filename, modal_black))
if modal_white != 255:
image_processor.white_results[subfolder].append((filename, modal_white))
else:
hsv = Image.fromarray(img).convert("HSV")
hue = np.array(hsv)[:, :, 0]
subfolder = str(path.parent.relative_to(Config.INPUT_FOLDER))
filename = path.name
if not is_grayscale_image(hue):
image_processor.color_results[subfolder].append(filename)
else:
adjusted, modal_black, modal_white = adjust_values(img)
if modal_black:
image_processor.black_results[subfolder].append((filename, modal_black))
if modal_white != 255:
image_processor.white_results[subfolder].append((filename, modal_white))
except (OSError, ValueError) as e:
log_error(f"Error processing image {path}: {e}")
Updated analyze_file Function Using RGB Differences:
def analyze_file(path, diff_threshold: int = 5, fraction_threshold: float = 0.05):
"""Analyze a single image file using RGB differences to determine color status."""
if is_valid_image(path):
try:
img = np.array(open_and_convert_image(path))
if img.ndim == 2 or (img.ndim == 3 and img.shape[2] == 1):
# Grayscale image
adjusted, modal_black, modal_white = adjust_values(img)
subfolder = str(path.parent.relative_to(Config.INPUT_FOLDER))
filename = path.name
if modal_black:
image_processor.black_results[subfolder].append((filename, modal_black))
if modal_white != 255:
image_processor.white_results[subfolder].append((filename, modal_white))
else:
# Determine if the image is color or grayscale based on RGB differences
if is_color_image(img, diff_threshold, fraction_threshold):
subfolder = str(path.parent.relative_to(Config.INPUT_FOLDER))
filename = path.name
image_processor.color_results[subfolder].append(filename)
else:
adjusted, modal_black, modal_white = adjust_values(img)
subfolder = str(path.parent.relative_to(Config.INPUT_FOLDER))
filename = path.name
if modal_black:
image_processor.black_results[subfolder].append((filename, modal_black))
if modal_white != 255:
image_processor.white_results[subfolder].append((filename, modal_white))
except (OSError, ValueError) as e:
log_error(f"Error processing image {path}: {e}")
Note: Ensure that when calling analyze_file, you pass the diff_threshold and fraction_threshold parameters if they are not set to their default values.
4. Update Any Other Relevant Parts
Ensure that all parts of the code that previously relied on HSV-based color detection now utilize the new RGB-based method. This includes updating any function calls and passing necessary parameters.
For example, in the analyze_images function where process_task is defined, make sure to pass the diff_threshold and fraction_threshold if required.
By implementing these changes, Code 1 will use the RGB channel difference method from Code 2 to determine whether images are color or grayscale, aligning its functionality with the desired approach.