Initial commit

This commit is contained in:
2026-08-22 19:02:35 +03:00 Unverified
commit 4de1b2c560
9 changed files with 917 additions and 0 deletions
+352
View File
@@ -0,0 +1,352 @@
## Ignore Visual Studio temporary files, build results, and
## files generated by popular Visual Studio add-ons.
##
## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore
# User-specific files
*.suo
*.user
*.userosscache
*.sln.docstates
# User-specific files (MonoDevelop/Xamarin Studio)
*.userprefs
# Build results
[Dd]ebug/
[Dd]ebugPublic/
[Rr]elease/
[Rr]eleases/
x64/
x86/
bld/
[Bb]in/
[Oo]bj/
[Ll]og/
# Visual Studio 2015/2017 cache/options directory
.vs/
.vscode/
# Uncomment if you have tasks that create the project's static files in wwwroot
#wwwroot/
# Visual Studio 2017 auto generated files
Generated\ Files/
# MSTest test Results
[Tt]est[Rr]esult*/
[Bb]uild[Ll]og.*
# NUNIT
*.VisualState.xml
TestResult.xml
# Build Results of an ATL Project
[Dd]ebugPS/
[Rr]eleasePS/
dlldata.c
# Benchmark Results
BenchmarkDotNet.Artifacts/
# .NET Core
project.lock.json
project.fragment.lock.json
artifacts/
**/Properties/launchSettings.json
# StyleCop
StyleCopReport.xml
# Files built by Visual Studio
*_p.c
*_i.h
*.ilk
*.meta
*.obj
*.iobj
*.pch
*.pdb
*.ipdb
*.pgc
*.pgd
*.rsp
*.sbr
*.tlb
*.tli
*.tlh
*.tmp
*.tmp_proj
*.log
*.vspscc
*.vssscc
.builds
*.pidb
*.svclog
*.scc
# Chutzpah Test files
_Chutzpah*
# Visual C++ cache files
ipch/
*.aps
*.ncb
*.opendb
*.opensdf
*.sdf
*.cachefile
*.VC.db
*.VC.VC.opendb
# Visual Studio profiler
*.psess
*.vsp
*.vspx
*.sap
# Visual Studio Trace Files
*.e2e
# TFS 2012 Local Workspace
$tf/
# Guidance Automation Toolkit
*.gpState
# ReSharper is a .NET coding add-in
_ReSharper*/
*.[Rr]e[Ss]harper
*.DotSettings.user
# JustCode is a .NET coding add-in
.JustCode
# TeamCity is a build add-in
_TeamCity*
# DotCover is a Code Coverage Tool
*.dotCover
# AxoCover is a Code Coverage Tool
.axoCover/*
!.axoCover/settings.json
# Visual Studio code coverage results
*.coverage
*.coveragexml
# NCrunch
_NCrunch_*
.*crunch*.local.xml
nCrunchTemp_*
# MightyMoose
*.mm.*
AutoTest.Net/
# Web workbench (sass)
.sass-cache/
# Installshield output folder
[Ee]xpress/
# DocProject is a documentation generator add-in
DocProject/buildhelp/
DocProject/Help/*.HxT
DocProject/Help/*.HxC
DocProject/Help/*.hhc
DocProject/Help/*.hhk
DocProject/Help/*.hhp
DocProject/Help/Html2
DocProject/Help/html
# Click-Once directory
publish/
# Publish Web Output
*.[Pp]ublish.xml
*.azurePubxml
# Note: Comment the next line if you want to checkin your web deploy settings,
# but database connection strings (with potential passwords) will be unencrypted
*.pubxml
*.publishproj
# Microsoft Azure Web App publish settings. Comment the next line if you want to
# checkin your Azure Web App publish settings, but sensitive information contained
# in these scripts will be unencrypted
PublishScripts/
# NuGet Packages
*.nupkg
# The packages folder can be ignored because of Package Restore
**/[Pp]ackages/*
# except build/, which is used as an MSBuild target.
!**/[Pp]ackages/build/
# Uncomment if necessary however generally it will be regenerated when needed
#!**/[Pp]ackages/repositories.config
# NuGet v3's project.json files produces more ignorable files
*.nuget.props
*.nuget.targets
# Microsoft Azure Build Output
csx/
*.build.csdef
# Microsoft Azure Emulator
ecf/
rcf/
# Windows Store app package directories and files
AppPackages/
BundleArtifacts/
Package.StoreAssociation.xml
_pkginfo.txt
*.appx
# Visual Studio cache files
# files ending in .cache can be ignored
*.[Cc]ache
# but keep track of directories ending in .cache
!*.[Cc]ache/
# Others
ClientBin/
~$*
*~
*.dbmdl
*.dbproj.schemaview
*.jfm
*.pfx
*.publishsettings
orleans.codegen.cs
# Including strong name files can present a security risk
# (https://github.com/github/gitignore/pull/2483#issue-259490424)
#*.snk
# Since there are multiple workflows, uncomment next line to ignore bower_components
# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
#bower_components/
# RIA/Silverlight projects
Generated_Code/
# Backup & report files from converting an old project file
# to a newer Visual Studio version. Backup files are not needed,
# because we have git ;-)
_UpgradeReport_Files/
Backup*/
UpgradeLog*.XML
UpgradeLog*.htm
ServiceFabricBackup/
*.rptproj.bak
# SQL Server files
*.mdf
*.ldf
*.ndf
# Business Intelligence projects
*.rdl.data
*.bim.layout
*.bim_*.settings
*.rptproj.rsuser
# Microsoft Fakes
FakesAssemblies/
# GhostDoc plugin setting file
*.GhostDoc.xml
# Node.js Tools for Visual Studio
.ntvs_analysis.dat
node_modules/
# Visual Studio 6 build log
*.plg
# Visual Studio 6 workspace options file
*.opt
# Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
*.vbw
# Visual Studio LightSwitch build output
**/*.HTMLClient/GeneratedArtifacts
**/*.DesktopClient/GeneratedArtifacts
**/*.DesktopClient/ModelManifest.xml
**/*.Server/GeneratedArtifacts
**/*.Server/ModelManifest.xml
_Pvt_Extensions
# Paket dependency manager
.paket/paket.exe
paket-files/
# FAKE - F# Make
.fake/
# JetBrains Rider
.idea/
*.sln.iml
# CodeRush
.cr/
# Python Tools for Visual Studio (PTVS)
__pycache__/
*.pyc
# Cake - Uncomment if you are using it
# tools/**
# !tools/packages.config
# Tabs Studio
*.tss
# Telerik's JustMock configuration file
*.jmconfig
# BizTalk build output
*.btp.cs
*.btm.cs
*.odx.cs
*.xsd.cs
# OpenCover UI analysis results
OpenCover/
# Azure Stream Analytics local run output
ASALocalRun/
# MSBuild Binary and Structured Log
*.binlog
# NVidia Nsight GPU debugger configuration file
*.nvuser
# MFractors (Xamarin productivity tool) working folder
.mfractor/
/.dotnet
/.packages
/.tools/vswhere/2.5.2
/.tools/vswhere/3.1.7
/.tools/native/iltools
### OSX ###
.DS_Store
.AppleDouble
.LSOverride
# Directories potentially created on remote AFP share
.AppleDB
.AppleDesktop
Network Trash Folder
Temporary Items
.apdisk
# Exceptions to the exclusions
!src/Microsoft.DotNet.Wpf/src/WpfGfx/codegen/mcg/main/*.rsp
!src/Microsoft.DotNet.Wpf/src/WpfGfx/tools/csp/**/*.rsp
+9
View File
@@ -0,0 +1,9 @@
<Application x:Class="DSPS_Lab3.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:DSPS_Lab3"
StartupUri="MainWindow.xaml">
<Application.Resources>
</Application.Resources>
</Application>
+12
View File
@@ -0,0 +1,12 @@
using System.Configuration;
using System.Data;
using System.Windows;
namespace DSPS_Lab3;
/// <summary>
/// Interaction logic for App.xaml
/// </summary>
public partial class App : Application
{
}
+10
View File
@@ -0,0 +1,10 @@
using System.Windows;
[assembly: ThemeInfo(
ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located
//(used if a resource is not found in the page,
// or application resource dictionaries)
ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located
//(used if a resource is not found in the page,
// app, or any theme specific resource dictionaries)
)]
+17
View File
@@ -0,0 +1,17 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>WinExe</OutputType>
<TargetFramework>net10.0-windows</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<UseWPF>true</UseWPF>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="MathNet.Numerics" Version="5.0.0" />
<PackageReference Include="MathNet.Numerics.MKL.Win-x64" Version="3.0.0" />
</ItemGroup>
</Project>
+3
View File
@@ -0,0 +1,3 @@
<Solution>
<Project Path="DSPS_Lab3.csproj" />
</Solution>
+58
View File
@@ -0,0 +1,58 @@
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows;
using System.Windows.Media.Imaging;
namespace DSPS_Lab3;
public static class Ex
{
public static float[,] GenerateSpatialKernel(int size, float sigma)
{
var kernel = new float[size, size];
float sum = 0;
var half = size / 2;
// Use <= half to ensure the full kernel is covered
for (var y = -half; y <= half; y++)
{
for (var x = -half; x <= half; x++)
{
// Optional: Bounds check for odd/even sizes
if (y + half >= size || x + half >= size) continue;
var val = (float)Math.Exp(-(x * x + y * y) / (2 * sigma * sigma));
kernel[y + half, x + half] = val;
sum += val;
}
}
for (var y = 0; y < size; y++)
for (var x = 0; x < size; x++)
kernel[y, x] /= sum;
return kernel;
}
public static float[,] PadAndShiftKernel(float[,] smallKernel, int imgWidth, int imgHeight)
{
var fullKernel = new float[imgHeight, imgWidth];
int kHeight = smallKernel.GetLength(0);
int kWidth = smallKernel.GetLength(1);
int radY = kHeight / 2;
int radX = kWidth / 2;
for (int y = 0; y < kHeight; y++)
{
for (int x = 0; x < kWidth; x++)
{
// Circular shift: maps kernel center to (0,0)
int targetY = (y - radY + imgHeight) % imgHeight;
int targetX = (x - radX + imgWidth) % imgWidth;
fullKernel[targetY, targetX] = smallKernel[y, x];
}
}
return fullKernel;
}
}
+88
View File
@@ -0,0 +1,88 @@
<Window x:Class="DSPS_Lab3.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:DSPS_Lab3"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="64"/>
</Grid.RowDefinitions>
<Image x:Name="MainImage" Grid.Column="0" Grid.Row="0" Margin="10" Stretch="Uniform">
<Image.Style>
<Style TargetType="Image">
<Setter Property="RenderOptions.BitmapScalingMode" Value="NearestNeighbor" />
<Style.Triggers>
<DataTrigger Binding="{Binding IsChecked, ElementName=QualityToggle}" Value="True">
<Setter Property="RenderOptions.BitmapScalingMode" Value="HighQuality" />
</DataTrigger>
</Style.Triggers>
</Style>
</Image.Style>
</Image>
<ProgressBar x:Name="progressBar1" Grid.Column="1" Grid.Row="0" VerticalAlignment="Stretch" Orientation="Vertical">
<ProgressBar.LayoutTransform>
<RotateTransform Angle="180" />
</ProgressBar.LayoutTransform>
</ProgressBar>
<CheckBox x:Name="QualityToggle" Content="Smooth" />
<Image x:Name="SlowImage" Grid.Column="1" Grid.Row="0" Margin="10" Stretch="Uniform">
<Image.Style>
<Style TargetType="Image">
<Setter Property="RenderOptions.BitmapScalingMode" Value="NearestNeighbor" />
<Style.Triggers>
<DataTrigger Binding="{Binding IsChecked, ElementName=QualityToggle}" Value="True">
<Setter Property="RenderOptions.BitmapScalingMode" Value="HighQuality" />
</DataTrigger>
</Style.Triggers>
</Style>
</Image.Style>
</Image>
<Image x:Name="FastImage" Grid.Column="2" Grid.Row="0" Margin="10" Stretch="Uniform">
<Image.Style>
<Style TargetType="Image">
<Setter Property="RenderOptions.BitmapScalingMode" Value="NearestNeighbor" />
<Style.Triggers>
<DataTrigger Binding="{Binding IsChecked, ElementName=QualityToggle}" Value="True">
<Setter Property="RenderOptions.BitmapScalingMode" Value="HighQuality" />
</DataTrigger>
</Style.Triggers>
</Style>
</Image.Style>
</Image>
<GridSplitter Grid.ColumnSpan="3" Grid.Row="1" Height="2" HorizontalAlignment="Stretch" ResizeDirection="Rows"/>
<Grid Grid.Column="0" Grid.Row="2">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Button Grid.Column="0" Margin="10" Content="Load Image" FontSize="20px" Click="LoadImageClick"/>
<Button Grid.Column="1" Margin="10" Content="Save Images" FontSize="20px" Click="SaveImagesClick"/>
</Grid>
<StackPanel Grid.Column="1" Grid.Row="2" Margin="10" Orientation="Horizontal" HorizontalAlignment="Center" VerticalAlignment="Center">
<Label Content="{Binding ElementName=kernelSize, Path=Value}" ContentStringFormat="Kernel size: {0}" FontSize="20px"/>
<Label Content="{Binding ElementName=sigmaValue, Path=Value}" ContentStringFormat="σ: {0:F2}" FontSize="20px"/>
</StackPanel>
<Label x:Name="spatialProgress" Grid.Column="1" Grid.Row="0" Content="1"/>
<Label x:Name="fftProgress" Grid.Column="2" Grid.Row="0" Content="2"/>
<Viewbox Stretch="Fill" Grid.Column="2" Grid.Row="2">
<Canvas x:Name="GraphCanvas" Width="100" Height="25" ClipToBounds="True">
</Canvas>
</Viewbox>
<StackPanel Grid.Column="2" Grid.Row="2" >
<Slider x:Name="kernelSize" Margin="5" Maximum="101" Value="5" VerticalAlignment="Center" TickPlacement="TopLeft" TickFrequency="2" IsSnapToTickEnabled="True" Minimum="1" ValueChanged="ChangeParams"/>
<Slider x:Name="sigmaValue" Margin="5" Maximum="10.0" Value="1" VerticalAlignment="Center" Minimum="0.1" ValueChanged="ChangeParams"/>
</StackPanel>
</Grid>
</Window>
+368
View File
@@ -0,0 +1,368 @@
using System.Diagnostics;
using System.IO;
using System.Linq.Expressions;
using System.Numerics;
using System.Runtime.InteropServices;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Media.Media3D;
using System.Windows.Navigation;
using System.Windows.Shapes;
using MathNet.Numerics;
using MathNet.Numerics.IntegralTransforms;
using Microsoft.Win32;
using static DSPS_Lab3.Ex;
namespace DSPS_Lab3;
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : System.Windows.Window
{
BitmapImage source;
WriteableBitmap _spatial, _fft;
CancellationTokenSource _cts;
string path = "";
public MainWindow()
{
_cts = new CancellationTokenSource();
InitializeComponent();
MathNet.Numerics.Control.UseNativeMKL();
}
private void ChangeParams(object sender, RoutedPropertyChangedEventArgs<double> e)
{
if (this.sigmaValue == null) return;
int kernelSize = 0, imgWnew = 0, imgHnew = 0, imgW = 0, imgH = 0;
float sigmaValue = 0;
Application.Current.Dispatcher.Invoke(() => {
kernelSize = (int)this.kernelSize.Value;
sigmaValue = (float)this.sigmaValue.Value;
});
DrawGaussianGraph(kernelSize, sigmaValue);
if (source == null) return;
_cts.Cancel();
_cts = new CancellationTokenSource();
_spatial = new WriteableBitmap(source);
_fft = new WriteableBitmap(source);
SlowImage.Source = _spatial;
FastImage.Source = _fft;
Application.Current.Dispatcher.Invoke(() => {
imgWnew = _fft.PixelWidth;
imgHnew = _fft.PixelHeight;
imgW = source.PixelWidth;
imgH = source.PixelHeight;
});
Stopwatch timer1 = Stopwatch.StartNew(), timer2 = Stopwatch.StartNew();
Task.Run(() => SpatialBlur(GenerateSpatialKernel(kernelSize, sigmaValue), _spatial, _cts.Token), _cts.Token)
.ContinueWith(t => {
Application.Current.Dispatcher.Invoke(() => {
timer1.Stop();
spatialProgress.Content = $"{timer1.ElapsedMilliseconds}ms";
});
});
Task.Run(() => FrequencyBlur(PadAndShiftKernel(GenerateSpatialKernel(kernelSize, sigmaValue), imgWnew, imgHnew), _fft, _cts.Token), _cts.Token)
.ContinueWith(t => {
Application.Current.Dispatcher.Invoke(() => {
timer2.Stop();
fftProgress.Content = $"{timer2.ElapsedMilliseconds}ms";
});
});
}
private void LoadImageClick(object sender, RoutedEventArgs e)
{
OpenFileDialog openFileDialog = new OpenFileDialog();
openFileDialog.Filter = "Image Files (*.jpg;*.jpeg;*.png;*.bmp;*.gif;*.tiff;*.tif;*.ico)|*.jpg;*.jpeg;*.png;*.bmp;*.gif;*.tiff;*.tif;*.ico|" +
"JPEG / JPG (*.jpg;*.jpeg)|*.jpg;*.jpeg|" +
"PNG (*.png)|*.png|" +
"BMP (*.bmp)|*.bmp|" +
"GIF (*.gif)|*.gif|" +
"TIFF (*.tiff;*.tif)|*.tiff;*.tif|" +
"ICO (*.ico)|*.ico";
openFileDialog.FilterIndex = 1;
if (openFileDialog.ShowDialog() == true)
{
_cts.Cancel();
path = openFileDialog.FileName;
source = new BitmapImage(new Uri(path));
MainImage.Source = source;
}
}
private void SaveImagesClick(object sender, RoutedEventArgs e)
{
string directory = System.IO.Path.GetDirectoryName(path);
string fileNameNoExt = System.IO.Path.GetFileNameWithoutExtension(path);
string targetFolder = System.IO.Path.Combine(directory, fileNameNoExt);
if (!Directory.Exists(targetFolder))
{
Directory.CreateDirectory(targetFolder);
}
string originalPath = System.IO.Path.Combine(targetFolder, $"{fileNameNoExt}_original.png");
string spatialPath = System.IO.Path.Combine(targetFolder, $"{fileNameNoExt}_spatial.png");
string fftPath = System.IO.Path.Combine(targetFolder, $"{fileNameNoExt}_fft.png");
SaveToPng(source, originalPath);
SaveToPng(_spatial, spatialPath);
SaveToPng(_fft, fftPath);
}
public void SpatialBlur(float[,] kernel, WriteableBitmap bitmap, CancellationToken ct)
{
int width = 0, height = 0, stride = 0;
IntPtr buffer = IntPtr.Zero;
Application.Current.Dispatcher.Invoke(() =>
{
width = bitmap.PixelWidth;
height = bitmap.PixelHeight;
stride = bitmap.BackBufferStride;
buffer = bitmap.BackBuffer;
});
byte[] srcPixels = new byte[height * stride];
Marshal.Copy(buffer, srcPixels, 0, srcPixels.Length);
int kWidth = kernel.GetLength(0);
int kHeight = kernel.GetLength(1);
int radX = kWidth / 2;
int radY = kHeight / 2;
Application.Current.Dispatcher.Invoke(() =>
{
progressBar1.Maximum = height;
progressBar1.Value = 0;
});
try
{
unsafe
{
byte* pDst = (byte*)buffer;
fixed (byte* pSrc = srcPixels)
{
for (int y = 0; y < height; y++)
{
ct.ThrowIfCancellationRequested();
for (int x = 0; x < width; x++)
{
float b = 0, g = 0, r = 0, a = 0;
// Kernel Window
for (int ky = -radY; ky <= radY; ky++)
{
// Edge handling: Clamp to image boundaries
int py = Math.Clamp(y + ky, 0, height - 1);
byte* rowPtr = pSrc + (py * stride);
for (int kx = -radX; kx <= radX; kx++)
{
int px = Math.Clamp(x + kx, 0, width - 1);
float weight = kernel[kx + radX, ky + radY];
// 4 bytes per pixel (BGRA)
int pixelIdx = px * 4;
b += rowPtr[pixelIdx] * weight;
g += rowPtr[pixelIdx + 1] * weight;
r += rowPtr[pixelIdx + 2] * weight;
a += rowPtr[pixelIdx + 3] * weight;
}
}
int destIdx = (y * stride) + (x * 4);
pDst[destIdx] = (byte)Math.Clamp(b, 0, 255);
pDst[destIdx + 1] = (byte)Math.Clamp(g, 0, 255);
pDst[destIdx + 2] = (byte)Math.Clamp(r, 0, 255);
pDst[destIdx + 3] = (byte)Math.Clamp(a, 0, 255);
}
if (y % 10 == 0 || y == height - 1)
{
Application.Current.Dispatcher.Invoke(() =>
{
progressBar1.Value = y;
bitmap.Lock();
bitmap.AddDirtyRect(new Int32Rect(0, 0, width, height));
bitmap.Unlock();
}, System.Windows.Threading.DispatcherPriority.Render);
}
}
}
}
}
catch (OperationCanceledException)
{
// Blurring was cancelled, which is expected when changing kernel size rapidly.
// No action needed here.
return;
}
Application.Current.Dispatcher.Invoke(() =>
{
progressBar1.Value = progressBar1.Maximum;
});
}
public void FrequencyBlur(float[,] paddedKernel, WriteableBitmap bitmap, CancellationToken ct)
{
int width = 0, height = 0, stride = 0;
IntPtr buffer = IntPtr.Zero;
Application.Current.Dispatcher.Invoke(() => {
width = bitmap.PixelWidth;
height = bitmap.PixelHeight;
stride = bitmap.BackBufferStride;
buffer = bitmap.BackBuffer;
});
int pixelCount = width * height;
Complex[] kernelFFT = new Complex[pixelCount];
for (int y = 0; y < height; y++)
for (int x = 0; x < width; x++)
kernelFFT[y * width + x] = new Complex(paddedKernel[y, x], 0);
Fourier.Forward2D(kernelFFT, height, width, FourierOptions.Matlab);
byte[] srcPixels = new byte[height * stride];
Marshal.Copy(buffer, srcPixels, 0, srcPixels.Length);
try
{
for (int c = 0; c < 4; c++)
{
ct.ThrowIfCancellationRequested();
Complex[] channel = new Complex[pixelCount];
for (int y = 0; y < height; y++)
for (int x = 0; x < width; x++)
channel[y * width + x] = new Complex(srcPixels[y * stride + x * 4 + c], 0);
Fourier.Forward2D(channel, height, width, FourierOptions.Matlab);
for (int i = 0; i < pixelCount; i++)
channel[i] *= kernelFFT[i];
Fourier.Inverse2D(channel, height, width, FourierOptions.Matlab);
for (int y = 0; y < height; y++)
for (int x = 0; x < width; x++)
srcPixels[y * stride + x * 4 + c] = (byte)Math.Clamp(channel[y * width + x].Real, 0, 255);
}
}
catch (OperationCanceledException)
{
// Blurring was cancelled, which is expected when changing kernel size rapidly.
// No action needed here.
return;
}
Application.Current.Dispatcher.Invoke(() => {
bitmap.Lock();
Marshal.Copy(srcPixels, 0, bitmap.BackBuffer, srcPixels.Length);
bitmap.AddDirtyRect(new Int32Rect(0, 0, width, height));
bitmap.Unlock();
});
}
private void SaveToPng(BitmapSource bitmapSource, string filePath)
{
if (bitmapSource == null) return;
using (var fileStream = new FileStream(filePath, FileMode.Create))
{
PngBitmapEncoder encoder = new PngBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create(bitmapSource));
encoder.Save(fileStream);
}
}
public void DrawGaussianGraph(int kernelSize, double sigma)
{
GraphCanvas.Children.Clear();
if (kernelSize <= 0 || sigma <= 0) return;
Polyline curve = new Polyline
{
Stroke = Brushes.DodgerBlue,
StrokeThickness = 2,
StrokeLineJoin = PenLineJoin.Round // Ensures smooth corners
};
double center = (kernelSize - 1) / 2.0;
PointCollection points = new PointCollection();
for (int i = 0; i < kernelSize; i++)
{
// 1. Calculate Gaussian Value
double xOffset = i - center;
double exponent = -(xOffset * xOffset) / (2 * sigma * sigma);
double yValue = Math.Exp(exponent); // Normalized height is 1.0
// 2. Map to Canvas Coordinates (100x100)
// X maps the index to 0-100
double xPos = (i / (double)(kernelSize - 1)) * 100;
// Y maps 1.0 (peak) to 0 (top of canvas) and 0.0 to 100 (bottom)
double yPos = (25 - (yValue * 20)) ; // 90 to leave a small margin at top
points.Add(new Point(xPos, yPos));
}
curve.Points = points;
GraphCanvas.Children.Add(curve);
}
public WriteableBitmap PreparePaddedBitmap(BitmapImage source)
{
int newWidth = NextPowerOfTwo(source.PixelWidth);
int newHeight = NextPowerOfTwo(source.PixelHeight);
// Create the larger bitmap
WriteableBitmap paddedBitmap = new WriteableBitmap(
newWidth,
newHeight,
source.DpiX,
source.DpiY,
PixelFormats.Bgra32,
null);
// Copy the original image into the top-left corner
// The rest of the bitmap remains black (0), which is "Zero Padding"
byte[] pixels = new byte[source.PixelWidth * 4 * source.PixelHeight];
source.CopyPixels(pixels, source.PixelWidth * 4, 0);
paddedBitmap.WritePixels(
new Int32Rect(0, 0, source.PixelWidth, source.PixelHeight),
pixels,
source.PixelWidth * 4,
0);
return paddedBitmap;
}
private int NextPowerOfTwo(int n)
{
if (n < 1) return 1;
return (int)Math.Pow(2, Math.Ceiling(Math.Log2(n)));
}
}