Release 1.1.3: reveal faint nebula structure with human-readable preview modes
All checks were successful
Release AstroFrame / packages (push) Successful in 1m6s
All checks were successful
Release AstroFrame / packages (push) Successful in 1m6s
This commit is contained in:
parent
5ad7a6a79e
commit
d3362c8341
15 changed files with 300 additions and 24 deletions
|
|
@ -1,6 +1,6 @@
|
||||||
<Project>
|
<Project>
|
||||||
<PropertyGroup>
|
<PropertyGroup>
|
||||||
<Version>1.1.2</Version>
|
<Version>1.1.3</Version>
|
||||||
<Authors>Elijah Kuntz</Authors>
|
<Authors>Elijah Kuntz</Authors>
|
||||||
<Product>AstroFrame</Product>
|
<Product>AstroFrame</Product>
|
||||||
</PropertyGroup>
|
</PropertyGroup>
|
||||||
|
|
|
||||||
|
|
@ -22,7 +22,7 @@ To analyze another dataset, choose **Analyze lights**, select the folder contain
|
||||||
- Select a quality measurement and click the graph to inspect an exposure. One graph shows the selected metric, including stellar flux when selected. Capture order uses UTC timestamps; gaps between sessions are marked rather than drawn to elapsed-time scale.
|
- Select a quality measurement and click the graph to inspect an exposure. One graph shows the selected metric, including stellar flux when selected. Capture order uses UTC timestamps; gaps between sessions are marked rather than drawn to elapsed-time scale.
|
||||||
- Filter **REVIEW** or **REJECT**, and sort by concern, star count, stellar flux, or FWHM.
|
- Filter **REVIEW** or **REJECT**, and sort by concern, star count, stellar flux, or FWHM.
|
||||||
- Toggle **Compare nearby** and **Spatial overlay**. Red fill shows transient sky structure in the aligned reference grid. Region outlines show forced stellar flux loss. Previews have independent display stretches; use measured flux to compare transparency.
|
- Toggle **Compare nearby** and **Spatial overlay**. Red fill shows transient sky structure in the aligned reference grid. Region outlines show forced stellar flux loss. Previews have independent display stretches; use measured flux to compare transparency.
|
||||||
- Use **Frame view** for an area-averaged exposure preview, or **Nebula view** for additional averaging of faint diffuse structure. Adjust **Stretch** to brighten the display. These controls never affect measurements, classifications or original files.
|
- Use **Frame view** for an area-averaged exposure preview. **Nebula view** suppresses small stars and noise, then stretches faint structure without reducing the preview dimensions. **Asinh view** offers a different stretch with softer highlights. **Color nebula** uses the FITS Bayer channels, neutralizes the sky and smooths uncertain color; monochrome files fall back to grayscale. Adjust **Preview stretch** to brighten any view. These controls never affect measurements, classifications or original files. Single exposures can still be noisy, and the color is a viewing aid rather than calibrated astrophotography.
|
||||||
- Scroll the mouse wheel over either preview to zoom around the cursor, and hold the left mouse button to drag. Zoom and image position persist across frames and are shared with the nearby comparison. **Reset view** restores the fitted, centered image. These display controls do not alter source pixels or analysis.
|
- Scroll the mouse wheel over either preview to zoom around the cursor, and hold the left mouse button to drag. Zoom and image position persist across frames and are shared with the nearby comparison. **Reset view** restores the fitted, centered image. These display controls do not alter source pixels or analysis.
|
||||||
- Press **1**, **2**, **3** for KEEP, REVIEW, REJECT. Decisions save and advance. **J/K** navigates. **Reset** restores the automatic decision. **Ctrl+Z** undoes a manual decision.
|
- Press **1**, **2**, **3** for KEEP, REVIEW, REJECT. Decisions save and advance. **J/K** navigates. **Reset** restores the automatic decision. **Ctrl+Z** undoes a manual decision.
|
||||||
- Decision evidence and measurements remain visible below the quality graph. Hover over an evidence line to read its full technical detail, and scroll the panel for additional measurements. Preview stretch and manual decisions sit below the image. Existing notes remain in saved projects and exports; the note editor has been removed. Automatic decisions and human overrides remain separate.
|
- Decision evidence and measurements remain visible below the quality graph. Hover over an evidence line to read its full technical detail, and scroll the panel for additional measurements. Preview stretch and manual decisions sit below the image. Existing notes remain in saved projects and exports; the note editor has been removed. Automatic decisions and human overrides remain separate.
|
||||||
|
|
|
||||||
|
|
@ -57,7 +57,11 @@ Version 1.1.0 selects up to 16 workers from CPU capacity, leaving two logical pr
|
||||||
|
|
||||||
Small JSON metadata stores decisions, notes, evidence and compact masks. Binary versioned caches hold stars, sky maps and forced photometry, validated against source size and modification time and reference identity. A new engine version invalidates analysis without losing human labels. Repeated analysis uses cached measurements and forced apertures when valid. Project writes replace a temporary file atomically. Cancellation leaves analysis incomplete and export disabled.
|
Small JSON metadata stores decisions, notes, evidence and compact masks. Binary versioned caches hold stars, sky maps and forced photometry, validated against source size and modification time and reference identity. A new engine version invalidates analysis without losing human labels. Repeated analysis uses cached measurements and forced apertures when valid. Project writes replace a temporary file atomically. Cancellation leaves analysis incomplete and export disabled.
|
||||||
|
|
||||||
Display caches have a separate version. They contain compressed, linear, area-averaged thumbnails rather than a permanently stretched byte image. The screen transfer uses a noise-aware black point and adjustable median brightness; **Nebula view** averages neighboring display samples further. This avoids nearest-pixel aliasing and the original excessively bright, noisy stretch. Prepared display statistics are cached in the viewer so slider changes remain responsive. Disk loading and first-time thumbnail creation run off the UI thread, with cancellation and a single preview-loading gate preventing queued FITS reads during rapid navigation. Old projects regenerate only requested displays on demand.
|
Display caches have a separate version. They contain compressed, linear, area-averaged thumbnails rather than a permanently stretched byte image. **Frame view** retains its noise-aware black point and adjustable median brightness. **Nebula view** applies a 3×3 median and four separable binomial smoothing passes at the existing thumbnail dimensions, suppressing small stars and noise while retaining faint filaments. Its black point also includes the lower background percentile, and its median is displayed slightly brighter. **Asinh view** applies an adjustable inverse-hyperbolic-sine transfer to this same smoothed plane, with a brightness-adjusted gamma fallback when its normalized median already exceeds the requested brightness.
|
||||||
|
|
||||||
|
**Color nebula** reads recognized RGGB, GRBG, GBRG or BGGR Bayer layouts and their offsets through a separate streaming display reader. It bins linear RGB superpixels, uses the same diffuse luminance preview, neutralizes each channel's median sky, smooths chroma and suppresses departures consistent with noise. A linked channel scale limits saturation and preserves neutral black and white highlights. Color is approximate and uncalibrated; no color is invented for monochrome or unknown Bayer layouts, which show the grayscale nebula preview with an explanatory label. Color has a separate fingerprinted linear cache generated only on demand. Neither display reader changes the monochrome analysis path, classifications, or original FITS files.
|
||||||
|
|
||||||
|
Prepared display statistics are cached in the viewer so slider changes remain responsive. Disk loading and first-time thumbnail creation run off the UI thread, with cancellation and a single preview-loading gate preventing queued FITS reads during rapid navigation. Both comparison panes use the selected mode and shared zoom/pan. Old projects regenerate only requested displays on demand. Single-frame previews cannot recover signal absent from the exposure and can remain noisy; these are human-readable viewing aids, not stacked images.
|
||||||
|
|
||||||
The preview is not an input to classification. Source-star inspection reads two originals, maps identical stars through their stored alignment, and displays enlarged source superpixels without interpolation. Crops are independently normalized to judge morphology. See [Siril's screen-transfer discussion](https://siril.readthedocs.io/en/latest/processing/stretching.html) for the distinction between display stretching and linear image data.
|
The preview is not an input to classification. Source-star inspection reads two originals, maps identical stars through their stored alignment, and displays enlarged source superpixels without interpolation. Crops are independently normalized to judge morphology. See [Siril's screen-transfer discussion](https://siril.readthedocs.io/en/latest/processing/stretching.html) for the distinction between display stretching and linear image data.
|
||||||
|
|
||||||
|
|
|
||||||
10
docs/release-notes/1.1.3.md
Normal file
10
docs/release-notes/1.1.3.md
Normal file
|
|
@ -0,0 +1,10 @@
|
||||||
|
# AstroFrame 1.1.3
|
||||||
|
|
||||||
|
- Rework **Nebula view** to reveal faint diffuse structure and thin filaments. Suppress small stars and noise at the existing preview resolution, then apply a background-aware stretch. NGC 6960's Veil filaments are now visible in the tested single exposures.
|
||||||
|
- Add **Asinh view**, an alternative adjustable stretch with softer highlights.
|
||||||
|
- Add **Color nebula** from recognized FITS Bayer channels. Neutralize the sky, smooth uncertain color and preserve neutral bright highlights. Monochrome and unknown Bayer layouts display the grayscale nebula preview instead of fabricated color.
|
||||||
|
- Apply every viewing mode to both comparison panes while preserving shared zoom and pan. Linear color previews are cached on demand without invalidating quality measurements.
|
||||||
|
|
||||||
|
These are display-only changes. Original FITS files, analysis, classifications and manual decisions are unaffected. Single exposures can remain noisy; color is a viewing aid rather than calibrated astrophotography.
|
||||||
|
|
||||||
|
Validation: 135 engine, 23 updater, 10 mocked publisher and 63 isolated Windows interaction checks, with rendering at 96 and 144 DPI. Covers faint-filament visibility, stretch brightness, Bayer patterns and offsets, color/cache integrity, monochrome fallback, rapid navigation, cancellation and source-file preservation. Visually inspected 18 real exposures across NGC 6960, NGC 7000, IC 1805, NGC 281, M33 and NGC 1432. Verification uses copied workspace caches and leaves the installed application untouched. The server workflow builds Windows and Linux packages and checks the packaged Linux settings page.
|
||||||
|
|
@ -127,7 +127,7 @@ For preview and processing-status changes, build the source and run the isolated
|
||||||
./tools/Verify-Preview.ps1 -FixtureProject 'path/to/saved-project' -Output artifacts/preview-verification
|
./tools/Verify-Preview.ps1 -FixtureProject 'path/to/saved-project' -Output artifacts/preview-verification
|
||||||
```
|
```
|
||||||
|
|
||||||
This checks comparison overlays, zoom/pan, processing-memory visibility, elongation crops and guide toggling, absent comparisons, loading cancellation, and native window controls. It renders normal and minimum-size controls at 96 and 144 DPI. Inspect the PNG files in the output's `qa` directory. It launches only the source build in diagnostic mode, which bypasses installed settings and updates.
|
This checks comparison overlays, zoom/pan, all four preview modes in both panes, Bayer color loading across frame changes, monochrome fallback, processing-memory visibility, elongation crops and guide toggling, absent comparisons, loading cancellation, and native window controls. It renders normal and minimum-size controls at 96 and 144 DPI. Inspect the PNG files in the output's `qa` directory. It launches only the source build in diagnostic mode, which bypasses installed settings and updates. Source `--capture` diagnostics accept `--preview=0` (Frame), `1` (Nebula), `2` (Asinh) or `3` (Color nebula) for real-exposure visual checks against copied workspace projects.
|
||||||
|
|
||||||
`./tools/Verify-ReleaseAutomation.ps1` exercises version/tag mismatch, upload failure, draft resumption, conflicting assets, immutable published releases and package integrity with a mocked release API. It never publishes a real release.
|
`./tools/Verify-ReleaseAutomation.ps1` exercises version/tag mismatch, upload failure, draft resumption, conflicting assets, immutable published releases and package integrity with a mocked release API. It never publishes a real release.
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -54,6 +54,23 @@ public sealed partial class MainWindow
|
||||||
spatial.IsChecked=true;compare.IsChecked=false;compare.IsChecked=true;Select(visible[0]);await WaitForPreviews();await Task.Delay(150);
|
spatial.IsChecked=true;compare.IsChecked=false;compare.IsChecked=true;Select(visible[0]);await WaitForPreviews();await Task.Delay(150);
|
||||||
Check(preview.Spatial&&comparison.Spatial&&comparison.HasImage,"Overlay persists on both panes after toggling comparison and changing frame");
|
Check(preview.Spatial&&comparison.Spatial&&comparison.HasImage,"Overlay persists on both panes after toggling comparison and changing frame");
|
||||||
Capture("comparison-fit",144);
|
Capture("comparison-fit",144);
|
||||||
|
double retainedZoom=viewport.Zoom;var retainedPan=viewport.Pan;previewMode.SelectedIndex=2;
|
||||||
|
Check(preview.Mode==AstroFrame.Engine.PreviewMode.Asinh&&comparison.Mode==preview.Mode&&viewport.Zoom==retainedZoom&&viewport.Pan==retainedPan,"Asinh view switches both panes without changing zoom or pan");Capture("asinh-comparison",144);
|
||||||
|
previewMode.SelectedIndex=3;await WaitForPreviews();await Task.Delay(100);
|
||||||
|
Check(preview.Mode==AstroFrame.Engine.PreviewMode.Color&&comparison.Mode==preview.Mode&&preview.HasColor&&comparison.HasColor,"Color nebula loads real Bayer RGB for both comparison frames");Capture("color-comparison",144);
|
||||||
|
Select(visible[1]);await WaitForPreviews();Check(preview.HasColor&&comparison.HasColor&&preview.Mode==AstroFrame.Engine.PreviewMode.Color,"color mode survives exposure changes and cached previews");
|
||||||
|
foreach(var frame in visible.Take(6))Select(frame);previewMode.SelectedIndex=2;previewMode.SelectedIndex=3;await WaitForPreviews();
|
||||||
|
Check(preview.HasColor&&comparison.HasColor&&preview.Frame==selected&&preview.Mode==AstroFrame.Engine.PreviewMode.Color,"rapid exposure and mode changes cancel stale color requests and retain the latest preview");
|
||||||
|
Select(visible[1]);await WaitForPreviews();
|
||||||
|
previewMode.SelectedIndex=0;Check(preview.Mode==AstroFrame.Engine.PreviewMode.Frame&&comparison.Mode==preview.Mode,"Frame view restores both original grayscale previews");previewMode.SelectedIndex=1;
|
||||||
|
string monoPath=System.IO.Path.Combine(output,"mono-source.fit");var monoBytes=File.ReadAllBytes(selected!.Path);
|
||||||
|
using(var sourceStream=File.OpenRead(selected.Path))
|
||||||
|
{
|
||||||
|
var(_,headerBytes)=AstroFrame.Engine.Fits.ReadHeader(sourceStream);
|
||||||
|
for(int offset=0;offset<headerBytes;offset+=80)if(System.Text.Encoding.ASCII.GetString(monoBytes,offset,8)=="BAYERPAT")System.Text.Encoding.ASCII.GetBytes("COMMENT ").CopyTo(monoBytes,offset);
|
||||||
|
}
|
||||||
|
File.WriteAllBytes(monoPath,monoBytes);var monoFrame=AstroFrame.Engine.Fits.Inspect(monoPath);var monoView=new ExposureView();monoView.SetMode(AstroFrame.Engine.PreviewMode.Color);monoView.Load(output,monoFrame);await monoView.Loading;
|
||||||
|
Check(monoView.HasImage&&!monoView.HasColor&&monoView.Mode==AstroFrame.Engine.PreviewMode.Color,"color mode falls back to readable grayscale for a monochrome FITS source");monoView.Dispose();
|
||||||
Busy(true);progress.Value=57;status.Text="Analyzing lights · 57 / 100 · "+selected!.Name;await Task.Delay(1100);
|
Busy(true);progress.Value=57;status.Text="Analyzing lights · 57 / 100 · "+selected!.Name;await Task.Delay(1100);
|
||||||
Check(memoryUsage.IsVisible&&memoryTimer.IsEnabled&&memoryUsage.Text!.StartsWith("Memory: ")&&memoryUsage.Text.EndsWith(" MB"),"processing shows a live process memory statistic");
|
Check(memoryUsage.IsVisible&&memoryTimer.IsEnabled&&memoryUsage.Text!.StartsWith("Memory: ")&&memoryUsage.Text.EndsWith(" MB"),"processing shows a live process memory statistic");
|
||||||
Check(!inspectElongation.IsEnabled,"star inspection is disabled during processing");
|
Check(!inspectElongation.IsEnabled,"star inspection is disabled during processing");
|
||||||
|
|
|
||||||
|
|
@ -30,7 +30,7 @@ public sealed partial class MainWindow:Window
|
||||||
readonly DispatcherTimer memoryTimer=new(){Interval=TimeSpan.FromSeconds(1)};
|
readonly DispatcherTimer memoryTimer=new(){Interval=TimeSpan.FromSeconds(1)};
|
||||||
StarInspector? starInspector;
|
StarInspector? starInspector;
|
||||||
readonly Border previewPanel,comparisonBorder,previewControls;
|
readonly Border previewPanel,comparisonBorder,previewControls;
|
||||||
readonly ComboBox previewMode=new(){ItemsSource=new[]{"Frame view","Nebula view"},SelectedIndex=0,MinWidth=150};
|
readonly ComboBox previewMode=new(){ItemsSource=new[]{"Frame view","Nebula view","Asinh view","Color nebula"},SelectedIndex=0,MinWidth=150};
|
||||||
readonly Slider displayStretch=new(){Minimum=.08,Maximum=.40,Value=.18};
|
readonly Slider displayStretch=new(){Minimum=.08,Maximum=.40,Value=.18};
|
||||||
readonly StackPanel inspector=new(){Spacing=9};
|
readonly StackPanel inspector=new(){Spacing=9};
|
||||||
readonly Grid previewWorkspace=new(){ColumnDefinitions=new("*,0"),Margin=new(0,8,0,6)};
|
readonly Grid previewWorkspace=new(){ColumnDefinitions=new("*,0"),Margin=new(0,8,0,6)};
|
||||||
|
|
@ -58,7 +58,8 @@ public sealed partial class MainWindow:Window
|
||||||
var resetStretch=Button("Reset");resetStretch.Padding=new(9,5);resetStretch.FontSize=11;resetStretch.VerticalAlignment=VerticalAlignment.Center;resetStretch.Click+=(_,_)=>displayStretch.Value=.18;Grid.SetColumn(resetStretch,1);stretchRow.Children.Add(resetStretch);Grid.SetRow(stretchRow,1);displayPanel.Children.Add(stretchRow);previewControls=new(){Child=displayPanel};
|
var resetStretch=Button("Reset");resetStretch.Padding=new(9,5);resetStretch.FontSize=11;resetStretch.VerticalAlignment=VerticalAlignment.Center;resetStretch.Click+=(_,_)=>displayStretch.Value=.18;Grid.SetColumn(resetStretch,1);stretchRow.Children.Add(resetStretch);Grid.SetRow(stretchRow,1);displayPanel.Children.Add(stretchRow);previewControls=new(){Child=displayPanel};
|
||||||
// Keep the native slider's input behavior; give its thumb a visible silver face and room for the full circle.
|
// Keep the native slider's input behavior; give its thumb a visible silver face and room for the full circle.
|
||||||
Styles.Add(new Style(x=>x.OfType<Slider>().Template().OfType<Avalonia.Controls.Primitives.Thumb>()){Setters={new Setter(Avalonia.Controls.Primitives.TemplatedControl.TemplateProperty,new FuncControlTemplate<Avalonia.Controls.Primitives.Thumb>((_,_)=>new Border{Width=20,Height=20,CornerRadius=new(10),Background=Palette.Accent,BorderBrush=Palette.Panel,BorderThickness=new(3),HorizontalAlignment=HorizontalAlignment.Center,VerticalAlignment=VerticalAlignment.Center}))}});
|
Styles.Add(new Style(x=>x.OfType<Slider>().Template().OfType<Avalonia.Controls.Primitives.Thumb>()){Setters={new Setter(Avalonia.Controls.Primitives.TemplatedControl.TemplateProperty,new FuncControlTemplate<Avalonia.Controls.Primitives.Thumb>((_,_)=>new Border{Width=20,Height=20,CornerRadius=new(10),Background=Palette.Accent,BorderBrush=Palette.Panel,BorderThickness=new(3),HorizontalAlignment=HorizontalAlignment.Center,VerticalAlignment=VerticalAlignment.Center}))}});
|
||||||
previewMode.SelectionChanged+=(_,_)=>{preview.Nebula=comparison.Nebula=previewMode.SelectedIndex==1;preview.RefreshDisplay();comparison.RefreshDisplay();};
|
previewMode.SelectionChanged+=(_,_)=>{preview.SetMode((PreviewMode)Math.Max(0,previewMode.SelectedIndex));comparison.SetMode((PreviewMode)Math.Max(0,previewMode.SelectedIndex));};
|
||||||
|
ToolTip.SetTip(previewMode,"Frame: original grayscale stretch. Nebula: smooth faint detail with less star dominance. Asinh: an alternative smooth stretch. Color: sky-neutralized Bayer RGB when available. Display options do not change analysis.");
|
||||||
displayStretch.PropertyChanged+=(_,e)=>{if(e.Property==Slider.ValueProperty){stretchValue.Text=displayStretch.Value.ToString("0.00");preview.Stretch=comparison.Stretch=displayStretch.Value;preview.RefreshDisplay();comparison.RefreshDisplay();}};
|
displayStretch.PropertyChanged+=(_,e)=>{if(e.Property==Slider.ValueProperty){stretchValue.Text=displayStretch.Value.ToString("0.00");preview.Stretch=comparison.Stretch=displayStretch.Value;preview.RefreshDisplay();comparison.RefreshDisplay();}};
|
||||||
Title="AstroFrame";Width=1450;Height=940;MinWidth=1120;MinHeight=740;Background=Palette.Background;FontFamily="Inter";FontSize=13;
|
Title="AstroFrame";Width=1450;Height=940;MinWidth=1120;MinHeight=740;Background=Palette.Background;FontFamily="Inter";FontSize=13;
|
||||||
ExtendClientAreaToDecorationsHint=true;ExtendClientAreaChromeHints=Avalonia.Platform.ExtendClientAreaChromeHints.PreferSystemChrome;ExtendClientAreaTitleBarHeightHint=36;
|
ExtendClientAreaToDecorationsHint=true;ExtendClientAreaChromeHints=Avalonia.Platform.ExtendClientAreaChromeHints.PreferSystemChrome;ExtendClientAreaTitleBarHeightHint=36;
|
||||||
|
|
@ -179,6 +180,8 @@ public sealed partial class MainWindow:Window
|
||||||
int index=Array.FindIndex(QualityChart.Metrics,m=>m.Name==name);
|
int index=Array.FindIndex(QualityChart.Metrics,m=>m.Name==name);
|
||||||
if(index<0)throw new ArgumentException("Unknown quality metric",nameof(name));metric.SelectedIndex=index;
|
if(index<0)throw new ArgumentException("Unknown quality metric",nameof(name));metric.SelectedIndex=index;
|
||||||
}
|
}
|
||||||
|
public void CapturePreviewMode(int mode)
|
||||||
|
{if(mode<0||mode>3)throw new ArgumentOutOfRangeException(nameof(mode));previewMode.SelectedIndex=mode;}
|
||||||
public async Task SmokeTest(string report)
|
public async Task SmokeTest(string report)
|
||||||
{
|
{
|
||||||
if(project==null)throw new InvalidOperationException("Project not loaded");
|
if(project==null)throw new InvalidOperationException("Project not loaded");
|
||||||
|
|
|
||||||
|
|
@ -82,6 +82,7 @@ public sealed class App:Application
|
||||||
else if(Program.Arguments[3]!="all")window.CaptureSelection(Program.Arguments[3]=="reject");
|
else if(Program.Arguments[3]!="all")window.CaptureSelection(Program.Arguments[3]=="reject");
|
||||||
}
|
}
|
||||||
string? metricOption=Program.Arguments.FirstOrDefault(a=>a.StartsWith("--metric="));if(metricOption!=null)window.CaptureMetric(metricOption[9..]);
|
string? metricOption=Program.Arguments.FirstOrDefault(a=>a.StartsWith("--metric="));if(metricOption!=null)window.CaptureMetric(metricOption[9..]);
|
||||||
|
string? previewOption=Program.Arguments.FirstOrDefault(a=>a.StartsWith("--preview="));if(previewOption!=null)window.CapturePreviewMode(int.Parse(previewOption[10..],System.Globalization.CultureInfo.InvariantCulture));
|
||||||
if(Program.Arguments.Length>4&&double.TryParse(Program.Arguments[4],System.Globalization.NumberStyles.Float,System.Globalization.CultureInfo.InvariantCulture,out double width)){window.Width=width;window.Height=740;}
|
if(Program.Arguments.Length>4&&double.TryParse(Program.Arguments[4],System.Globalization.NumberStyles.Float,System.Globalization.CultureInfo.InvariantCulture,out double width)){window.Width=width;window.Height=740;}
|
||||||
await window.WaitForPreviews();await Task.Delay(400);
|
await window.WaitForPreviews();await Task.Delay(400);
|
||||||
if(window.Content is Control content)
|
if(window.Content is Control content)
|
||||||
|
|
|
||||||
|
|
@ -75,6 +75,9 @@ public sealed class ExposureView:Control,IDisposable
|
||||||
static readonly SemaphoreSlim LoadGate=new(1);
|
static readonly SemaphoreSlim LoadGate=new(1);
|
||||||
WriteableBitmap? bitmap;
|
WriteableBitmap? bitmap;
|
||||||
PreviewDisplay? frameDisplay,nebulaDisplay;
|
PreviewDisplay? frameDisplay,nebulaDisplay;
|
||||||
|
ColorPreviewDisplay? colorDisplay;
|
||||||
|
bool colorAttempted;
|
||||||
|
string directory="";
|
||||||
byte[] overlayMask=[];
|
byte[] overlayMask=[];
|
||||||
CancellationTokenSource? request;
|
CancellationTokenSource? request;
|
||||||
string message="Select an exposure";
|
string message="Select an exposure";
|
||||||
|
|
@ -82,12 +85,15 @@ public sealed class ExposureView:Control,IDisposable
|
||||||
public bool HasImage=>bitmap!=null;
|
public bool HasImage=>bitmap!=null;
|
||||||
public Frame? Frame {get;private set;}
|
public Frame? Frame {get;private set;}
|
||||||
public bool Spatial {get;set;}
|
public bool Spatial {get;set;}
|
||||||
public bool Nebula {get;set;}
|
public PreviewMode Mode {get;private set;}
|
||||||
|
public bool Nebula {get=>Mode==PreviewMode.Nebula;set=>SetMode(value?PreviewMode.Nebula:PreviewMode.Frame);}
|
||||||
|
public bool HasColor=>colorDisplay!=null;
|
||||||
public double Stretch {get;set;}=.18;
|
public double Stretch {get;set;}=.18;
|
||||||
public string Caption {get;set;}="";
|
public string Caption {get;set;}="";
|
||||||
public PreviewViewport Viewport {get;}
|
public PreviewViewport Viewport {get;}
|
||||||
Point? dragStart;IPointer? dragPointer;
|
Point? dragStart;IPointer? dragPointer;
|
||||||
Rect ImageArea=>new(0,(Caption!=""?26:0)+(Spatial?22:0),Math.Max(1,Bounds.Width),Math.Max(1,Bounds.Height-(Caption!=""?26:0)-(Spatial?22:0)));
|
string ModeNote=>Mode switch{PreviewMode.Nebula=>"Faint detail · smoothed",PreviewMode.Asinh=>"Asinh · smoothed",PreviewMode.Color=>colorDisplay!=null?"Color · neutral sky":colorAttempted?"Color unavailable · grayscale":"Loading color…",_=>""};
|
||||||
|
Rect ImageArea=>new(0,(Caption!=""?26:0)+(Spatial?22:0)+(ModeNote!=""?20:0),Math.Max(1,Bounds.Width),Math.Max(1,Bounds.Height-(Caption!=""?26:0)-(Spatial?22:0)-(ModeNote!=""?20:0)));
|
||||||
public ExposureView():this(new PreviewViewport()){}
|
public ExposureView():this(new PreviewViewport()){}
|
||||||
public ExposureView(PreviewViewport viewport)
|
public ExposureView(PreviewViewport viewport)
|
||||||
{
|
{
|
||||||
|
|
@ -103,7 +109,7 @@ public sealed class ExposureView:Control,IDisposable
|
||||||
void EndDrag(){dragStart=null;dragPointer?.Capture(null);dragPointer=null;Cursor=Cursor.Default;}
|
void EndDrag(){dragStart=null;dragPointer?.Capture(null);dragPointer=null;Cursor=Cursor.Default;}
|
||||||
public void Load(string projectDirectory,Frame? f,IReadOnlyList<Frame>? frames=null)
|
public void Load(string projectDirectory,Frame? f,IReadOnlyList<Frame>? frames=null)
|
||||||
{
|
{
|
||||||
Dispose();Frame=f;message=f==null?"Select an exposure":"Loading preview…";InvalidateVisual();
|
Dispose();directory=projectDirectory;Frame=f;message=f==null?"Select an exposure":"Loading preview…";InvalidateVisual();
|
||||||
if(f==null){Loading=Task.CompletedTask;return;}
|
if(f==null){Loading=Task.CompletedTask;return;}
|
||||||
request=new();Loading=LoadCore(projectDirectory,f,frames??[],request.Token);
|
request=new();Loading=LoadCore(projectDirectory,f,frames??[],request.Token);
|
||||||
}
|
}
|
||||||
|
|
@ -125,21 +131,57 @@ public sealed class ExposureView:Control,IDisposable
|
||||||
using var memory=await ResourcePolicy.Acquire(ResourcePolicy.EstimateFrameBytes(f.Width,f.Height,f.Bayer!=""?2:1),token);
|
using var memory=await ResourcePolicy.Acquire(ResourcePolicy.EstimateFrameBytes(f.Width,f.Height,f.Bayer!=""?2:1),token);
|
||||||
var image=Fits.Read(f.Path,token);token.ThrowIfCancellationRequested();Fits.Preview(image,path,f);plane=PreviewRenderer.Read(path,f);
|
var image=Fits.Read(f.Path,token);token.ThrowIfCancellationRequested();Fits.Preview(image,path,f);plane=PreviewRenderer.Read(path,f);
|
||||||
}
|
}
|
||||||
token.ThrowIfCancellationRequested();return(PreviewRenderer.Prepare(plane),PreviewRenderer.Prepare(plane,true),SkyOverlay.LoadMask(directory,f,frames,token));
|
token.ThrowIfCancellationRequested();return(PreviewRenderer.Prepare(plane,false,token),PreviewRenderer.Prepare(plane,true,token),SkyOverlay.LoadMask(directory,f,frames,token));
|
||||||
},token);
|
},token);
|
||||||
}
|
}
|
||||||
finally{LoadGate.Release();}
|
finally{LoadGate.Release();}
|
||||||
token.ThrowIfCancellationRequested();frameDisplay=prepared.Frame;nebulaDisplay=prepared.Nebula;overlayMask=prepared.Overlay;RefreshDisplay();
|
token.ThrowIfCancellationRequested();frameDisplay=prepared.Frame;nebulaDisplay=prepared.Nebula;overlayMask=prepared.Overlay;RefreshDisplay();
|
||||||
|
if(Mode==PreviewMode.Color)await LoadColor(directory,f,token);
|
||||||
}
|
}
|
||||||
catch(OperationCanceledException){}
|
catch(OperationCanceledException){}
|
||||||
catch(Exception e){if(!token.IsCancellationRequested){message="Preview unavailable: "+e.Message;InvalidateVisual();}}
|
catch(Exception e){if(!token.IsCancellationRequested){message="Preview unavailable: "+e.Message;InvalidateVisual();}}
|
||||||
}
|
}
|
||||||
|
public void SetMode(PreviewMode mode)
|
||||||
|
{
|
||||||
|
Mode=mode;RefreshDisplay();InvalidateVisual();
|
||||||
|
if(mode==PreviewMode.Color&&!colorAttempted&&Frame is {} frame&&request is {} active)
|
||||||
|
{var previous=Loading;Loading=LoadColorAfter(previous,directory,frame,active.Token);}
|
||||||
|
}
|
||||||
|
async Task LoadColorAfter(Task previous,string projectDirectory,Frame frame,CancellationToken token)
|
||||||
|
{await previous;if(!token.IsCancellationRequested)await LoadColor(projectDirectory,frame,token);}
|
||||||
|
async Task LoadColor(string projectDirectory,Frame frame,CancellationToken token)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
await LoadGate.WaitAsync(token);
|
||||||
|
try
|
||||||
|
{
|
||||||
|
if(colorAttempted)return;
|
||||||
|
var prepared=await Task.Run(async()=>
|
||||||
|
{
|
||||||
|
var info=new FileInfo(frame.Path);if(!info.Exists||info.Length!=frame.Length||info.LastWriteTimeUtc.Ticks!=frame.Modified)throw new IOException("Source changed; reanalyze before inspecting");
|
||||||
|
string path=ColorPreview.PathFor(projectDirectory,frame);ColorPreviewPlane? color=null;
|
||||||
|
try{if(File.Exists(path))color=ColorPreview.Read(path,frame);}catch(IOException){}
|
||||||
|
if(color==null)
|
||||||
|
{
|
||||||
|
using var memory=await ResourcePolicy.Acquire(ResourcePolicy.EstimateFrameBytes(frame.Width,frame.Height,2),token);
|
||||||
|
color=ColorPreview.ReadFits(frame.Path,token);token.ThrowIfCancellationRequested();if(color!=null)ColorPreview.Write(color,path,frame);
|
||||||
|
}
|
||||||
|
return color==null?null:ColorPreview.Prepare(color,token);
|
||||||
|
},token);
|
||||||
|
token.ThrowIfCancellationRequested();colorDisplay=prepared;colorAttempted=true;RefreshDisplay();InvalidateVisual();
|
||||||
|
}
|
||||||
|
finally{LoadGate.Release();}
|
||||||
|
}
|
||||||
|
catch(OperationCanceledException){}
|
||||||
|
catch(Exception){if(!token.IsCancellationRequested){colorAttempted=true;RefreshDisplay();InvalidateVisual();}}
|
||||||
|
}
|
||||||
public void RefreshDisplay()
|
public void RefreshDisplay()
|
||||||
{
|
{
|
||||||
var display=Nebula?nebulaDisplay:frameDisplay;if(display==null)return;
|
var display=Mode==PreviewMode.Frame?frameDisplay:nebulaDisplay;if(display==null)return;
|
||||||
byte[] pixels=PreviewRenderer.Render(display,Stretch);int w=display.Plane.Width,h=display.Plane.Height;bitmap?.Dispose();
|
bool color=Mode==PreviewMode.Color&&colorDisplay!=null;byte[] pixels=color?ColorPreview.Render(colorDisplay!,Stretch):PreviewRenderer.Render(display,Stretch,Mode==PreviewMode.Asinh);int w=color?colorDisplay!.Luminance.Plane.Width:display.Plane.Width,h=color?colorDisplay!.Luminance.Plane.Height:display.Plane.Height;bitmap?.Dispose();
|
||||||
bitmap=new WriteableBitmap(new PixelSize(w,h),new Vector(96,96),PixelFormat.Bgra8888,AlphaFormat.Opaque);
|
bitmap=new WriteableBitmap(new PixelSize(w,h),new Vector(96,96),PixelFormat.Bgra8888,AlphaFormat.Opaque);
|
||||||
using var locked=bitmap.Lock();byte[] row=new byte[w*4];for(int y=0;y<h;y++){for(int x=0;x<w;x++){byte v=pixels[y*w+x];row[x*4]=v;row[x*4+1]=v;row[x*4+2]=v;row[x*4+3]=255;}Marshal.Copy(row,0,locked.Address+y*locked.RowBytes,row.Length);}InvalidateVisual();
|
using var locked=bitmap.Lock();byte[] row=new byte[w*4];for(int y=0;y<h;y++){if(color)Array.Copy(pixels,y*w*4,row,0,row.Length);else for(int x=0;x<w;x++){byte v=pixels[y*w+x];row[x*4]=v;row[x*4+1]=v;row[x*4+2]=v;row[x*4+3]=255;}Marshal.Copy(row,0,locked.Address+y*locked.RowBytes,row.Length);}InvalidateVisual();
|
||||||
}
|
}
|
||||||
public override void Render(DrawingContext c)
|
public override void Render(DrawingContext c)
|
||||||
{
|
{
|
||||||
|
|
@ -148,6 +190,7 @@ public sealed class ExposureView:Control,IDisposable
|
||||||
double captionHeight=Caption!=""?26:0,header=captionHeight+(Spatial?22:0);
|
double captionHeight=Caption!=""?26:0,header=captionHeight+(Spatial?22:0);
|
||||||
if(captionHeight>0)c.DrawText(new FormattedText(Caption+" · "+Frame?.Time,System.Globalization.CultureInfo.CurrentCulture,FlowDirection.LeftToRight,new Typeface("Inter"),10,Palette.Muted),new(8,7));
|
if(captionHeight>0)c.DrawText(new FormattedText(Caption+" · "+Frame?.Time,System.Globalization.CultureInfo.CurrentCulture,FlowDirection.LeftToRight,new Typeface("Inter"),10,Palette.Muted),new(8,7));
|
||||||
if(Spatial)c.DrawText(new FormattedText(overlayMask.Length==SkyModel.Count?"Pink: excess sky · Grid: stellar flux":"Sky overlay unavailable · cached reference required",System.Globalization.CultureInfo.CurrentCulture,FlowDirection.LeftToRight,new Typeface("Inter"),10,Palette.Muted){MaxTextWidth=Math.Max(1,Bounds.Width-16)},new(8,captionHeight+5));
|
if(Spatial)c.DrawText(new FormattedText(overlayMask.Length==SkyModel.Count?"Pink: excess sky · Grid: stellar flux":"Sky overlay unavailable · cached reference required",System.Globalization.CultureInfo.CurrentCulture,FlowDirection.LeftToRight,new Typeface("Inter"),10,Palette.Muted){MaxTextWidth=Math.Max(1,Bounds.Width-16)},new(8,captionHeight+5));
|
||||||
|
if(ModeNote!="")c.DrawText(new FormattedText(ModeNote,System.Globalization.CultureInfo.CurrentCulture,FlowDirection.LeftToRight,new Typeface("Inter"),10,Palette.Muted){MaxTextWidth=Math.Max(1,Bounds.Width-16)},new(8,header+4));
|
||||||
using var imageClip=c.PushClip(ImageArea);
|
using var imageClip=c.PushClip(ImageArea);
|
||||||
var rect=Viewport.ImageRect(ImageArea,bitmap.Size);double w=rect.Width,h=rect.Height;c.DrawImage(bitmap,new Rect(bitmap.Size),rect);
|
var rect=Viewport.ImageRect(ImageArea,bitmap.Size);double w=rect.Width,h=rect.Height;c.DrawImage(bitmap,new Rect(bitmap.Size),rect);
|
||||||
if(Spatial&&Frame!=null&&Frame.Alignment.Length==4)
|
if(Spatial&&Frame!=null&&Frame.Alignment.Length==4)
|
||||||
|
|
@ -169,5 +212,5 @@ public sealed class ExposureView:Control,IDisposable
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
public void Dispose(){EndDrag();request?.Cancel();request?.Dispose();request=null;bitmap?.Dispose();bitmap=null;frameDisplay=nebulaDisplay=null;overlayMask=[];}
|
public void Dispose(){EndDrag();request?.Cancel();request?.Dispose();request=null;bitmap?.Dispose();bitmap=null;frameDisplay=nebulaDisplay=null;colorDisplay=null;colorAttempted=false;overlayMask=[];}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
106
src/AstroFrame.Engine/ColorPreview.cs
Normal file
106
src/AstroFrame.Engine/ColorPreview.cs
Normal file
|
|
@ -0,0 +1,106 @@
|
||||||
|
using System.Buffers.Binary;
|
||||||
|
using System.Globalization;
|
||||||
|
using System.IO.Compression;
|
||||||
|
using System.Runtime.InteropServices;
|
||||||
|
|
||||||
|
namespace AstroFrame.Engine;
|
||||||
|
|
||||||
|
public sealed record ColorPreviewPlane(int Width,int Height,float[] Red,float[] Green,float[] Blue);
|
||||||
|
public sealed record ColorPreviewDisplay(PreviewDisplay Luminance,float[][] Chroma,double ChromaThreshold);
|
||||||
|
/// <summary>Display-only Bayer binning. Does not alter the monochrome analysis reader or caches.</summary>
|
||||||
|
public static class ColorPreview
|
||||||
|
{
|
||||||
|
const int Magic=0x41504331;
|
||||||
|
public static ColorPreviewPlane? ReadFits(string path,CancellationToken ct=default)
|
||||||
|
{
|
||||||
|
using var stream=File.OpenRead(path);var(header,_)=Fits.ReadHeader(stream);
|
||||||
|
double Number(string key,double fallback=0)=>header.TryGetValue(key,out var value)&&double.TryParse(value.Replace('D','E'),NumberStyles.Float,CultureInfo.InvariantCulture,out double number)?number:fallback;
|
||||||
|
string pattern=header.GetValueOrDefault("BAYERPAT","").Trim().ToUpperInvariant();
|
||||||
|
if(pattern is not ("RGGB" or "GRBG" or "GBRG" or "BGGR"))return null;
|
||||||
|
int w=(int)Number("NAXIS1"),h=(int)Number("NAXIS2"),bit=(int)Number("BITPIX");
|
||||||
|
if(Number("NAXIS")!=2||w<32||h<32||(long)w*h>100_000_000)throw new InvalidDataException("Unsupported color preview dimensions");
|
||||||
|
if(bit is not (8 or 16 or 32 or -32 or -64))throw new InvalidDataException("Unsupported FITS BITPIX");
|
||||||
|
int bytes=Math.Abs(bit)/8,uw=w/2,uh=h/2,step=Math.Max((uh+899)/900,(int)Math.Ceiling(Math.Sqrt((double)uw*uh/2_000_000))),ow=(uw+step-1)/step,oh=(uh+step-1)/step;
|
||||||
|
if(stream.Length-stream.Position<(long)w*h*bytes)throw new InvalidDataException("Truncated FITS pixels");
|
||||||
|
double zero=Number("BZERO"),factor=Number("BSCALE",1);int ox=((int)Number("XBAYROFF")%2+2)%2,oy=((int)Number("YBAYROFF")%2+2)%2;
|
||||||
|
double[][] sums=[new double[ow*oh],new double[ow*oh],new double[ow*oh]];byte[] rows=new byte[w*bytes*2];
|
||||||
|
for(int y=0;y<uh;y++)
|
||||||
|
{
|
||||||
|
ct.ThrowIfCancellationRequested();stream.ReadExactly(rows);
|
||||||
|
for(int x=0;x<uw;x++)for(int dy=0;dy<2;dy++)for(int dx=0;dx<2;dx++)
|
||||||
|
{
|
||||||
|
var span=rows.AsSpan((dy*w+x*2+dx)*bytes,bytes);
|
||||||
|
double raw=bit switch{8=>span[0],16=>BinaryPrimitives.ReadInt16BigEndian(span),32=>BinaryPrimitives.ReadInt32BigEndian(span),-32=>BitConverter.Int32BitsToSingle(BinaryPrimitives.ReadInt32BigEndian(span)),_=>BitConverter.Int64BitsToDouble(BinaryPrimitives.ReadInt64BigEndian(span))};
|
||||||
|
double value=raw*factor+zero;if(!double.IsFinite(value)||Math.Abs(value)>float.MaxValue)throw new InvalidDataException("Nonfinite color preview");
|
||||||
|
int channel=pattern[((dy+oy)%2)*2+(dx+ox)%2] switch{'R'=>0,'G'=>1,_=>2};sums[channel][y/step*ow+x/step]+=value;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
float[][] channels=[new float[ow*oh],new float[ow*oh],new float[ow*oh]];
|
||||||
|
for(int y=0;y<oh;y++)for(int x=0;x<ow;x++)
|
||||||
|
{
|
||||||
|
int i=y*ow+x,count=(Math.Min((y+1)*step,uh)-y*step)*(Math.Min((x+1)*step,uw)-x*step);
|
||||||
|
for(int c=0;c<3;c++)channels[c][i]=(float)(sums[c][i]/(count*(c==1?2:1)));
|
||||||
|
}
|
||||||
|
return new(ow,oh,channels[0],channels[1],channels[2]);
|
||||||
|
}
|
||||||
|
public static ColorPreviewDisplay Prepare(ColorPreviewPlane color,CancellationToken ct=default)
|
||||||
|
{
|
||||||
|
int count=color.Width*color.Height;float[][] channels=[color.Red,color.Green,color.Blue],chroma=new float[3][];double[] noise=new double[3];
|
||||||
|
float[] luma=new float[count];for(int i=0;i<count;i++)luma[i]=(float)(((double)color.Red[i]+color.Green[i]+color.Blue[i])/3);
|
||||||
|
for(int c=0;c<3;c++)
|
||||||
|
{
|
||||||
|
List<double> diff=[];for(int y=0;y<color.Height;y++)for(int x=0;x<color.Width-1;x++)diff.Add(Math.Abs(channels[c][y*color.Width+x]-channels[c][y*color.Width+x+1]));
|
||||||
|
noise[c]=Robust.Median(diff)/.953872;
|
||||||
|
chroma[c]=PreviewRenderer.Smooth(new(color.Width,color.Height,channels[c]),12,ct).Pixels;
|
||||||
|
double median=Robust.Median(chroma[c].Select(v=>(double)v));for(int i=0;i<count;i++)chroma[c][i]-=(float)median;
|
||||||
|
}
|
||||||
|
for(int i=0;i<count;i++)
|
||||||
|
{float mean=(chroma[0][i]+chroma[1][i]+chroma[2][i])/3;for(int c=0;c<3;c++)chroma[c][i]-=mean;}
|
||||||
|
// A 12-pass binomial filter has ~0.065 of the original 2D white-noise sigma.
|
||||||
|
// Suppress uncertain color excursions instead of painting noise with saturated hues.
|
||||||
|
return new(PreviewRenderer.Prepare(new(color.Width,color.Height,luma),true,ct),chroma,Math.Max(.001,noise.Average()*.065*2.5));
|
||||||
|
}
|
||||||
|
public static byte[] Render(ColorPreviewDisplay display,double target=.18)
|
||||||
|
{
|
||||||
|
byte[] mono=PreviewRenderer.Render(display.Luminance,target),output=new byte[mono.Length*4];
|
||||||
|
for(int i=0;i<mono.Length;i++)
|
||||||
|
{
|
||||||
|
double maximum=Math.Max(Math.Abs(display.Chroma[0][i]),Math.Max(Math.Abs(display.Chroma[1][i]),Math.Abs(display.Chroma[2][i]))),certainty=maximum>display.ChromaThreshold?1-Math.Pow(display.ChromaThreshold/maximum,2):0;
|
||||||
|
double level=Math.Max(.001,display.Luminance.Plane.Pixels[i]-display.Luminance.Black);
|
||||||
|
// Keep the linked luminance and scale all channels together into gamut.
|
||||||
|
// Bright star cores tend to neutral white, without clipped colored rings.
|
||||||
|
double scale=maximum>0?Math.Min(.6*certainty*mono[i]/level,Math.Min(.45*mono[i],255-mono[i])/maximum):0;
|
||||||
|
for(int c=0;c<3;c++)output[4*i+(2-c)]=(byte)Math.Clamp(mono[i]+scale*display.Chroma[c][i],0,255);
|
||||||
|
output[4*i+3]=255;
|
||||||
|
}
|
||||||
|
return output;
|
||||||
|
}
|
||||||
|
public static string PathFor(string directory,Frame frame)=>Path.Combine(directory,"previews",frame.Id+"-color1.bin");
|
||||||
|
public static void Write(ColorPreviewPlane color,string path,Frame frame)
|
||||||
|
{
|
||||||
|
Directory.CreateDirectory(Path.GetDirectoryName(Path.GetFullPath(path))!);string temp=path+".tmp";
|
||||||
|
try
|
||||||
|
{
|
||||||
|
using(var stream=File.Create(temp))
|
||||||
|
{
|
||||||
|
using(var header=new BinaryWriter(stream,System.Text.Encoding.UTF8,true)){header.Write(Magic);header.Write(frame.Length);header.Write(frame.Modified);header.Write(color.Width);header.Write(color.Height);}
|
||||||
|
using var compressed=new DeflateStream(stream,CompressionLevel.Fastest,true);
|
||||||
|
using var writer=new BinaryWriter(compressed);
|
||||||
|
foreach(var channel in new[]{color.Red,color.Green,color.Blue})
|
||||||
|
{if(BitConverter.IsLittleEndian)compressed.Write(MemoryMarshal.AsBytes(channel.AsSpan()));else foreach(float value in channel)writer.Write(value);}
|
||||||
|
}
|
||||||
|
File.Move(temp,path,true);
|
||||||
|
}
|
||||||
|
finally{if(File.Exists(temp))File.Delete(temp);}
|
||||||
|
}
|
||||||
|
public static ColorPreviewPlane Read(string path,Frame frame)
|
||||||
|
{
|
||||||
|
using var stream=File.OpenRead(path);using var header=new BinaryReader(stream,System.Text.Encoding.UTF8,true);
|
||||||
|
if(header.ReadInt32()!=Magic||header.ReadInt64()!=frame.Length||header.ReadInt64()!=frame.Modified)throw new InvalidDataException("Color preview source fingerprint changed");
|
||||||
|
int w=header.ReadInt32(),h=header.ReadInt32();if(w<=0||h<=0||(long)w*h>2_000_000)throw new InvalidDataException("Color preview dimensions exceed safety budget");
|
||||||
|
float[][] channels=[new float[w*h],new float[w*h],new float[w*h]];using var compressed=new DeflateStream(stream,CompressionMode.Decompress);using var reader=new BinaryReader(compressed);
|
||||||
|
foreach(var channel in channels)
|
||||||
|
{if(BitConverter.IsLittleEndian)compressed.ReadExactly(MemoryMarshal.AsBytes(channel.AsSpan()));else for(int i=0;i<channel.Length;i++)channel[i]=reader.ReadSingle();if(channel.Any(v=>!float.IsFinite(v)))throw new InvalidDataException("Nonfinite color preview");}
|
||||||
|
return new(w,h,channels[0],channels[1],channels[2]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -3,7 +3,8 @@ using System.Runtime.InteropServices;
|
||||||
namespace AstroFrame.Engine;
|
namespace AstroFrame.Engine;
|
||||||
|
|
||||||
public sealed record PreviewPlane(int Width,int Height,float[] Pixels);
|
public sealed record PreviewPlane(int Width,int Height,float[] Pixels);
|
||||||
public sealed record PreviewDisplay(PreviewPlane Plane,double Black,double White,double Mid);
|
public sealed record PreviewDisplay(PreviewPlane Plane,double Black,double White,double Mid,bool Diffuse=false);
|
||||||
|
public enum PreviewMode { Frame, Nebula, Asinh, Color }
|
||||||
/// <summary>Display-only area reduction and screen transfer. Never used by a quality detector.</summary>
|
/// <summary>Display-only area reduction and screen transfer. Never used by a quality detector.</summary>
|
||||||
public static class PreviewRenderer
|
public static class PreviewRenderer
|
||||||
{
|
{
|
||||||
|
|
@ -21,20 +22,54 @@ public static class PreviewRenderer
|
||||||
}
|
}
|
||||||
public static byte[] Render(PreviewPlane image,double target=.18,bool nebula=false)
|
public static byte[] Render(PreviewPlane image,double target=.18,bool nebula=false)
|
||||||
=>Render(Prepare(image,nebula),target);
|
=>Render(Prepare(image,nebula),target);
|
||||||
public static PreviewDisplay Prepare(PreviewPlane image,bool nebula=false)
|
public static PreviewDisplay Prepare(PreviewPlane image,bool nebula=false,CancellationToken ct=default)
|
||||||
{
|
{
|
||||||
var plane=nebula?Reduce(new(image.Width,image.Height,image.Pixels,1),2):image;
|
ct.ThrowIfCancellationRequested();var plane=nebula?Diffuse(image,ct):image;
|
||||||
var values=plane.Pixels.Select(v=>(double)v).ToArray();double median=Robust.Median(values);
|
var values=plane.Pixels.Select(v=>(double)v).ToArray();double median=Robust.Median(values);
|
||||||
List<double> differences=[];for(int y=0;y<plane.Height;y++)for(int x=0;x<plane.Width-1;x++)differences.Add(Math.Abs(plane.Pixels[y*plane.Width+x]-plane.Pixels[y*plane.Width+x+1]));
|
List<double> differences=[];for(int y=0;y<plane.Height;y++)for(int x=0;x<plane.Width-1;x++)differences.Add(Math.Abs(plane.Pixels[y*plane.Width+x]-plane.Pixels[y*plane.Width+x+1]));
|
||||||
double noise=Math.Max(.001,Robust.Median(differences)/.953872),black=median-2.8*noise,white=Math.Max(Robust.Quantile(values,.9995),median+30*noise),span=white-black;
|
double noise=Math.Max(.001,Robust.Median(differences)/.953872),black=median-2.8*noise,white=Math.Max(Robust.Quantile(values,.9995),median+30*noise),span=white-black;
|
||||||
return new(plane,black,white,(median-black)/span);
|
if(nebula){black=Math.Min(black,Robust.Quantile(values,.005));span=white-black;}
|
||||||
|
return new(plane,black,white,(median-black)/span,nebula);
|
||||||
}
|
}
|
||||||
public static byte[] Render(PreviewDisplay display,double target=.18)
|
public static byte[] Render(PreviewDisplay display,double target=.18,bool asinh=false)
|
||||||
{
|
{
|
||||||
double mid=display.Mid,t=Math.Clamp(target,.06,.45),m=mid*(t-1)/((2*t-1)*mid-t),span=display.White-display.Black;byte[] output=new byte[display.Plane.Pixels.Length];
|
double mid=display.Mid,t=Math.Clamp(target+(display.Diffuse?.07:0),.06,.48),m=mid*(t-1)/((2*t-1)*mid-t),span=display.White-display.Black;byte[] output=new byte[display.Plane.Pixels.Length];
|
||||||
for(int i=0;i<output.Length;i++){double v=Math.Clamp((display.Plane.Pixels[i]-display.Black)/span,0,1);output[i]=(byte)Math.Clamp(255*(m-1)*v/((2*m-1)*v-m),0,255);}
|
double strength=asinh?AsinhStrength(mid,t):0;
|
||||||
|
for(int i=0;i<output.Length;i++){double v=Math.Clamp((display.Plane.Pixels[i]-display.Black)/span,0,1);double result=asinh?(strength>0?Math.Asinh(strength*v)/Math.Asinh(strength):Math.Pow(v,Math.Log(t)/Math.Log(mid))):(m-1)*v/((2*m-1)*v-m);output[i]=(byte)Math.Clamp(255*result,0,255);}
|
||||||
return output;
|
return output;
|
||||||
}
|
}
|
||||||
|
static double AsinhStrength(double mid,double target)
|
||||||
|
{
|
||||||
|
if(mid>=target)return 0;double lo=.001,hi=1e10;
|
||||||
|
for(int n=0;n<64;n++){double k=(lo+hi)/2;if(Math.Asinh(k*mid)/Math.Asinh(k)<target)lo=k;else hi=k;}return hi;
|
||||||
|
}
|
||||||
|
public static PreviewPlane Diffuse(PreviewPlane image,CancellationToken ct=default)
|
||||||
|
{
|
||||||
|
int w=image.Width,h=image.Height;float[] median=new float[w*h];Span<float> samples=stackalloc float[9];
|
||||||
|
for(int y=0;y<h;y++)
|
||||||
|
{
|
||||||
|
ct.ThrowIfCancellationRequested();for(int x=0;x<w;x++)
|
||||||
|
{int n=0;for(int dy=-1;dy<=1;dy++)for(int dx=-1;dx<=1;dx++)samples[n++]=image.Pixels[Math.Clamp(y+dy,0,h-1)*w+Math.Clamp(x+dx,0,w-1)];samples.Sort();median[y*w+x]=samples[4];}
|
||||||
|
}
|
||||||
|
return Smooth(new(w,h,median),4,ct);
|
||||||
|
}
|
||||||
|
public static PreviewPlane Smooth(PreviewPlane image,int passes,CancellationToken ct=default)
|
||||||
|
{
|
||||||
|
int w=image.Width,h=image.Height;float[] input=(float[])image.Pixels.Clone(),horizontal=new float[w*h],output=new float[w*h];int[] kernel=[1,6,15,20,15,6,1];
|
||||||
|
for(int n=0;n<passes;n++)
|
||||||
|
{
|
||||||
|
for(int y=0;y<h;y++)
|
||||||
|
{
|
||||||
|
ct.ThrowIfCancellationRequested();for(int x=0;x<w;x++){double sum=0;for(int k=0;k<7;k++)sum+=kernel[k]*input[y*w+Math.Clamp(x+k-3,0,w-1)];horizontal[y*w+x]=(float)(sum/64);}
|
||||||
|
}
|
||||||
|
for(int y=0;y<h;y++)
|
||||||
|
{
|
||||||
|
ct.ThrowIfCancellationRequested();for(int x=0;x<w;x++){double sum=0;for(int k=0;k<7;k++)sum+=kernel[k]*horizontal[Math.Clamp(y+k-3,0,h-1)*w+x];output[y*w+x]=(float)(sum/64);}
|
||||||
|
}
|
||||||
|
(input,output)=(output,input);
|
||||||
|
}
|
||||||
|
return new(w,h,input);
|
||||||
|
}
|
||||||
public static void Write(ImagePlane image,string path,Frame? frame=null)
|
public static void Write(ImagePlane image,string path,Frame? frame=null)
|
||||||
{
|
{
|
||||||
var plane=Reduce(image,Math.Max(1,(image.Height+899)/900));string tmp=path+".tmp";Directory.CreateDirectory(Path.GetDirectoryName(Path.GetFullPath(path))!);
|
var plane=Reduce(image,Math.Max(1,(image.Height+899)/900));string tmp=path+".tmp";Directory.CreateDirectory(Path.GetDirectoryName(Path.GetFullPath(path))!);
|
||||||
|
|
|
||||||
43
tests/AstroFrame.Validation/ColorPreviewRegression.cs
Normal file
43
tests/AstroFrame.Validation/ColorPreviewRegression.cs
Normal file
|
|
@ -0,0 +1,43 @@
|
||||||
|
using AstroFrame.Engine;
|
||||||
|
using System.Security.Cryptography;
|
||||||
|
|
||||||
|
static class ColorPreviewRegression
|
||||||
|
{
|
||||||
|
public static void Run(Action<bool,string> check)
|
||||||
|
{
|
||||||
|
string directory=Path.Combine(Path.GetTempPath(),"AstroFrame-color-"+Guid.NewGuid());Directory.CreateDirectory(directory);
|
||||||
|
try
|
||||||
|
{
|
||||||
|
const int size=128;ColorPreviewPlane? last=null;Frame? frame=null;
|
||||||
|
foreach(string pattern in new[]{"RGGB","GRBG","GBRG","BGGR"})foreach(var offset in new[]{(X:0,Y:0),(X:1,Y:0),(X:0,Y:1),(X:1,Y:1)})
|
||||||
|
{
|
||||||
|
float[] pixels=new float[size*size];for(int y=0;y<size;y++)for(int x=0;x<size;x++)pixels[y*size+x]=pattern[((y+offset.Y)%2)*2+(x+offset.X)%2] switch{'R'=>600,'G'=>1000,_=>1400};
|
||||||
|
string path=Path.Combine(directory,$"{pattern}-{offset.X}-{offset.Y}.fit");ImageRegression.WriteFits(path,pixels,size,size,0,pattern,offset.X,offset.Y);
|
||||||
|
var color=ColorPreview.ReadFits(path)!;bool correct=color.Red.All(v=>v==600)&&color.Green.All(v=>v==1000)&&color.Blue.All(v=>v==1400);
|
||||||
|
check(correct,$"Bayer color channels respect {pattern} with offsets {offset.X},{offset.Y}");
|
||||||
|
check(Fits.Read(path).Pixels.All(v=>v==1000),$"color support preserves analysis grayscale for {pattern} with offsets {offset.X},{offset.Y}");
|
||||||
|
last=color;frame=Fits.Inspect(path);
|
||||||
|
}
|
||||||
|
byte[] sourceHash=SHA256.HashData(File.ReadAllBytes(frame!.Path));string cache=ColorPreview.PathFor(directory,frame!);ColorPreview.Write(last!,cache,frame!);var restored=ColorPreview.Read(cache,frame!);
|
||||||
|
check(restored.Red.SequenceEqual(last!.Red)&&restored.Green.SequenceEqual(last.Green)&&restored.Blue.SequenceEqual(last.Blue),"color caches retain linear RGB samples without losing channel order");
|
||||||
|
var neutral=ColorPreview.Render(ColorPreview.Prepare(restored));
|
||||||
|
check(Enumerable.Range(0,neutral.Length/4).All(i=>neutral[i*4]==neutral[i*4+1]&&neutral[i*4+1]==neutral[i*4+2]),"sky neutralization does not turn a constant colored pedestal into false nebula color");
|
||||||
|
check(sourceHash.SequenceEqual(SHA256.HashData(File.ReadAllBytes(frame.Path))),"color reading, preparing, rendering and caching preserve source FITS bytes");
|
||||||
|
bool refused=false;try{ColorPreview.Read(cache,new Frame{Length=frame.Length+1,Modified=frame.Modified});}catch(InvalidDataException){refused=true;}
|
||||||
|
check(refused,"changed sources invalidate color caches independently of quality data");
|
||||||
|
const int w=96,h=96;var random=new Random(1902);float[][] channels=[new float[w*h],new float[w*h],new float[w*h]];
|
||||||
|
for(int y=0;y<h;y++)for(int x=0;x<w;x++)for(int c=0;c<3;c++)channels[c][y*w+x]=(float)(1000+(c==0?80:0)*Math.Exp(-Math.Pow((x-48)/12.0,2)-Math.Pow((y-48)/20.0,2))+(random.NextDouble()-.5)*12);
|
||||||
|
var input=(float[])channels[0].Clone();var display=ColorPreview.Prepare(new(w,h,channels[0],channels[1],channels[2]));var output=ColorPreview.Render(display);
|
||||||
|
check(Enumerable.Range(0,w*h).Count(i=>output[i*4+2]>output[i*4]+30&&output[i*4+2]>output[i*4+1]+30)>20,"color nebula preserves a real red diffuse signal through the linked stretch");
|
||||||
|
var extremes=ColorPreview.Render(new(new(new(2,1,[0,10]),0,10,.5,true),[[100,100],[-50,-50],[-50,-50]],1));
|
||||||
|
check(extremes.Take(3).All(v=>v==0)&&extremes.Skip(4).Take(3).All(v=>v==255),"linked color stays neutral at black and white instead of clipping individual channels");
|
||||||
|
check(channels[0].SequenceEqual(input)&&Enumerable.Range(0,w*h).All(i=>output[i*4+3]==255),"color display leaves linear channels untouched and emits opaque pixels");
|
||||||
|
using(var cancel=new CancellationTokenSource()){cancel.Cancel();bool cancelled=false;try{ColorPreview.ReadFits(frame.Path,cancel.Token);}catch(OperationCanceledException){cancelled=true;}check(cancelled,"color FITS reading cancels before processing rows");}
|
||||||
|
string mono=Path.Combine(directory,"mono.fit");ImageRegression.WriteFits(mono,Enumerable.Repeat(1000f,128*128).ToArray(),128,128,0);
|
||||||
|
check(ColorPreview.ReadFits(mono)==null,"monochrome FITS files never acquire fabricated color channels");
|
||||||
|
string invalid=Path.Combine(directory,"invalid.fit");ImageRegression.WriteFits(invalid,Enumerable.Repeat(1000f,128*128).ToArray(),128,128,0,"XXXX");
|
||||||
|
check(ColorPreview.ReadFits(invalid)==null,"unknown Bayer layouts fall back to grayscale instead of guessing color");
|
||||||
|
}
|
||||||
|
finally{Directory.Delete(directory,true);}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -60,11 +60,11 @@ static class ImageRegression
|
||||||
}
|
}
|
||||||
finally{Directory.Delete(directory,true);}
|
finally{Directory.Delete(directory,true);}
|
||||||
}
|
}
|
||||||
internal static void WriteFits(string path,float[] pixels,int width,int height,int n)
|
internal static void WriteFits(string path,float[] pixels,int width,int height,int n,string bayer="",int offsetX=0,int offsetY=0)
|
||||||
{
|
{
|
||||||
string Card(string key,string value)=>(key.PadRight(8)+"= "+value).PadRight(80);
|
string Card(string key,string value)=>(key.PadRight(8)+"= "+value).PadRight(80);
|
||||||
string date=new DateTime(2026,9,20,8,0,0,DateTimeKind.Utc).AddSeconds(n*30).ToString("yyyy-MM-ddTHH:mm:ss",CultureInfo.InvariantCulture);
|
string date=new DateTime(2026,9,20,8,0,0,DateTimeKind.Utc).AddSeconds(n*30).ToString("yyyy-MM-ddTHH:mm:ss",CultureInfo.InvariantCulture);
|
||||||
string header=Card("SIMPLE","T")+Card("BITPIX","-32")+Card("NAXIS","2")+Card("NAXIS1",width.ToString())+Card("NAXIS2",height.ToString())+Card("EXPTIME","30")+Card("OBJECT","'Synthetic field'")+Card("DATE-OBS",$"'{date}'")+"END".PadRight(80);
|
string header=Card("SIMPLE","T")+Card("BITPIX","-32")+Card("NAXIS","2")+Card("NAXIS1",width.ToString())+Card("NAXIS2",height.ToString())+Card("EXPTIME","30")+Card("OBJECT","'Synthetic field'")+Card("DATE-OBS",$"'{date}'")+(bayer==""?"":Card("BAYERPAT",$"'{bayer}'")+Card("XBAYROFF",offsetX.ToString())+Card("YBAYROFF",offsetY.ToString()))+"END".PadRight(80);
|
||||||
using var stream=File.Create(path);stream.Write(Encoding.ASCII.GetBytes(header.PadRight((header.Length+2879)/2880*2880)));
|
using var stream=File.Create(path);stream.Write(Encoding.ASCII.GetBytes(header.PadRight((header.Length+2879)/2880*2880)));
|
||||||
byte[] row=new byte[width*4];for(int y=0;y<height;y++){for(int x=0;x<width;x++)BinaryPrimitives.WriteInt32BigEndian(row.AsSpan(x*4,4),BitConverter.SingleToInt32Bits(pixels[y*width+x]));stream.Write(row);}
|
byte[] row=new byte[width*4];for(int y=0;y<height;y++){for(int x=0;x<width;x++)BinaryPrimitives.WriteInt32BigEndian(row.AsSpan(x*4,4),BitConverter.SingleToInt32Bits(pixels[y*width+x]));stream.Write(row);}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -11,7 +11,20 @@ static class PreviewRegression
|
||||||
List<double> diff=[];for(int y=0;y<reduced.Height;y++)for(int x=0;x<reduced.Width-1;x++)diff.Add(Math.Abs(frame[y*reduced.Width+x]-frame[y*reduced.Width+x+1])/255.0);
|
List<double> diff=[];for(int y=0;y<reduced.Height;y++)for(int x=0;x<reduced.Width-1;x++)diff.Add(Math.Abs(frame[y*reduced.Width+x]-frame[y*reduced.Width+x+1])/255.0);
|
||||||
check(Robust.Median(diff)<.06&&Robust.Median(frame.Select(v=>v/255.0))<.25,"preview transfer keeps background grain subordinate to the image");
|
check(Robust.Median(diff)<.06&&Robust.Median(frame.Select(v=>v/255.0))<.25,"preview transfer keeps background grain subordinate to the image");
|
||||||
check(untouched.SequenceEqual(pixels),"preview reduction, stretching and nebula mode never alter analysis pixels");
|
check(untouched.SequenceEqual(pixels),"preview reduction, stretching and nebula mode never alter analysis pixels");
|
||||||
check(frame.Max()>frame[0]+80&&diffuse.Length<frame.Length,"preview preserves conspicuous stars and exposes a distinct diffuse-detail view");
|
check(frame.Max()>frame[0]+80&&diffuse.Length==frame.Length&&!diffuse.SequenceEqual(frame),"frame preview preserves conspicuous stars and diffuse view retains the full preview geometry");
|
||||||
|
float[] filament=new float[w*h];random=new Random(8461);
|
||||||
|
for(int y=0;y<h;y++)for(int x=0;x<w;x++)filament[y*w+x]=(float)(1000+10*Math.Exp(-Math.Pow((x-160-25*Math.Sin(y/120.0))/5,2))+(random.NextDouble()-.5)*60);
|
||||||
|
float[] original=(float[])filament.Clone();var enhanced=PreviewRenderer.Prepare(new(w,h,filament),true);var enhancedPixels=PreviewRenderer.Render(enhanced);List<double> core=[],sky=[];
|
||||||
|
for(int y=20;y<h-20;y++){int x=(int)Math.Round(160+25*Math.Sin(y/120.0));core.Add(enhancedPixels[y*w+x]);sky.Add(enhancedPixels[y*w+x+30]);}
|
||||||
|
check(Robust.Median(core)-Robust.Median(sky)>20,"nebula preview makes a faint narrow filament visible above adjacent sky");
|
||||||
|
check(original.SequenceEqual(filament),"faint-detail smoothing never modifies the original linear preview samples");
|
||||||
|
var alternate=PreviewRenderer.Render(enhanced,.18,true);var brighter=PreviewRenderer.Render(enhanced,.30,true);
|
||||||
|
check(!alternate.SequenceEqual(enhancedPixels)&&alternate.Zip(brighter).All(pair=>pair.Second>=pair.First),"asinh offers a distinct monotonic stretch and responds to brightness adjustments");
|
||||||
|
var highMedian=new PreviewDisplay(new(1,1,[.7f]),0,1,.7,true);
|
||||||
|
check(Math.Abs(PreviewRenderer.Render(highMedian,.18,true)[0]-255*.25)<2&&PreviewRenderer.Render(highMedian,.30,true)[0]>PreviewRenderer.Render(highMedian,.18,true)[0],"asinh brightness remains adjustable when the source median already exceeds the display target");
|
||||||
|
var flat=PreviewRenderer.Prepare(new(32,32,Enumerable.Repeat(1000f,1024).ToArray()),true);
|
||||||
|
check(PreviewRenderer.Render(flat).Distinct().Count()==1&&PreviewRenderer.Render(flat,.18,true).Distinct().Count()==1,"constant fields remain constant without invented diffuse structure");
|
||||||
|
using(var cancel=new CancellationTokenSource()){cancel.Cancel();bool cancelled=false;try{PreviewRenderer.Diffuse(new(w,h,filament),cancel.Token);}catch(OperationCanceledException){cancelled=true;}check(cancelled,"diffuse preview preparation cancels while smoothing");}
|
||||||
string path=Path.Combine(Path.GetTempPath(),"AstroFrame-preview-"+Guid.NewGuid()+".bin");var f=new Frame{Length=7654,Modified=4321};
|
string path=Path.Combine(Path.GetTempPath(),"AstroFrame-preview-"+Guid.NewGuid()+".bin");var f=new Frame{Length=7654,Modified=4321};
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
|
|
|
||||||
|
|
@ -130,4 +130,5 @@ QualityRegression.Run(Check);
|
||||||
OverlayRegression.Run(Check);
|
OverlayRegression.Run(Check);
|
||||||
PreviewRegression.Run(Check);
|
PreviewRegression.Run(Check);
|
||||||
StellarDetailRegression.Run(Check);
|
StellarDetailRegression.Run(Check);
|
||||||
|
ColorPreviewRegression.Run(Check);
|
||||||
Console.WriteLine($"{passed} checks passed. Synthetic tests validate mechanics, not astrophotography stack quality.");
|
Console.WriteLine($"{passed} checks passed. Synthetic tests validate mechanics, not astrophotography stack quality.");
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue