/ concept-collection / numbl-image-filter
Sign in
concept-collection / numbl-image-filter
numbl-image-filter / src / examples.ts
108 lines · 2.4 KBBlameHistoryRaw
1/**
2 * Preset numbl filter scripts.
3 *
4 * Each is a function `out = filterImage(img)` where:
5 * - img : H x W x 3 array of doubles in [0, 255] (RGB)
6 * - out : H x W x 3 (color) or H x W (grayscale) array in [0, 255]
7 *
8 * MATLAB syntax (this is what numbl runs). Values outside 0-255 are clamped
9 * when the image is displayed.
10 */
12export interface Example {
13 name: string;
14 code: string;
17export const EXAMPLES: Example[] = [
18 {
19 name: "Invert",
20 code: `function out = filterImage(img)
21 % Invert each channel
22 out = 255 - img;
23end
24`,
25 },
26 {
27 name: "Grayscale",
28 code: `function out = filterImage(img)
29 % Luminance-weighted grayscale, copied back to 3 channels
30 g = 0.2989 * img(:,:,1) + 0.5870 * img(:,:,2) + 0.1140 * img(:,:,3);
31 out = cat(3, g, g, g);
32end
33`,
34 },
35 {
36 name: "Brighten",
37 code: `function out = filterImage(img)
38 % Scale brightness (min keeps it in range)
39 out = min(255, img * 1.4);
40end
41`,
42 },
43 {
44 name: "Sepia",
45 code: `function out = filterImage(img)
46 r = img(:,:,1); g = img(:,:,2); b = img(:,:,3);
47 sr = 0.393*r + 0.769*g + 0.189*b;
48 sg = 0.349*r + 0.686*g + 0.168*b;
49 sb = 0.272*r + 0.534*g + 0.131*b;
50 out = min(255, cat(3, sr, sg, sb));
51end
52`,
53 },
54 {
55 name: "Swap R/B channels",
56 code: `function out = filterImage(img)
57 % Reorder the 3rd dimension: RGB -> BGR
58 out = img(:, :, [3 2 1]);
59end
60`,
61 },
62 {
63 name: "Posterize",
64 code: `function out = filterImage(img)
65 % Snap each channel to a few levels
66 levels = 4;
67 step = 255 / (levels - 1);
68 out = round(img / step) * step;
69end
70`,
71 },
72 {
73 name: "Increase contrast",
74 code: `function out = filterImage(img)
75 % Push values away from mid-gray (128)
76 k = 1.6;
77 out = min(255, max(0, (img - 128) * k + 128));
78end
79`,
80 },
81 {
82 name: "Sobel edges",
83 code: `function out = filterImage(img)
84 % Edge magnitude on the grayscale image
85 g = 0.2989*img(:,:,1) + 0.5870*img(:,:,2) + 0.1140*img(:,:,3);
86 kx = [-1 0 1; -2 0 2; -1 0 1];
87 ky = [-1 -2 -1; 0 0 0; 1 2 1];
88 gx = conv2(g, kx, 'same');
89 gy = conv2(g, ky, 'same');
90 out = min(255, sqrt(gx.^2 + gy.^2));
91end
92`,
93 },
94 {
95 name: "Box blur",
96 code: `function out = filterImage(img)
97 % 5x5 average blur, applied to each channel
98 k = ones(5, 5) / 25;
99 out = zeros(size(img));
100 for c = 1:3
101 out(:,:,c) = conv2(img(:,:,c), k, 'same');
102 end
103end
104`,
105 },
106];
108export const DEFAULT_SCRIPT = EXAMPLES[0].code;
moveopenescclose