-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsensor_camera.py
More file actions
executable file
·793 lines (651 loc) · 29.4 KB
/
Copy pathsensor_camera.py
File metadata and controls
executable file
·793 lines (651 loc) · 29.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
# Standard modules
import os
# Common 3rd party
import numpy as np
import plotly.express as px
import pandas as pd
from tqdm import tqdm
# Raw-specific modules
import rawpy
try:
from utils.exiftool_helper import get_exiftool_helper
except ImportError:
# Fallback for standalone use of sensor_camera.py
import exiftool
def get_exiftool_helper(**kwargs):
return exiftool.ExifToolHelper(**kwargs)
# GPU acceleration (optional)
try:
import cupy as cp
GPU_AVAILABLE = True
print("GPU acceleration enabled (CuPy detected)")
except ImportError:
cp = None
GPU_AVAILABLE = False
print("GPU acceleration not available (CuPy not installed)")
class Sensor(object):
"""Analyzes noise characteristics of camera sensors from raw image files."""
# Camera-specific crop regions to remove artifacts
CAMERA_CROPS = {
"LEICA Q (Typ 116)": (slice(None), slice(0, 6011)),
"RICOH GR III": (slice(28, 4052), slice(56, 6088)),
"LEICA CL": (slice(None), slice(0, 6048)),
"LEICA Q3": (slice(None), slice(0, 7412)),
"LEICA SL2-S": (slice(0, 4000), slice(0, 6000)),
}
def __init__(self, path='.', use_gpu=True):
"""Initialize Sensor with a base path for scanning.
Args:
path: Base directory path containing camera raw files
use_gpu: Use GPU acceleration if available (default: True)
"""
self.path = path
self.data = None
self.use_gpu = use_gpu and GPU_AVAILABLE
if use_gpu and not GPU_AVAILABLE:
print("Warning: GPU requested but not available, falling back to CPU")
def _get_scan_path(self, path):
"""Construct the full scan path from base path and relative path.
Args:
path: Relative path or None to use base path
Returns:
Full absolute path for scanning
"""
if path is None:
return self.path
return os.path.join(self.path, path)
def _get_file_list(self, directory, suffix):
"""Get sorted list of raw files with given suffix.
Args:
directory: Directory to scan
suffix: File extension to filter by
Returns:
Sorted list of filenames
"""
return sorted([
filename for filename in os.listdir(directory)
if filename.upper().endswith(suffix.upper())
])
def _extract_black_level(self, metadata, raw):
"""Extract black level from metadata or raw file.
Args:
metadata: EXIF metadata dictionary
raw: rawpy RawImage object
Returns:
Black level value as integer
"""
black_level = metadata.get('EXIF:BlackLevel')
if black_level is None:
black_level = metadata.get('MakerNotes:BlackLevel')
if isinstance(black_level, str):
return int(black_level.split()[0])
elif black_level is None:
return raw.black_level_per_channel[0]
return black_level
def _extract_white_level(self, metadata):
"""Extract white level from metadata.
Args:
metadata: EXIF metadata dictionary
Returns:
White level value as integer
"""
white_level = metadata.get('EXIF:WhiteLevel')
if white_level is None:
# Assume white level is based on bit depth
bits = metadata.get('EXIF:BitsPerSample')
if bits is not None:
white_level = 2**bits
if isinstance(white_level, str):
return int(white_level.split()[0])
return white_level
def _extract_camera_name(self, metadata):
"""Extract camera name from metadata.
Args:
metadata: EXIF metadata dictionary
Returns:
Camera name string
"""
camera = metadata.get('EXIF:UniqueCameraModel')
if camera is None:
camera = metadata.get('EXIF:Model')
return camera
def _apply_camera_crop(self, image, camera):
"""Apply camera-specific crop to remove artifacts.
Args:
image: numpy array of raw image data
camera: Camera name string
Returns:
Cropped image array
"""
if camera in self.CAMERA_CROPS:
crop = self.CAMERA_CROPS[camera]
return image[crop[0], crop[1]]
return image
def _extract_dimensions(self, metadata):
"""Extract image dimensions from metadata.
Args:
metadata: EXIF metadata dictionary
Returns:
Tuple of (width, height)
"""
width = metadata.get('EXIF:ExifImageWidth')
if width is None:
width = metadata.get('EXIF:ImageWidth')
height = metadata.get('EXIF:ExifImageHeight')
if height is None:
height = metadata.get('EXIF:ImageHeight')
return width, height
def _calculate_image_stats(self, image):
"""Calculate statistical measures of image data.
Uses GPU acceleration if enabled and available.
Args:
image: numpy array of raw image data
Returns:
Dictionary with std, mean, min, max values
"""
if self.use_gpu:
# Transfer to GPU, compute, and transfer back
gpu_image = cp.asarray(image)
stats = {
'std': float(cp.std(gpu_image)),
'mean': float(cp.mean(gpu_image)),
'min': float(cp.min(gpu_image)),
'max': float(cp.max(gpu_image)),
}
# Explicitly free GPU memory
del gpu_image
else:
# CPU computation
stats = {
'std': np.std(image),
'mean': np.mean(image),
'min': np.min(image),
'max': np.max(image),
}
return stats
def _process_raw_file(self, filepath, metadata):
"""Process a single raw file and extract noise characteristics.
Args:
filepath: Path to raw file
metadata: EXIF metadata dictionary
Returns:
Dictionary with processed data for this file
"""
raw = rawpy.imread(filepath)
# Extract metadata
black_level = self._extract_black_level(metadata, raw)
white_level = self._extract_white_level(metadata)
camera = self._extract_camera_name(metadata)
width, height = self._extract_dimensions(metadata)
# Process image
image = raw.raw_image
image = self._apply_camera_crop(image, camera)
stats = self._calculate_image_stats(image)
raw.close()
# Build result dictionary
return {
'camera': camera,
'source': metadata.get('SourceFile'),
'black_level': black_level,
'white_level': white_level,
'width': width,
'height': height,
'iso': metadata.get('EXIF:ISO'),
'time': metadata.get('EXIF:ExposureTime'),
**stats
}
def _calculate_exposure_value(self, data):
"""Calculate exposure value (EV) from noise data.
EV = log2((white_level - black_level) / std_dev)
Args:
data: DataFrame with noise measurements
Returns:
DataFrame with EV column added
"""
data['EV'] = data.apply(
lambda x: np.log((x['white_level'] - x['black_level']) / x['std']) / np.log(2),
axis='columns'
)
return data
def _save_results(self, data, directory):
"""Save scan results to CSV file in the scanned directory.
Args:
data: DataFrame with scan results
directory: Directory to save results in
"""
output_file = os.path.join(directory, 'noise_results.csv')
data.to_csv(output_file, index=False)
print(f'Results saved to: {output_file}')
def scan(self, path=None, suffix='DNG', force_rescan=False):
"""Scan a directory for raw files and analyze noise characteristics.
Args:
path: Relative path from base directory (None to use base path)
suffix: File extension to scan for (default: 'DNG')
force_rescan: If True, rescan even if results exist (default: False)
Returns:
DataFrame with noise analysis results for all scanned files
"""
full_path = self._get_scan_path(path)
results_file = os.path.join(full_path, 'noise_results.csv')
# Check if results already exist
if not force_rescan and os.path.exists(results_file):
print(f'Loading existing results from: {results_file}')
data = pd.read_csv(results_file)
self.data = data
return data
file_list = self._get_file_list(full_path, suffix)
results = []
with get_exiftool_helper() as et:
# Create progress bar
with tqdm(total=len(file_list), desc='Scanning files', unit='file') as pbar:
for filename in file_list:
# Update progress bar with current filename
pbar.set_postfix_str(f'Processing: {filename}')
filepath = os.path.join(full_path, filename)
metadata = et.get_metadata(filepath)[0]
file_data = self._process_raw_file(filepath, metadata)
results.append(file_data)
# Update progress bar
pbar.update(1)
# Create DataFrame and calculate derived metrics
data = pd.DataFrame(results)
data = self._calculate_exposure_value(data)
# Store and save results
self.data = data
self._save_results(data, full_path)
return data
class Analysis(object):
"""Manages aggregate analysis of multiple camera sensors."""
def __init__(self, base_path='.'):
"""Initialize Analysis with a base path for scanning.
Args:
base_path: Base directory path containing camera raw files
"""
self.base_path = base_path
self.sensor = Sensor(base_path)
self.scan_results = None
self.aggregate_data = None
def scan(self, scan_specs, force_rescan=False):
"""Scan multiple cameras according to specifications.
Args:
scan_specs: OrderedDict with camera names as keys and scan parameters as values
Each value should be a dict with 'path' and 'suffix' keys
force_rescan: If True, rescan even if cached results exist (default: False)
Returns:
OrderedDict with scan results for each camera
Example:
>>> from collections import OrderedDict
>>> specs = OrderedDict([
... ('Leica M11', {'path': 'M11-36MP', 'suffix': 'DNG'}),
... ('Leica Q3', {'path': 'Q3-36MP', 'suffix': 'DNG'}),
... ])
>>> analysis = Analysis('/path/to/data')
>>> results = analysis.scan(specs)
"""
from collections import OrderedDict
scan_results = OrderedDict()
for name, params in scan_specs.items():
print(f"Scanning {name}...")
# Add force_rescan to params if specified
scan_params = params.copy()
scan_params['force_rescan'] = force_rescan
# Scan and store results
scan_results[name] = self.sensor.scan(**scan_params)
self.scan_results = scan_results
return scan_results
def create_aggregate(self, camera_list=None):
"""Create aggregate DataFrame from scan results.
Args:
camera_list: List of camera names to include (default: all scanned cameras)
Returns:
Combined DataFrame with data from selected cameras
"""
if self.scan_results is None:
raise ValueError("No scan results available. Run scan() first.")
# Use all cameras if not specified
if camera_list is None:
camera_list = list(self.scan_results.keys())
# Concatenate selected camera data, preserving the scan_specs key as camera name
data_frames = []
for name in camera_list:
if name in self.scan_results:
df = self.scan_results[name].copy()
# Override the EXIF camera name with the scan_specs key to preserve variant info
df['camera'] = name
data_frames.append(df)
if not data_frames:
raise ValueError("No valid cameras found in scan results")
self.aggregate_data = pd.concat(data_frames, ignore_index=True)
return self.aggregate_data
def save_aggregate(self, filename='aggregate_analysis.csv'):
"""Save aggregate data to CSV file.
Args:
filename: Output filename (default: 'aggregate_analysis.csv')
"""
if self.aggregate_data is None:
raise ValueError("No aggregate data available. Run create_aggregate() first.")
self.aggregate_data.to_csv(filename, index=False)
print(f"Aggregate analysis saved to: {filename}")
def get_aliases(self, short_names=None):
"""Create convenient variable aliases for scan results.
Args:
short_names: Dict mapping camera names to short variable names
If None, uses simple numbered aliases
Returns:
Dictionary of aliases pointing to scan results
"""
if self.scan_results is None:
raise ValueError("No scan results available. Run scan() first.")
aliases = {}
if short_names is None:
# Auto-generate simple aliases
for i, name in enumerate(self.scan_results.keys()):
aliases[f'camera_{i}'] = self.scan_results[name]
else:
# Use provided mapping
for full_name, short_name in short_names.items():
if full_name in self.scan_results:
aliases[short_name] = self.scan_results[full_name]
return aliases
def plot_ev_vs_iso(self, data=None, exposure_time=None, title=None, height=700, ev_range=None):
"""Create a professional plot of Exposure Value vs ISO for camera comparison.
Args:
data: DataFrame with camera noise data (default: uses self.aggregate_data)
exposure_time: Filter data to this exposure time. Can be:
- Single value (e.g., 0.004 for 1/250s)
- List of values (e.g., [0.004, 0.001])
- None (creates plot for each unique exposure time)
Default: None (all exposure times)
title: Custom title for the plot (default: auto-generated)
height: Plot height in pixels (default: 700)
ev_range: Tuple of (min, max) for Y-axis range (default: auto-calculated with padding)
Returns:
Single Plotly figure (if exposure_time is single value)
or list of figures (if exposure_time is list or None)
"""
# Use aggregate data if not provided
if data is None:
if self.aggregate_data is None:
raise ValueError("No data available. Run create_aggregate() first or provide data.")
data = self.aggregate_data
# Handle multiple exposure times
if exposure_time is None:
# Get all unique exposure times, sorted
exposure_times = sorted(data['time'].unique())
elif isinstance(exposure_time, (list, tuple)):
exposure_times = exposure_time
else:
exposure_times = [exposure_time]
# If multiple exposure times, create multiple plots
if len(exposure_times) > 1:
figures = []
for exp_time in exposure_times:
fig = self._create_ev_vs_iso_plot(data, exp_time, title, height, ev_range)
figures.append(fig)
return figures
# Single exposure time - create one plot
return self._create_ev_vs_iso_plot(data, exposure_times[0], title, height, ev_range)
def _create_ev_vs_iso_plot(self, data, exposure_time, title, height, ev_range):
"""Internal method to create a single EV vs ISO plot."""
# Filter data by exposure time
filtered_data = data[data['time'] == exposure_time]
# Generate title if not provided
if title is None:
shutter_speed = f"1/{round(1/exposure_time)}s" if exposure_time > 0 else "N/A"
title = f'Camera Sensor Dynamic Range vs ISO Sensitivity<br><sub>Measured at {shutter_speed} shutter speed</sub>'
# Calculate EV range if not provided - add 10% padding
if ev_range is None:
ev_min = filtered_data['EV'].min()
ev_max = filtered_data['EV'].max()
ev_padding = (ev_max - ev_min) * 0.1
ev_range = [ev_min - ev_padding, ev_max + ev_padding]
# Parse camera names to extract base model and group variants
def parse_camera_name(name):
"""Extract base model and variant from camera name."""
if '(' in name:
parts = name.split('(')
base = parts[0].strip()
variant = '(' + parts[1].strip()
return base, variant
return name, ''
# Group cameras by base model
camera_groups = {}
for camera in filtered_data['camera'].unique():
base_model, variant = parse_camera_name(camera)
if base_model not in camera_groups:
camera_groups[base_model] = []
camera_groups[base_model].append((camera, variant))
# Create color palette for base models
import plotly.colors as pc
color_sequence = pc.qualitative.Plotly
base_model_colors = {}
for i, base_model in enumerate(camera_groups.keys()):
base_model_colors[base_model] = color_sequence[i % len(color_sequence)]
# Line styles for variants
line_styles = ['solid', 'dash', 'dot', 'dashdot', 'longdash', 'longdashdot']
# Create the plot manually to control colors and grouping
from plotly import graph_objects as go
fig = go.Figure()
for base_model, variants in camera_groups.items():
base_color = base_model_colors[base_model]
has_multiple_variants = len(variants) > 1
for idx, (camera_name, variant) in enumerate(variants):
camera_data = filtered_data[filtered_data['camera'] == camera_name]
# Use different line styles for variants of the same base model
line_style = line_styles[idx % len(line_styles)] if has_multiple_variants else 'solid'
# Format shutter speed for hover
shutter_speed = f"1/{round(1/exposure_time)}s" if exposure_time > 0 else "N/A"
trace = go.Scatter(
x=camera_data['iso'],
y=camera_data['EV'],
mode='markers+lines',
name=camera_name,
legendgroup=base_model,
legendgrouptitle=dict(text=base_model) if has_multiple_variants else None,
line=dict(color=base_color, width=2.5, dash=line_style),
marker=dict(size=8, color=base_color, line=dict(width=1, color='white')),
hovertemplate=f'{camera_name}<br>ISO%{{x}} | {shutter_speed} | %{{y:.1f}}eV<extra></extra>',
showlegend=True
)
fig.add_trace(trace)
# Update axes to log scale for x
fig.update_xaxes(type='log')
# Set title and labels
fig.update_layout(
title=title,
xaxis_title='ISO Sensitivity',
yaxis_title='Exposure Value (EV)',
height=height
)
# Update layout for professional appearance
fig.update_layout(
hovermode="x unified",
hoverlabel=dict(bgcolor="white", font_size=12),
font=dict(family="Arial, sans-serif", size=12),
title=dict(font=dict(size=18, color='#2c3e50'), x=0.5, xanchor='center'),
xaxis=dict(
showgrid=True,
gridwidth=1,
gridcolor='rgba(128,128,128,0.2)',
title_font=dict(size=14, color='#2c3e50'),
tickfont=dict(size=11),
hoverformat=',d' # Format ISO as integer with thousands separator
),
yaxis=dict(
showgrid=True,
gridwidth=1,
gridcolor='rgba(128,128,128,0.2)',
title_font=dict(size=14, color='#2c3e50'),
tickfont=dict(size=11),
range=ev_range
),
legend=dict(
title=dict(text='Camera Model', font=dict(size=13, color='#2c3e50')),
font=dict(size=11),
bgcolor='rgba(255,255,255,0.9)',
bordercolor='rgba(128,128,128,0.3)',
borderwidth=1,
x=1.02,
y=1,
xanchor='left',
yanchor='top'
),
plot_bgcolor='white',
paper_bgcolor='white',
margin=dict(l=80, r=200, t=100, b=80)
)
return fig
def plot_ev_vs_time(self, data=None, iso=None, title=None, height=700, ev_range=None):
"""Create a professional plot of Exposure Value vs Exposure Time for camera comparison.
Args:
data: DataFrame with camera noise data (default: uses self.aggregate_data)
iso: Filter data to this ISO value. Can be:
- Single value (e.g., 3200)
- List of values (e.g., [3200, 6400])
- None (creates plot for each unique ISO value)
Default: None
title: Custom title for the plot (default: auto-generated)
height: Plot height in pixels (default: 700)
ev_range: Tuple of (min, max) for Y-axis range (default: auto-calculated with padding)
Returns:
Single Plotly figure (if iso is single value)
or list of figures (if iso is list or None)
"""
# Use aggregate data if not provided
if data is None:
if self.aggregate_data is None:
raise ValueError("No data available. Run create_aggregate() first or provide data.")
data = self.aggregate_data
# Handle multiple ISO values
if iso is None:
# Get all unique ISO values, sorted
iso_values = sorted(data['iso'].unique())
elif isinstance(iso, (list, tuple)):
iso_values = iso
else:
iso_values = [iso]
# If multiple ISO values, create multiple plots
if len(iso_values) > 1:
figures = []
for iso_val in iso_values:
fig = self._create_ev_vs_time_plot(data, iso_val, title, height, ev_range)
figures.append(fig)
return figures
# Single ISO value - create one plot
return self._create_ev_vs_time_plot(data, iso_values[0], title, height, ev_range)
def _create_ev_vs_time_plot(self, data, iso, title, height, ev_range):
"""Internal method to create a single EV vs Time plot."""
# Filter data by ISO
filtered_data = data[data['iso'] == iso]
if len(filtered_data) == 0:
raise ValueError(f"No data found for ISO {iso}")
# Generate title if not provided
if title is None:
title = f'Camera Sensor Dynamic Range vs Exposure Time<br><sub>Measured at ISO {iso}</sub>'
# Calculate EV range if not provided - add 10% padding
if ev_range is None:
ev_min = filtered_data['EV'].min()
ev_max = filtered_data['EV'].max()
ev_padding = (ev_max - ev_min) * 0.1
ev_range = [ev_min - ev_padding, ev_max + ev_padding]
# Parse camera names to extract base model and group variants
def parse_camera_name(name):
"""Extract base model and variant from camera name."""
if '(' in name:
parts = name.split('(')
base = parts[0].strip()
variant = '(' + parts[1].strip()
return base, variant
return name, ''
# Group cameras by base model
camera_groups = {}
for camera in filtered_data['camera'].unique():
base_model, variant = parse_camera_name(camera)
if base_model not in camera_groups:
camera_groups[base_model] = []
camera_groups[base_model].append((camera, variant))
# Create color palette for base models
import plotly.colors as pc
color_sequence = pc.qualitative.Plotly
base_model_colors = {}
for i, base_model in enumerate(camera_groups.keys()):
base_model_colors[base_model] = color_sequence[i % len(color_sequence)]
# Line styles for variants
line_styles = ['solid', 'dash', 'dot', 'dashdot', 'longdash', 'longdashdot']
# Create the plot manually to control colors and grouping
from plotly import graph_objects as go
fig = go.Figure()
for base_model, variants in camera_groups.items():
base_color = base_model_colors[base_model]
has_multiple_variants = len(variants) > 1
for idx, (camera_name, variant) in enumerate(variants):
camera_data = filtered_data[filtered_data['camera'] == camera_name].sort_values('time')
# Use different line styles for variants of the same base model
line_style = line_styles[idx % len(line_styles)] if has_multiple_variants else 'solid'
# Create custom hover text with shutter speed format
hover_text = []
for _, row in camera_data.iterrows():
time_val = row['time']
shutter_speed = f"1/{int(1/time_val)}s" if time_val > 0 else "N/A"
hover_text.append(f"{camera_name}<br>ISO{iso} | {shutter_speed} | {row['EV']:.1f}eV")
trace = go.Scatter(
x=camera_data['time'],
y=camera_data['EV'],
mode='markers+lines',
name=camera_name,
legendgroup=base_model,
legendgrouptitle=dict(text=base_model) if has_multiple_variants else None,
line=dict(color=base_color, width=2.5, dash=line_style),
marker=dict(size=8, color=base_color, line=dict(width=1, color='white')),
text=hover_text,
hovertemplate='%{text}<extra></extra>',
showlegend=True
)
fig.add_trace(trace)
# Update axes to log scale for x
fig.update_xaxes(type='log')
# Set title and labels
fig.update_layout(
title=title,
xaxis_title='Exposure Time (seconds)',
yaxis_title='Exposure Value (EV)',
height=height
)
# Update layout for professional appearance
fig.update_layout(
hovermode="x unified",
hoverlabel=dict(bgcolor="white", font_size=12),
font=dict(family="Arial, sans-serif", size=12),
title=dict(font=dict(size=18, color='#2c3e50'), x=0.5, xanchor='center'),
xaxis=dict(
showgrid=True,
gridwidth=1,
gridcolor='rgba(128,128,128,0.2)',
title_font=dict(size=14, color='#2c3e50'),
tickfont=dict(size=11),
hoverformat='.6fs' # Format time with seconds unit (e.g., 0.004000s)
),
yaxis=dict(
showgrid=True,
gridwidth=1,
gridcolor='rgba(128,128,128,0.2)',
title_font=dict(size=14, color='#2c3e50'),
tickfont=dict(size=11),
range=ev_range
),
legend=dict(
title=dict(text='Camera Model', font=dict(size=13, color='#2c3e50')),
font=dict(size=11),
bgcolor='rgba(255,255,255,0.9)',
bordercolor='rgba(128,128,128,0.3)',
borderwidth=1,
x=1.02,
y=1,
xanchor='left',
yanchor='top'
),
plot_bgcolor='white',
paper_bgcolor='white',
margin=dict(l=80, r=200, t=100, b=80)
)
return fig