/
ErrorDither.cs
232 lines (200 loc) · 8.35 KB
/
ErrorDither.cs
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
// Copyright (c) Six Labors.
// Licensed under the Six Labors Split License.
using System.Numerics;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using SixLabors.ImageSharp.Memory;
using SixLabors.ImageSharp.PixelFormats;
using SixLabors.ImageSharp.Processing.Processors.Quantization;
namespace SixLabors.ImageSharp.Processing.Processors.Dithering;
/// <summary>
/// An error diffusion dithering implementation.
/// <see href="http://www.efg2.com/Lab/Library/ImageProcessing/DHALF.TXT"/>
/// </summary>
public readonly partial struct ErrorDither : IDither, IEquatable<ErrorDither>, IEquatable<IDither>
{
private readonly int offset;
private readonly DenseMatrix<float> matrix;
/// <summary>
/// Initializes a new instance of the <see cref="ErrorDither"/> struct.
/// </summary>
/// <param name="matrix">The diffusion matrix.</param>
/// <param name="offset">The starting offset within the matrix.</param>
[MethodImpl(InliningOptions.ShortMethod)]
public ErrorDither(in DenseMatrix<float> matrix, int offset)
{
Guard.MustBeGreaterThan(offset, 0, nameof(offset));
this.matrix = matrix;
this.offset = offset;
}
/// <summary>
/// Compares the two <see cref="ErrorDither"/> instances to determine whether they are equal.
/// </summary>
/// <param name="left">The first source instance.</param>
/// <param name="right">The second source instance.</param>
/// <returns>The <see cref="bool"/>.</returns>
public static bool operator ==(IDither left, ErrorDither right)
=> right == left;
/// <summary>
/// Compares the two <see cref="ErrorDither"/> instances to determine whether they are unequal.
/// </summary>
/// <param name="left">The first source instance.</param>
/// <param name="right">The second source instance.</param>
/// <returns>The <see cref="bool"/>.</returns>
public static bool operator !=(IDither left, ErrorDither right)
=> !(right == left);
/// <summary>
/// Compares the two <see cref="ErrorDither"/> instances to determine whether they are equal.
/// </summary>
/// <param name="left">The first source instance.</param>
/// <param name="right">The second source instance.</param>
/// <returns>The <see cref="bool"/>.</returns>
public static bool operator ==(ErrorDither left, IDither right)
=> left.Equals(right);
/// <summary>
/// Compares the two <see cref="ErrorDither"/> instances to determine whether they are unequal.
/// </summary>
/// <param name="left">The first source instance.</param>
/// <param name="right">The second source instance.</param>
/// <returns>The <see cref="bool"/>.</returns>
public static bool operator !=(ErrorDither left, IDither right)
=> !(left == right);
/// <summary>
/// Compares the two <see cref="ErrorDither"/> instances to determine whether they are equal.
/// </summary>
/// <param name="left">The first source instance.</param>
/// <param name="right">The second source instance.</param>
/// <returns>The <see cref="bool"/>.</returns>
public static bool operator ==(ErrorDither left, ErrorDither right)
=> left.Equals(right);
/// <summary>
/// Compares the two <see cref="ErrorDither"/> instances to determine whether they are unequal.
/// </summary>
/// <param name="left">The first source instance.</param>
/// <param name="right">The second source instance.</param>
/// <returns>The <see cref="bool"/>.</returns>
public static bool operator !=(ErrorDither left, ErrorDither right)
=> !(left == right);
/// <inheritdoc/>
[MethodImpl(InliningOptions.ShortMethod)]
public void ApplyQuantizationDither<TFrameQuantizer, TPixel>(
ref TFrameQuantizer quantizer,
ImageFrame<TPixel> source,
IndexedImageFrame<TPixel> destination,
Rectangle bounds)
where TFrameQuantizer : struct, IQuantizer<TPixel>
where TPixel : unmanaged, IPixel<TPixel>
{
if (this == default)
{
ThrowDefaultInstance();
}
int offsetY = bounds.Top;
int offsetX = bounds.Left;
float scale = quantizer.Options.DitherScale;
Buffer2D<TPixel> sourceBuffer = source.PixelBuffer;
for (int y = 0; y < destination.Height; y++)
{
ReadOnlySpan<TPixel> sourceRow = sourceBuffer.DangerousGetRowSpan(y + offsetY);
Span<byte> destinationRow = destination.GetWritablePixelRowSpanUnsafe(y);
for (int x = 0; x < destinationRow.Length; x++)
{
TPixel sourcePixel = sourceRow[x + offsetX];
destinationRow[x] = quantizer.GetQuantizedColor(sourcePixel, out TPixel transformed);
this.Dither(source, bounds, sourcePixel, transformed, x, y, scale);
}
}
}
/// <inheritdoc/>
[MethodImpl(InliningOptions.ShortMethod)]
public void ApplyPaletteDither<TPaletteDitherImageProcessor, TPixel>(
in TPaletteDitherImageProcessor processor,
ImageFrame<TPixel> source,
Rectangle bounds)
where TPaletteDitherImageProcessor : struct, IPaletteDitherImageProcessor<TPixel>
where TPixel : unmanaged, IPixel<TPixel>
{
if (this == default)
{
ThrowDefaultInstance();
}
Buffer2D<TPixel> sourceBuffer = source.PixelBuffer;
float scale = processor.DitherScale;
for (int y = bounds.Top; y < bounds.Bottom; y++)
{
ref TPixel sourceRowRef = ref MemoryMarshal.GetReference(sourceBuffer.DangerousGetRowSpan(y));
for (int x = bounds.Left; x < bounds.Right; x++)
{
ref TPixel sourcePixel = ref Unsafe.Add(ref sourceRowRef, (uint)x);
TPixel transformed = Unsafe.AsRef(processor).GetPaletteColor(sourcePixel);
this.Dither(source, bounds, sourcePixel, transformed, x, y, scale);
sourcePixel = transformed;
}
}
}
// Internal for AOT
[MethodImpl(InliningOptions.ShortMethod)]
internal TPixel Dither<TPixel>(
ImageFrame<TPixel> image,
Rectangle bounds,
TPixel source,
TPixel transformed,
int x,
int y,
float scale)
where TPixel : unmanaged, IPixel<TPixel>
{
// Equal? Break out as there's no error to pass.
if (source.Equals(transformed))
{
return transformed;
}
// Calculate the error
Vector4 error = (source.ToVector4() - transformed.ToVector4()) * scale;
int offset = this.offset;
DenseMatrix<float> matrix = this.matrix;
Buffer2D<TPixel> imageBuffer = image.PixelBuffer;
// Loop through and distribute the error amongst neighboring pixels.
for (int row = 0, targetY = y; row < matrix.Rows; row++, targetY++)
{
if (targetY >= bounds.Bottom)
{
continue;
}
Span<TPixel> rowSpan = imageBuffer.DangerousGetRowSpan(targetY);
for (int col = 0; col < matrix.Columns; col++)
{
int targetX = x + (col - offset);
if (targetX < bounds.Left || targetX >= bounds.Right)
{
continue;
}
float coefficient = matrix[row, col];
if (coefficient == 0)
{
continue;
}
ref TPixel pixel = ref rowSpan[targetX];
Vector4 result = pixel.ToVector4();
result += error * coefficient;
pixel.FromVector4(result);
}
}
return transformed;
}
/// <inheritdoc/>
public override bool Equals(object? obj)
=> obj is ErrorDither dither && this.Equals(dither);
/// <inheritdoc/>
public bool Equals(ErrorDither other)
=> this.offset == other.offset && this.matrix.Equals(other.matrix);
/// <inheritdoc/>
public bool Equals(IDither? other)
=> this.Equals((object?)other);
/// <inheritdoc/>
public override int GetHashCode()
=> HashCode.Combine(this.offset, this.matrix);
[MethodImpl(InliningOptions.ColdPath)]
private static void ThrowDefaultInstance()
=> throw new ImageProcessingException("Cannot use the default value type instance to dither.");
}