Spaces:
Sleeping
Sleeping
Elvis Claude Opus 4.5 commited on
Commit ·
abd1771
1
Parent(s): 292612f
Add EXIF metadata reading and dynamic tone curve analysis
Browse files- Read actual camera settings (focal length, aperture, ISO, shutter) from EXIF
- Fall back to estimation with "(estimated)" label when EXIF unavailable
- Display camera make/model and lens info when available
- Add EXIF/Estimated badge to CameraPanel
- Generate tone curve from image histogram analysis
- Render dynamic SVG curve based on actual tonal distribution
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
Files changed (3)
123451 unmodified line789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616218 unmodified lines81828384858687888935369091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818941421901914445192193474819419519619719819952200201542022035620420520620720820960210211622122136465666768697071727374214215216217295 unmodified lines5135145155165175185195205211 unmodified line523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582from PIL import Imagefrom PIL.ExifTags import TAGS, GPSTAGSimport numpy as npfrom io import BytesIOfrom colorthief import ColorThief1 unmodified line
class ImageAnalyzer: # Common EXIF tag IDs EXIF_FOCAL_LENGTH = 37386 EXIF_FOCAL_LENGTH_35MM = 41989 EXIF_FNUMBER = 33437 EXIF_ISO = 34855 EXIF_EXPOSURE_TIME = 33434 EXIF_MAKE = 271 EXIF_MODEL = 272 EXIF_LENS_MODEL = 42036
def _extract_exif(self, image: Image.Image) -> dict: """Extract EXIF metadata from image.""" exif_data = {} try: exif = image._getexif() if exif: for tag_id, value in exif.items(): tag = TAGS.get(tag_id, tag_id) exif_data[tag] = value exif_data[tag_id] = value # Also store by ID for reliable lookup except (AttributeError, KeyError, TypeError): pass return exif_data
def _format_exposure_time(self, exposure) -> str: """Format exposure time as a fraction.""" if exposure is None: return None try: # Handle IFDRational or tuple if hasattr(exposure, 'numerator'): num, den = exposure.numerator, exposure.denominator elif isinstance(exposure, tuple): num, den = exposure else: val = float(exposure) if val >= 1: return f"{val:.1f}s" return f"1/{int(1/val)}s"
if num == 0: return None if den == 1: return f"{num}s" # Simplify fraction if num == 1: return f"1/{den}s" return f"{num}/{den}s" except (TypeError, ValueError, ZeroDivisionError): return None def analyze(self, image_bytes: BytesIO) -> dict: image = Image.open(image_bytes) image_bytes.seek(0)18 unmodified lines width, height = image.size aspect_ratio = width / height
# First, try to extract EXIF data exif = self._extract_exif(image) has_exif = len(exif) > 0
img_array = np.array(image.convert("L"))
# Estimate focal length based on perspective distortion analysis focal_estimate, sensor_hint = self._estimate_focal_length(img_array, width, height) # Focal Length - prefer EXIF focal_exif = exif.get(self.EXIF_FOCAL_LENGTH) or exif.get('FocalLength') focal_35mm = exif.get(self.EXIF_FOCAL_LENGTH_35MM) or exif.get('FocalLengthIn35mmFilm')
if focal_exif: try: focal_val = float(focal_exif) if focal_35mm: focal_estimate = f"{focal_val:.0f}mm ({float(focal_35mm):.0f}mm equiv)" else: focal_estimate = f"{focal_val:.0f}mm" # Determine sensor hint based on focal length if focal_val < 24: sensor_hint = "Ultra-wide angle lens" elif focal_val < 35: sensor_hint = "Wide angle lens" elif focal_val < 50: sensor_hint = "Wide-normal lens" elif focal_val < 85: sensor_hint = "Standard lens" elif focal_val < 135: sensor_hint = "Portrait/Short telephoto" else: sensor_hint = "Telephoto lens" except (TypeError, ValueError): focal_estimate, sensor_hint = self._estimate_focal_length(img_array, width, height) else: focal_estimate, sensor_hint = self._estimate_focal_length(img_array, width, height)
# Aperture - prefer EXIF fnumber = exif.get(self.EXIF_FNUMBER) or exif.get('FNumber') if fnumber: try: f_val = float(fnumber) aperture = f"f/{f_val:.1f}" if f_val <= 2.0: dof = "Shallow" elif f_val <= 5.6: dof = "Medium" else: dof = "Deep" except (TypeError, ValueError): aperture, dof = self._estimate_aperture(img_array) else: aperture, dof = self._estimate_aperture(img_array)
# ISO - prefer EXIF iso_exif = exif.get(self.EXIF_ISO) or exif.get('ISOSpeedRatings') if iso_exif: try: # ISO can be a single value or a tuple if isinstance(iso_exif, (list, tuple)): iso_val = int(iso_exif[0]) else: iso_val = int(iso_exif) iso = f"ISO {iso_val}" except (TypeError, ValueError, IndexError): iso = self._estimate_iso(img_array) else: iso = self._estimate_iso(img_array)
# Shutter Speed - prefer EXIF exposure = exif.get(self.EXIF_EXPOSURE_TIME) or exif.get('ExposureTime') shutter = self._format_exposure_time(exposure) if not shutter: shutter = self._estimate_shutter(img_array)
# Camera/Lens info camera_make = exif.get(self.EXIF_MAKE) or exif.get('Make', '') camera_model = exif.get(self.EXIF_MODEL) or exif.get('Model', '') lens_model = exif.get(self.EXIF_LENS_MODEL) or exif.get('LensModel', '')
camera_info = None if camera_make or camera_model: camera_info = f"{camera_make} {camera_model}".strip()
result = { "focalLength": focal_estimate, "aperture": aperture, "depthOfField": dof, "iso": iso, "shutterSpeed": shutter, "sensorSize": sensor_hint, "aspectRatio": f"{width}:{height}", "hasExif": has_exif, }
if camera_info: result["camera"] = camera_info if lens_model: result["lens"] = str(lens_model)
return result
def _estimate_aperture(self, img_array: np.ndarray) -> tuple: """Estimate aperture from edge variance when EXIF not available.""" edges = np.abs(np.diff(img_array.astype(float), axis=0)) edge_variance = np.var(edges)
if edge_variance > 2000: aperture = "f/5.6 - f/8 (Deep DoF)" dof = "Deep" return "f/5.6 - f/8 (estimated)", "Deep" elif edge_variance > 1000: aperture = "f/2.8 - f/4" dof = "Medium" return "f/2.8 - f/4 (estimated)", "Medium" else: aperture = "f/1.4 - f/2.0 (Shallow DoF)" dof = "Shallow" return "f/1.4 - f/2.0 (estimated)", "Shallow"
def _estimate_iso(self, img_array: np.ndarray) -> str: """Estimate ISO from brightness when EXIF not available.""" brightness = np.mean(img_array) if brightness > 150: iso = "Low (100-400)" return "Low ISO (estimated)" elif brightness > 80: iso = "Medium (400-1600)" return "Medium ISO (estimated)" else: iso = "Higher (1600+)" return "High ISO (estimated)"
def _estimate_shutter(self, img_array: np.ndarray) -> str: """Estimate shutter speed from motion blur when EXIF not available.""" motion_blur = self._detect_motion_blur(img_array) if motion_blur > 0.7: shutter = "Slow (1/30s or slower)" return "Slow shutter (estimated)" elif motion_blur > 0.4: shutter = "~1/60s - 1/125s" return "~1/60s - 1/125s (estimated)" else: shutter = "Fast (1/250s+)"
return { "focalLength": focal_estimate, "aperture": aperture, "depthOfField": dof, "iso": iso, "shutterSpeed": shutter, "sensorSize": sensor_hint, "aspectRatio": f"{width}:{height}", } return "Fast shutter (estimated)"
def _detect_motion_blur(self, gray_image: np.ndarray) -> float: laplacian = np.abs(295 unmodified lines else: saturation = "Desaturated"
# Analyze tone curve from image histogram tone_curve = self._analyze_tone_curve(gray)
return { "palette": palette_hex, "temperature": temp,1 unmodified line "saturation": saturation, "shadows": f"Lifted, {shadow_tint}", "highlights": highlight_tint, "toneCurve": tone_curve, }
def _analyze_tone_curve(self, gray: np.ndarray) -> list: """ Analyze the image's tonal distribution and return control points for a tone curve. Returns a list of [x, y] points where x is input (0-100) and y is output (0-100). """ # Compute histogram hist, _ = np.histogram(gray.flatten(), bins=256, range=(0, 256))
# Compute cumulative distribution function (CDF) cdf = hist.cumsum() cdf_normalized = cdf / cdf[-1] # Normalize to 0-1
# Sample the CDF at key points to create curve control points # We sample at shadows, quarter-tones, midtones, three-quarter-tones, highlights sample_points = [0, 32, 64, 96, 128, 160, 192, 224, 255] curve_points = []
for input_val in sample_points: # The CDF tells us what percentage of pixels are at or below this value # We use this to derive the "output" value for the curve output_val = cdf_normalized[input_val] * 100 input_normalized = (input_val / 255) * 100 curve_points.append([round(input_normalized, 1), round(output_val, 1)])
# Analyze characteristics for additional curve shaping # Check if shadows are lifted (black point is raised) black_point = np.percentile(gray, 2) white_point = np.percentile(gray, 98)
# Adjust curve based on actual tonal range if black_point > 20: # Lifted shadows # Raise the shadow portion of the curve for i, pt in enumerate(curve_points): if pt[0] < 25: lift_amount = (black_point / 255) * 100 * 0.5 curve_points[i][1] = min(100, pt[1] + lift_amount * (1 - pt[0]/25))
if white_point < 235: # Crushed highlights # Lower the highlight portion for i, pt in enumerate(curve_points): if pt[0] > 75: crush_amount = ((255 - white_point) / 255) * 100 * 0.5 curve_points[i][1] = max(0, pt[1] - crush_amount * ((pt[0] - 75) / 25))
# Ensure curve is valid (monotonically increasing, within bounds) for i, pt in enumerate(curve_points): curve_points[i][1] = max(0, min(100, pt[1]))
# Convert to list of floats for JSON serialization return [[float(p[0]), float(p[1])] for p in curve_points]
def _generate_summary(self, camera: dict, lighting: dict, color: dict) -> str: return ( f"This appears to be a {camera['depthOfField'].lower()} depth of field shot, "14 unmodified lines15161718192021222324252627283 unmodified lines32333435363738394041424344454614 unmodified lines { label: 'Sensor Size', value: camera.sensorSize, icon: '📷' }, ]
// Add camera/lens info if available from EXIF if (camera.camera) { items.unshift({ label: 'Camera', value: camera.camera, icon: '📷' }) } if (camera.lens) { items.splice(camera.camera ? 1 : 0, 0, { label: 'Lens', value: camera.lens, icon: '🔍' }) }
return ( <div className="p-6 bg-slate-800/50 rounded-xl border border-slate-700/50"> <div className="flex items-center gap-2 mb-4">3 unmodified lines </svg> </div> <h3 className="text-lg font-semibold text-white">Camera Settings</h3> {camera.hasExif ? ( <span className="ml-auto text-xs px-2 py-0.5 rounded-full bg-green-500/20 text-green-400 border border-green-500/30"> EXIF Data </span> ) : ( <span className="ml-auto text-xs px-2 py-0.5 rounded-full bg-amber-500/20 text-amber-400 border border-amber-500/30"> Estimated </span> )} </div>
<div className="space-y-3">15 unmodified lines161718192021222324252627282930313233343536373839404142434445464748495051525354555638 unmodified lines9596979899100101651021031041051061077110810911011111211311411511611711811912012112212312415 unmodified lines { label: 'Highlights', value: color.highlights }, ]
// Generate SVG path from tone curve points // Points are [x, y] where x and y are 0-100, y needs to be flipped for SVG coordinates const generateCurvePath = (points) => { if (!points || points.length < 2) { // Fallback to linear curve return "M 0 100 L 100 0" }
// Convert points to SVG coordinates (flip Y axis) const svgPoints = points.map(([x, y]) => [x, 100 - y])
// Create a smooth curve through the points using quadratic bezier let path = `M ${svgPoints[0][0]} ${svgPoints[0][1]}`
for (let i = 1; i < svgPoints.length; i++) { const prev = svgPoints[i - 1] const curr = svgPoints[i]
// Use quadratic bezier for smooth curve const cpX = (prev[0] + curr[0]) / 2 const cpY = prev[1]
if (i === 1) { path += ` Q ${cpX} ${cpY}, ${curr[0]} ${curr[1]}` } else { path += ` T ${curr[0]} ${curr[1]}` } }
return path }
const curvePath = generateCurvePath(color.toneCurve) const fillPath = curvePath + " L 100 100 L 0 100 Z"
return ( <div className="p-6 bg-slate-800/50 rounded-xl border border-slate-700/50"> <div className="flex items-center justify-between mb-4">38 unmodified lines <stop offset="100%" stopColor="#ea580c" stopOpacity="0.3" /> </linearGradient> </defs> {/* Reference diagonal line (linear response) */} <line x1="0" y1="100" x2="100" y2="0" stroke="#374151" strokeWidth="0.5" strokeDasharray="2,2" /> {/* Actual tone curve from image analysis */} <path d="M 0 95 Q 15 85, 30 70 T 60 40 T 100 5" d={curvePath} fill="none" stroke="url(#curveGradient)" strokeWidth="2" /> <path d="M 0 95 Q 15 85, 30 70 T 60 40 T 100 5 L 100 100 L 0 100 Z" d={fillPath} fill="url(#curveGradient)" /> {/* Control points visualization */} {color.toneCurve?.map(([x, y], i) => ( <circle key={i} cx={x} cy={100 - y} r="1.5" fill="#f59e0b" opacity="0.6" /> ))} </svg> <div className="absolute bottom-2 left-2 text-xs text-slate-500">Shadows</div> <div className="absolute top-2 right-2 text-xs text-slate-500">Highlights</div>backend/app/services/analyzer.py+219-24
frontend/src/components/CameraPanel.jsx+17
frontend/src/components/ColorPanel.jsx+50-2