/
convolution.ts
274 lines (248 loc) · 7.91 KB
/
convolution.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
import {
BorderType as ConvolutionBorderType,
DirectConvolution,
} from 'ml-convolution';
import { Image } from '../Image';
import { getClamp } from '../utils/clamp';
import { extendBorders } from '../utils/extendBorders';
import { getIndex } from '../utils/getIndex';
import { getOutputImage } from '../utils/getOutputImage';
import { BorderType, getBorderInterpolation } from '../utils/interpolateBorder';
import { round } from '../utils/round';
import {
BorderInterpolationFunction,
ClampFunction,
} from '../utils/utils.types';
export interface ConvolutionOptions {
/**
* Specify how the borders should be handled.
* @default `'reflect101'`
*/
borderType?: BorderType;
/**
* Value of the border if BorderType is 'constant'.
* @default `0`
*/
borderValue?: number;
/**
* Whether the kernel should be normalized.
* @default `false`
*/
normalize?: boolean;
/**
* Image to which to output.
*/
out?: Image;
}
/**
* Apply a direct convolution on an image using the specified kernel. The convolution corresponds of a weighted average of the surrounding pixels, the weights being defined in the kernel.
* @param image - The image to process.
* @param kernel - Kernel to use for the convolution. Should be a 2D matrix with odd number of rows and columns.
* @param options - Convolution options.
* @returns The convoluted image.
*/
export function directConvolution(
image: Image,
kernel: number[][],
options: ConvolutionOptions = {},
): Image {
const { borderType = 'reflect101', borderValue = 0 } = options;
const convolutedData = rawDirectConvolution(image, kernel, {
borderType,
borderValue,
});
const newImage = getOutputImage(image, options);
const clamp = getClamp(newImage);
for (let i = 0; i < image.size; i++) {
for (let channel = 0; channel < image.channels; channel++) {
const dataIndex = i * image.channels + channel;
const newValue = round(clamp(convolutedData[dataIndex]));
newImage.setValueByIndex(i, channel, newValue);
}
}
return newImage;
}
/**
* Compute direct convolution of an image and return an array with the raw values.
* @param image - Image to process.
* @param kernel - 2D kernel used for the convolution.
* @param options - Convolution options.
* @returns Array with the raw convoluted values.
*/
export function rawDirectConvolution(
image: Image,
kernel: number[][],
options: ConvolutionOptions = {},
): Float64Array {
const { borderType = 'reflect101', borderValue = 0 } = options;
const interpolateBorder = getBorderInterpolation(borderType, borderValue);
const result = new Float64Array(image.size * image.channels);
for (let channel = 0; channel < image.channels; channel++) {
for (let row = 0; row < image.height; row++) {
for (let column = 0; column < image.width; column++) {
const index = getIndex(column, row, image, channel);
result[index] = computeConvolutionValue(
column,
row,
channel,
image,
kernel,
interpolateBorder,
{ returnRawValue: true },
);
}
}
}
return result;
}
/**
* Compute the separable convolution of an image.
* @param image - Image to convolute.
* @param kernelX - Kernel along x axis.
* @param kernelY - Kernel along y axis.
* @param options - Convolution options.
* @returns The convoluted image.
*/
export function separableConvolution(
image: Image,
kernelX: number[],
kernelY: number[],
options: ConvolutionOptions = {},
): Image {
const { normalize, borderType = 'reflect101', borderValue = 0 } = options;
if (normalize) {
[kernelX, kernelY] = normalizeSeparatedKernel(kernelX, kernelY);
}
const doubleKernelOffsetX = kernelX.length - 1;
const kernelOffsetX = doubleKernelOffsetX / 2;
const doubleKernelOffsetY = kernelY.length - 1;
const kernelOffsetY = doubleKernelOffsetY / 2;
const extendedImage = extendBorders(image, {
horizontal: kernelOffsetX,
vertical: kernelOffsetY,
borderType,
borderValue,
});
const newImage = Image.createFrom(image);
const clamp = getClamp(newImage);
const rowConvolution = new DirectConvolution(
extendedImage.width,
kernelX,
ConvolutionBorderType.CUT,
);
const columnConvolution = new DirectConvolution(
extendedImage.height,
kernelY,
ConvolutionBorderType.CUT,
);
const rowData = new Float64Array(extendedImage.width);
const columnData = new Float64Array(extendedImage.height);
const convolvedData = new Float64Array(
// Use `image.width` because convolution with BorderType.CUT reduces the size of the convolved data.
image.width * extendedImage.height,
);
for (let channel = 0; channel < extendedImage.channels; channel++) {
for (let row = 0; row < extendedImage.height; row++) {
for (let column = 0; column < extendedImage.width; column++) {
rowData[column] = extendedImage.getValue(column, row, channel);
}
const convolvedRow = rowConvolution.convolve(rowData);
for (let column = 0; column < image.width; column++) {
convolvedData[row * image.width + column] = convolvedRow[column];
}
}
for (let column = 0; column < image.width; column++) {
for (let row = 0; row < extendedImage.height; row++) {
columnData[row] = convolvedData[row * image.width + column];
}
const convolvedColumn = columnConvolution.convolve(columnData);
for (let row = 0; row < image.height; row++) {
newImage.setValue(
column,
row,
channel,
round(clamp(convolvedColumn[row])),
);
}
}
}
return newImage;
}
export interface ComputeConvolutionValueOptions {
/**
* Specify wether the return value should not be clamped and rounded.
*/
returnRawValue?: boolean;
/**
* If the value has to be clamped, specify the clamping function.
*/
clamp?: ClampFunction;
}
/**
* Compute the convolution of a value of a pixel in an image.
* @param column - Column of the pixel.
* @param row - Row of the pixel.
* @param channel - Channel to process.
* @param image - Image to process.
* @param kernel - Kernel for the convolutions.
* @param interpolateBorder - Function to interpolate the border pixels.
* @param options - Compute convolution value options.
* @returns The convoluted value.
*/
export function computeConvolutionValue(
column: number,
row: number,
channel: number,
image: Image,
kernel: number[][],
interpolateBorder: BorderInterpolationFunction,
options: ComputeConvolutionValueOptions = {},
): number {
let { clamp } = options;
const { returnRawValue = false } = options;
if (returnRawValue) {
clamp = undefined;
}
let val = 0;
const kernelWidth = kernel[0].length;
const kernelHeight = kernel.length;
const kernelOffsetX = (kernelWidth - 1) / 2;
const kernelOffsetY = (kernelHeight - 1) / 2;
for (let kY = 0; kY < kernelHeight; kY++) {
for (let kX = 0; kX < kernelWidth; kX++) {
const kernelValue = kernel[kY][kX];
val +=
kernelValue *
interpolateBorder(
column + kX - kernelOffsetX,
row + kY - kernelOffsetY,
channel,
image,
);
}
}
if (!clamp) {
return val;
} else {
return round(clamp(val));
}
}
/**
* Normalize a separated kernel.
* @param kernelX - Horizontal component of the separated kernel.
* @param kernelY - Vertical component of the separated kernel.
* @returns The normalized kernel.
*/
function normalizeSeparatedKernel(
kernelX: number[],
kernelY: number[],
): [number[], number[]] {
const sumKernelX = kernelX.reduce((prev, current) => prev + current, 0);
const sumKernelY = kernelY.reduce((prev, current) => prev + current, 0);
const prod = sumKernelX * sumKernelY;
if (prod < 0) {
throw new RangeError('this separated kernel cannot be normalized');
}
const factor = 1 / Math.sqrt(Math.abs(prod));
return [kernelX.map((v) => v * factor), kernelY.map((v) => v * factor)];
}