#!/usr/bin/env python3
"""
Script to extract and analyze printer tracking dots from an image
"""
from PIL import Image
import numpy as np
import sys

def extract_yellow_channel(image_path):
    """Extract and enhance the yellow channel to find tracking dots"""
    img = Image.open(image_path)
    img_array = np.array(img)
    
    # Convert to float for better processing
    img_float = img_array.astype(float)
    
    # Extract yellow dots by looking at differences in blue channel
    # Yellow dots appear as areas with low blue, high red and green
    if len(img_array.shape) == 3:
        r = img_float[:,:,0]
        g = img_float[:,:,1]
        b = img_float[:,:,2]
        
        # Yellow has high R and G, but low B
        yellow = (r + g - 2*b) / 3
        
        # Normalize
        yellow = (yellow - yellow.min()) / (yellow.max() - yellow.min()) * 255
        
        # Create image
        yellow_img = Image.fromarray(yellow.astype(np.uint8))
        yellow_img.save('yellow_channel.png')
        print(f"Saved yellow channel to yellow_channel.png")
        print(f"Image shape: {img_array.shape}")
        print(f"Yellow channel stats: min={yellow.min()}, max={yellow.max()}, mean={yellow.mean()}")
        
        # Try to find dots by thresholding
        threshold = np.percentile(yellow, 95)  # Top 5% brightest pixels
        dots = yellow > threshold
        dot_count = np.sum(dots)
        print(f"Potential dots found (threshold={threshold:.2f}): {dot_count}")
        
        # Save dots image
        dots_img = Image.fromarray((dots * 255).astype(np.uint8))
        dots_img.save('dots_detected.png')
        print("Saved detected dots to dots_detected.png")
        
    return img_array

if __name__ == "__main__":
    image_path = "Zard.jpg"
    print(f"Analyzing {image_path}...")
    extract_yellow_channel(image_path)
