-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
264 lines (230 loc) · 16.7 KB
/
Copy pathProgram.cs
File metadata and controls
264 lines (230 loc) · 16.7 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
using System;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Imaging;
using System.Runtime.InteropServices;
public class ImageProcessorUnique
{
private const string SourceImagePath = @"C:\Users\Admin\Desktop\grafikatest.jpg";
private static readonly string SelectedFilterName = "GaussianBlur5x5";
private static readonly double[,] SelectedFilter = Filters.GaussianBlur5x5;
public static void Main(string[] args)
{
Console.WriteLine("--- Benchmark Przetwarzania Obrazu ---");
Console.WriteLine($"Filtr: {SelectedFilterName}");
NormalizeFilter(SelectedFilter);
int filterWidth = SelectedFilter.GetLength(1);
int filterHeight = SelectedFilter.GetLength(0);
if (!System.IO.File.Exists(SourceImagePath))
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine($"\nKRYTYCZNY BŁĄD: Nie odnaleziono pliku źródłowego pod ścieżką:");
Console.WriteLine(SourceImagePath);
Console.ResetColor();
Console.WriteLine("Sprawdź ścieżkę w kodzie (SourceImagePath) i spróbuj ponownie.");
Console.ReadLine();
return;
}
Console.WriteLine("\nWybierz metodę przetwarzania:");
Console.WriteLine(" 1. unmanaged (Unsafe / wskaźniki)");
Console.WriteLine(" 2. managed (byte[,])");
Console.Write("Twój wybór (1 lub 2): ");
string modeChoice = Console.ReadLine() ?? "1";
try
{
using (Bitmap originalBmp = new Bitmap(SourceImagePath))
{
PixelFormat targetPixelFormat = (originalBmp.PixelFormat == PixelFormat.Format24bppRgb ||
originalBmp.PixelFormat == PixelFormat.Format32bppArgb ||
originalBmp.PixelFormat == PixelFormat.Format32bppRgb)
? originalBmp.PixelFormat
: PixelFormat.Format24bppRgb;
using (Bitmap resultBmp = (originalBmp.PixelFormat == targetPixelFormat)
? new Bitmap(originalBmp.Width, originalBmp.Height, targetPixelFormat)
: originalBmp.Clone(new Rectangle(0, 0, originalBmp.Width, originalBmp.Height), targetPixelFormat))
{
Stopwatch perfTimer = new Stopwatch();
long baseExecutionTimeMs = 0;
Action processingMethod;
string selectedMethodName = "";
switch (modeChoice)
{
case "1":
selectedMethodName = "Direct Access (Unsafe)";
Console.WriteLine($"\nWybrana metoda: {selectedMethodName}");
Console.WriteLine("Uwaga: Wymaga włączonej opcji 'Allow unsafe code' w projekcie.");
if (resultBmp.PixelFormat != PixelFormat.Format24bppRgb && resultBmp.PixelFormat != PixelFormat.Format32bppArgb && resultBmp.PixelFormat != PixelFormat.Format32bppRgb)
{
Console.WriteLine($"INFO: Format obrazu '{resultBmp.PixelFormat}' może nie być optymalny dla tej metody. Preferowane: 24bppRGB, 32bppArgb/Rgb.");
}
processingMethod = () => ApplyConvolution_UnsafeDirect(originalBmp, resultBmp, SelectedFilter, filterWidth, filterHeight);
break;
case "2":
selectedMethodName = "Managed 2D Array (byte[,])";
Console.WriteLine($"\nWybrana metoda: {selectedMethodName}");
if (resultBmp.PixelFormat != PixelFormat.Format24bppRgb && resultBmp.PixelFormat != PixelFormat.Format32bppArgb && resultBmp.PixelFormat != PixelFormat.Format32bppRgb)
{
Console.WriteLine($"INFO: Format obrazu '{resultBmp.PixelFormat}'. Metoda obsługuje 24bppRGB, 32bppArgb/Rgb.");
}
processingMethod = () => ApplyConvolution_Managed2DBytes(originalBmp, resultBmp, SelectedFilter, filterWidth, filterHeight);
break;
default:
selectedMethodName = "Direct Access (Unsafe)";
Console.WriteLine($"\nNieprawidłowy wybór. Używam domyślnej metody: {selectedMethodName}");
Console.WriteLine("Uwaga: Wymaga włączonej opcji 'Allow unsafe code' w projekcie.");
modeChoice = "1";
if (resultBmp.PixelFormat != PixelFormat.Format24bppRgb && resultBmp.PixelFormat != PixelFormat.Format32bppArgb && resultBmp.PixelFormat != PixelFormat.Format32bppRgb) { Console.WriteLine($"INFO: Format obrazu '{resultBmp.PixelFormat}'..."); }
processingMethod = () => ApplyConvolution_UnsafeDirect(originalBmp, resultBmp, SelectedFilter, filterWidth, filterHeight);
break;
}
Console.WriteLine($"\nRozpoczynanie przetwarzania bazowego dla '{selectedMethodName}'...");
perfTimer.Start();
processingMethod();
perfTimer.Stop();
baseExecutionTimeMs = perfTimer.ElapsedMilliseconds;
Console.WriteLine($"Czas przetwarzania bazowego ({selectedMethodName}): {baseExecutionTimeMs} ms");
Console.Write($"\nCzy uruchomić ponownie z wymuszeniem GC przed pomiarem? (tak/nie): ");
string runGcTestInput = Console.ReadLine()?.ToLowerInvariant() ?? "nie";
string outputFilePath;
string gcSuffix = "-BaseRun";
if (runGcTestInput == "tak")
{
Console.WriteLine("Wymuszanie pełnej kolekcji Garbage Collector...");
GC.Collect();
GC.WaitForPendingFinalizers();
Console.WriteLine($"\nRozpoczynanie przetwarzania po GC dla '{selectedMethodName}'...");
perfTimer.Restart();
processingMethod();
perfTimer.Stop();
Console.WriteLine($"Czas przetwarzania po GC ({selectedMethodName}): {perfTimer.ElapsedMilliseconds} ms");
gcSuffix = "-AfterGC";
}
string desktopDir = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
string outputDir = System.IO.Path.Combine(desktopDir, "obrazy_wynikowe");
try { System.IO.Directory.CreateDirectory(outputDir); }
catch (Exception ex) { Console.WriteLine($"\nOSTRZEŻENIE: Nie udało się utworzyć katalogu '{outputDir}': {ex.Message}"); outputDir = "."; }
string sourceFileName = System.IO.Path.GetFileNameWithoutExtension(SourceImagePath);
string methodSuffix = selectedMethodName.Contains("Unsafe") ? "Unsafe" : "Managed2D";
string resultFileName = $"{sourceFileName}-{methodSuffix}-{SelectedFilterName}{gcSuffix}.jpg";
outputFilePath = System.IO.Path.Combine(outputDir, resultFileName);
try
{
resultBmp.Save(outputFilePath, ImageFormat.Jpeg);
Console.WriteLine($"\nObraz wynikowy zapisano jako: {outputFilePath}");
}
catch (Exception ex) { Console.WriteLine($"\nKRYTYCZNY BŁĄD: Nie udało się zapisać pliku '{outputFilePath}': {ex.Message}"); }
}
}
}
catch (ArgumentException ex)
{
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine($"\nBŁĄD KONFIGURACJI/ARGUMENTU: {ex.Message}");
Console.ResetColor();
Console.WriteLine("Sprawdź, czy format obrazu jest obsługiwany (24bppRGB, 32bppArgb, 32bppRgb) i czy 'Allow unsafe code' jest włączone dla trybu 1.");
}
catch (Exception ex)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine($"\nNIESPODZIEWANY BŁĄD APLIKACJI: {ex.Message}");
Console.ResetColor();
}
Console.WriteLine("\nZakończono działanie. Wciśnij Enter, aby zamknąć okno.");
Console.ReadLine();
}
public static unsafe void ApplyConvolution_UnsafeDirect(Bitmap source, Bitmap destination, double[,] kernel, int kernelWidth, int kernelHeight)
{
if (source.PixelFormat != destination.PixelFormat) { throw new ArgumentException("Formaty pikseli obrazów źródłowego i docelowego muszą być identyczne dla trybu Unsafe."); }
PixelFormat pixelFormat = source.PixelFormat;
if (pixelFormat != PixelFormat.Format24bppRgb && pixelFormat != PixelFormat.Format32bppArgb && pixelFormat != PixelFormat.Format32bppRgb) { throw new ArgumentException($"Nieobsługiwany format pikseli '{pixelFormat}' dla trybu Unsafe."); }
int width = source.Width; int height = source.Height;
int kernelOffsetX = kernelWidth / 2; int kernelOffsetY = kernelHeight / 2;
BitmapData sourceData = source.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.ReadOnly, pixelFormat);
BitmapData destData = destination.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.WriteOnly, pixelFormat);
try
{
int bytesPerPixel = Image.GetPixelFormatSize(pixelFormat) / 8;
int stride = sourceData.Stride;
byte* ptrSrcBase = (byte*)sourceData.Scan0; byte* ptrDstBase = (byte*)destData.Scan0;
System.Threading.Tasks.Parallel.For(0, height, y =>
{
byte* ptrDstRow = ptrDstBase + (y * stride);
for (int x = 0; x < width; x++)
{
double rAcc = 0, gAcc = 0, bAcc = 0;
for (int fy = 0; fy < kernelHeight; fy++)
{
int srcY = y + fy - kernelOffsetY; srcY = Math.Max(0, Math.Min(height - 1, srcY));
byte* ptrSrcRow = ptrSrcBase + (srcY * stride);
for (int fx = 0; fx < kernelWidth; fx++)
{
int srcX = x + fx - kernelOffsetX; srcX = Math.Max(0, Math.Min(width - 1, srcX));
byte* ptrSrcPixel = ptrSrcRow + (srcX * bytesPerPixel);
double kernelValue = kernel[fy, fx];
bAcc += ptrSrcPixel[0] * kernelValue; gAcc += ptrSrcPixel[1] * kernelValue; rAcc += ptrSrcPixel[2] * kernelValue;
}
}
int rFinal = Math.Min(Math.Max((int)(rAcc + 0.5), 0), 255);
int gFinal = Math.Min(Math.Max((int)(gAcc + 0.5), 0), 255);
int bFinal = Math.Min(Math.Max((int)(bAcc + 0.5), 0), 255);
byte* ptrDstPixel = ptrDstRow + (x * bytesPerPixel);
ptrDstPixel[0] = (byte)bFinal; ptrDstPixel[1] = (byte)gFinal; ptrDstPixel[2] = (byte)rFinal;
if (bytesPerPixel == 4) { byte* ptrSrcCenterPixel = ptrSrcBase + (y * stride) + (x * bytesPerPixel); ptrDstPixel[3] = ptrSrcCenterPixel[3]; }
}
});
}
finally { source.UnlockBits(sourceData); destination.UnlockBits(destData); }
}
public static void ApplyConvolution_Managed2DBytes(Bitmap source, Bitmap destination, double[,] kernel, int kernelWidth, int kernelHeight)
{
if (source.PixelFormat != destination.PixelFormat) { throw new ArgumentException("Formaty pikseli obrazów źródłowego i docelowego muszą być identyczne dla trybu Managed 2D Array."); }
PixelFormat pixelFormat = source.PixelFormat;
if (pixelFormat != PixelFormat.Format24bppRgb && pixelFormat != PixelFormat.Format32bppArgb && pixelFormat != PixelFormat.Format32bppRgb) { throw new ArgumentException($"Nieobsługiwany format pikseli '{pixelFormat}' dla trybu Managed 2D Array."); }
int width = source.Width; int height = source.Height;
int kernelOffsetX = kernelWidth / 2; int kernelOffsetY = kernelHeight / 2;
int bytesPerPixel = Image.GetPixelFormatSize(pixelFormat) / 8;
BitmapData? sourceData = null; BitmapData? destData = null;
byte[,] sourceBuffer = new byte[height, width * bytesPerPixel]; byte[,] resultBuffer = new byte[height, width * bytesPerPixel];
byte[] rowTransferBuffer = new byte[width * bytesPerPixel];
try
{
sourceData = source.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.ReadOnly, pixelFormat);
destData = destination.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.WriteOnly, pixelFormat);
IntPtr ptrSrcScan0 = sourceData.Scan0; int srcStride = sourceData.Stride;
for (int y = 0; y < height; y++) { IntPtr ptrSrcRow = ptrSrcScan0 + y * srcStride; Marshal.Copy(ptrSrcRow, rowTransferBuffer, 0, width * bytesPerPixel); Buffer.BlockCopy(rowTransferBuffer, 0, sourceBuffer, y * width * bytesPerPixel, width * bytesPerPixel); }
source.UnlockBits(sourceData); sourceData = null;
for (int y = 0; y < height; y++)
{
for (int x = 0; x < width; x++)
{
double rAcc = 0, gAcc = 0, bAcc = 0;
for (int fy = 0; fy < kernelHeight; fy++) { int srcY = y + fy - kernelOffsetY; srcY = Math.Max(0, Math.Min(height - 1, srcY)); for (int fx = 0; fx < kernelWidth; fx++) { int srcX = x + fx - kernelOffsetX; srcX = Math.Max(0, Math.Min(width - 1, srcX)); int bufferColIdx = srcX * bytesPerPixel; double kernelValue = kernel[fy, fx]; bAcc += sourceBuffer[srcY, bufferColIdx] * kernelValue; gAcc += sourceBuffer[srcY, bufferColIdx + 1] * kernelValue; rAcc += sourceBuffer[srcY, bufferColIdx + 2] * kernelValue; } }
int rFinal = Math.Min(Math.Max((int)(rAcc + 0.5), 0), 255); int gFinal = Math.Min(Math.Max((int)(gAcc + 0.5), 0), 255); int bFinal = Math.Min(Math.Max((int)(bAcc + 0.5), 0), 255);
int destBufferColIdx = x * bytesPerPixel;
resultBuffer[y, destBufferColIdx] = (byte)bFinal; resultBuffer[y, destBufferColIdx + 1] = (byte)gFinal; resultBuffer[y, destBufferColIdx + 2] = (byte)rFinal;
if (bytesPerPixel == 4) { resultBuffer[y, destBufferColIdx + 3] = sourceBuffer[y, x * bytesPerPixel + 3]; }
}
}
IntPtr ptrDestScan0 = destData.Scan0; int destStride = destData.Stride;
for (int y = 0; y < height; y++) { Buffer.BlockCopy(resultBuffer, y * width * bytesPerPixel, rowTransferBuffer, 0, width * bytesPerPixel); IntPtr ptrDestRow = ptrDestScan0 + y * destStride; Marshal.Copy(rowTransferBuffer, 0, ptrDestRow, width * bytesPerPixel); }
}
finally { if (sourceData != null) source.UnlockBits(sourceData); if (destData != null) destination.UnlockBits(destData); }
}
public static void NormalizeFilter(double[,] kernel)
{
double sum = 0; foreach (double val in kernel) { sum += val; }
if (Math.Abs(sum) > 1e-6 && Math.Abs(sum - 1.0) > 1e-6)
{
int width = kernel.GetLength(1); int height = kernel.GetLength(0);
for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { kernel[y, x] /= sum; } }
}
}
public static class Filters
{
public static readonly double[,] GaussianBlur5x5 = { { 1, 4, 7, 4, 1 }, { 4, 16, 26, 16, 4 }, { 7, 26, 41, 26, 7 }, { 4, 16, 26, 16, 4 }, { 1, 4, 7, 4, 1 } };
public static readonly double[,] BoxBlur5x5 = { { 0.04, 0.04, 0.04, 0.04, 0.04 }, { 0.04, 0.04, 0.04, 0.04, 0.04 }, { 0.04, 0.04, 0.04, 0.04, 0.04 }, { 0.04, 0.04, 0.04, 0.04, 0.04 }, { 0.04, 0.04, 0.04, 0.04, 0.04 } };
public static readonly double[,] Sharpen5x5 = { { -1, -1, -1, -1, -1 }, { -1, 2, 2, 2, -1 }, { -1, 2, 9, 2, -1 }, { -1, 2, 2, 2, -1 }, { -1, -1, -1, -1, -1 } };
public static readonly double[,] Laplacian5x5 = { { 0, 0, -1, 0, 0 }, { 0, -1, -2, -1, 0 }, { -1, -2, 16, -2, -1 }, { 0, -1, -2, -1, 0 }, { 0, 0, -1, 0, 0 } };
public static readonly double[,] Identity5x5 = { { 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0 }, { 0, 0, 1, 0, 0 }, { 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0 } };
}
}