#!/usr/bin/env python3
"""
Manual yellow dot detection and analysis
"""
from PIL import Image
import numpy as np

def analyze_image_for_dots(image_path):
    """Thoroughly analyze image for yellow tracking dots"""
    print(f"Analyzing {image_path}...\n")
    
    img = Image.open(image_path)
    img_array = np.array(img)
    
    print(f"Image shape: {img_array.shape}")
    print(f"Image mode: {img.mode}")
    print(f"Image size: {img.size}")
    print(f"Image format: {img.format}")
    
    if len(img_array.shape) == 3:
        r = img_array[:,:,0].astype(float)
        g = img_array[:,:,1].astype(float)
        b = img_array[:,:,2].astype(float)
        
        print(f"\nChannel statistics:")
        print(f"  R: min={r.min()}, max={r.max()}, mean={r.mean():.2f}")
        print(f"  G: min={g.min()}, max={g.max()}, mean={g.mean():.2f}")
        print(f"  B: min={b.min()}, max={b.max()}, mean={b.mean():.2f}")
        
        # Yellow dots have high R and G, but low B
        # Create yellow channel
        yellow = (r + g - 2*b) / 4
        
        print(f"\nYellow channel:")
        print(f"  min={yellow.min()}, max={yellow.max()}, mean={yellow.mean():.2f}")
        
        # Try to find dots in different ways
        # Method 1: Simple threshold on yellow
        for threshold_pct in [90, 95, 97, 99]:
            threshold = np.percentile(yellow, threshold_pct)
            dots = yellow > threshold
            count = np.sum(dots)
            print(f"  Percentile {threshold_pct} (>{threshold:.2f}): {count} pixels")
        
        # Method 2: Look for pixels where R and G are similar and high, but B is low
        print(f"\nAlternative detection (R≈G, R&G high, B low):")
        rg_similar = np.abs(r - g) < 20
        r_high = r > 200
        g_high = g > 200
        b_low = b < 150
        
        yellow_dots_strict = rg_similar & r_high & g_high & b_low
        print(f"  Strict yellow dots: {np.sum(yellow_dots_strict)} pixels")
        
        # Method 3: Extremely strict - pure yellow
        rg_very_similar = np.abs(r - g) < 10
        r_very_high = r > 230
        g_very_high = g > 230
        b_very_low = b < 100
        
        yellow_dots_very_strict = rg_very_similar & r_very_high & g_very_high & b_very_low
        print(f"  Very strict yellow dots: {np.sum(yellow_dots_very_strict)} pixels")
        
        # Check for pure yellow pixels (255, 255, 0)
        pure_yellow = (r > 250) & (g > 250) & (b < 10)
        print(f"  Pure yellow (255,255,0±5): {np.sum(pure_yellow)} pixels")
        
        # Save various filtered versions
        yellow_normalized = ((yellow - yellow.min()) / (yellow.max() - yellow.min()) * 255).astype(np.uint8)
        Image.fromarray(yellow_normalized).save('analysis_yellow_channel.png')
        
        Image.fromarray((yellow_dots_strict * 255).astype(np.uint8)).save('analysis_strict_yellow.png')
        Image.fromarray((yellow_dots_very_strict * 255).astype(np.uint8)).save('analysis_very_strict_yellow.png')
        
        print(f"\nSaved analysis images:")
        print(f"  - analysis_yellow_channel.png")
        print(f"  - analysis_strict_yellow.png")
        print(f"  - analysis_very_strict_yellow.png")
        
        # Check a small crop for patterns
        crop_size = 500
        crop = img_array[:crop_size, :crop_size, :]
        
        r_crop = crop[:,:,0].astype(float)
        g_crop = crop[:,:,1].astype(float)
        b_crop = crop[:,:,2].astype(float)
        yellow_crop = (r_crop + g_crop - 2*b_crop) / 4
        
        threshold = np.percentile(yellow_crop, 98)
        dots_crop = yellow_crop > threshold
        
        Image.fromarray((dots_crop * 255).astype(np.uint8)).save('analysis_crop_dots.png')
        print(f"  - analysis_crop_dots.png (top-left {crop_size}x{crop_size})")

if __name__ == "__main__":
    analyze_image_for_dots("Zard.jpg")
