-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathimages.html
1120 lines (985 loc) · 61.8 KB
/
images.html
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
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
<head>
<!-- 2022-09-01 Thu 09:58 -->
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Image Manipulation</title>
<meta name="author" content="NUS15260-12-davfrei" />
<meta name="generator" content="Org Mode" />
<style>
#content { max-width: 60em; margin: auto; }
.title { text-align: center;
margin-bottom: .2em; }
.subtitle { text-align: center;
font-size: medium;
font-weight: bold;
margin-top:0; }
.todo { font-family: monospace; color: red; }
.done { font-family: monospace; color: green; }
.priority { font-family: monospace; color: orange; }
.tag { background-color: #eee; font-family: monospace;
padding: 2px; font-size: 80%; font-weight: normal; }
.timestamp { color: #bebebe; }
.timestamp-kwd { color: #5f9ea0; }
.org-right { margin-left: auto; margin-right: 0px; text-align: right; }
.org-left { margin-left: 0px; margin-right: auto; text-align: left; }
.org-center { margin-left: auto; margin-right: auto; text-align: center; }
.underline { text-decoration: underline; }
#postamble p, #preamble p { font-size: 90%; margin: .2em; }
p.verse { margin-left: 3%; }
pre {
border: 1px solid #e6e6e6;
border-radius: 3px;
background-color: #f2f2f2;
padding: 8pt;
font-family: monospace;
overflow: auto;
margin: 1.2em;
}
pre.src {
position: relative;
overflow: auto;
}
pre.src:before {
display: none;
position: absolute;
top: -8px;
right: 12px;
padding: 3px;
color: #555;
background-color: #f2f2f299;
}
pre.src:hover:before { display: inline; margin-top: 14px;}
/* Languages per Org manual */
pre.src-asymptote:before { content: 'Asymptote'; }
pre.src-awk:before { content: 'Awk'; }
pre.src-authinfo::before { content: 'Authinfo'; }
pre.src-C:before { content: 'C'; }
/* pre.src-C++ doesn't work in CSS */
pre.src-clojure:before { content: 'Clojure'; }
pre.src-css:before { content: 'CSS'; }
pre.src-D:before { content: 'D'; }
pre.src-ditaa:before { content: 'ditaa'; }
pre.src-dot:before { content: 'Graphviz'; }
pre.src-calc:before { content: 'Emacs Calc'; }
pre.src-emacs-lisp:before { content: 'Emacs Lisp'; }
pre.src-fortran:before { content: 'Fortran'; }
pre.src-gnuplot:before { content: 'gnuplot'; }
pre.src-haskell:before { content: 'Haskell'; }
pre.src-hledger:before { content: 'hledger'; }
pre.src-java:before { content: 'Java'; }
pre.src-js:before { content: 'Javascript'; }
pre.src-latex:before { content: 'LaTeX'; }
pre.src-ledger:before { content: 'Ledger'; }
pre.src-lisp:before { content: 'Lisp'; }
pre.src-lilypond:before { content: 'Lilypond'; }
pre.src-lua:before { content: 'Lua'; }
pre.src-matlab:before { content: 'MATLAB'; }
pre.src-mscgen:before { content: 'Mscgen'; }
pre.src-ocaml:before { content: 'Objective Caml'; }
pre.src-octave:before { content: 'Octave'; }
pre.src-org:before { content: 'Org mode'; }
pre.src-oz:before { content: 'OZ'; }
pre.src-plantuml:before { content: 'Plantuml'; }
pre.src-processing:before { content: 'Processing.js'; }
pre.src-python:before { content: 'Python'; }
pre.src-R:before { content: 'R'; }
pre.src-ruby:before { content: 'Ruby'; }
pre.src-sass:before { content: 'Sass'; }
pre.src-scheme:before { content: 'Scheme'; }
pre.src-screen:before { content: 'Gnu Screen'; }
pre.src-sed:before { content: 'Sed'; }
pre.src-sh:before { content: 'shell'; }
pre.src-sql:before { content: 'SQL'; }
pre.src-sqlite:before { content: 'SQLite'; }
/* additional languages in org.el's org-babel-load-languages alist */
pre.src-forth:before { content: 'Forth'; }
pre.src-io:before { content: 'IO'; }
pre.src-J:before { content: 'J'; }
pre.src-makefile:before { content: 'Makefile'; }
pre.src-maxima:before { content: 'Maxima'; }
pre.src-perl:before { content: 'Perl'; }
pre.src-picolisp:before { content: 'Pico Lisp'; }
pre.src-scala:before { content: 'Scala'; }
pre.src-shell:before { content: 'Shell Script'; }
pre.src-ebnf2ps:before { content: 'ebfn2ps'; }
/* additional language identifiers per "defun org-babel-execute"
in ob-*.el */
pre.src-cpp:before { content: 'C++'; }
pre.src-abc:before { content: 'ABC'; }
pre.src-coq:before { content: 'Coq'; }
pre.src-groovy:before { content: 'Groovy'; }
/* additional language identifiers from org-babel-shell-names in
ob-shell.el: ob-shell is the only babel language using a lambda to put
the execution function name together. */
pre.src-bash:before { content: 'bash'; }
pre.src-csh:before { content: 'csh'; }
pre.src-ash:before { content: 'ash'; }
pre.src-dash:before { content: 'dash'; }
pre.src-ksh:before { content: 'ksh'; }
pre.src-mksh:before { content: 'mksh'; }
pre.src-posh:before { content: 'posh'; }
/* Additional Emacs modes also supported by the LaTeX listings package */
pre.src-ada:before { content: 'Ada'; }
pre.src-asm:before { content: 'Assembler'; }
pre.src-caml:before { content: 'Caml'; }
pre.src-delphi:before { content: 'Delphi'; }
pre.src-html:before { content: 'HTML'; }
pre.src-idl:before { content: 'IDL'; }
pre.src-mercury:before { content: 'Mercury'; }
pre.src-metapost:before { content: 'MetaPost'; }
pre.src-modula-2:before { content: 'Modula-2'; }
pre.src-pascal:before { content: 'Pascal'; }
pre.src-ps:before { content: 'PostScript'; }
pre.src-prolog:before { content: 'Prolog'; }
pre.src-simula:before { content: 'Simula'; }
pre.src-tcl:before { content: 'tcl'; }
pre.src-tex:before { content: 'TeX'; }
pre.src-plain-tex:before { content: 'Plain TeX'; }
pre.src-verilog:before { content: 'Verilog'; }
pre.src-vhdl:before { content: 'VHDL'; }
pre.src-xml:before { content: 'XML'; }
pre.src-nxml:before { content: 'XML'; }
/* add a generic configuration mode; LaTeX export needs an additional
(add-to-list 'org-latex-listings-langs '(conf " ")) in .emacs */
pre.src-conf:before { content: 'Configuration File'; }
table { border-collapse:collapse; }
caption.t-above { caption-side: top; }
caption.t-bottom { caption-side: bottom; }
td, th { vertical-align:top; }
th.org-right { text-align: center; }
th.org-left { text-align: center; }
th.org-center { text-align: center; }
td.org-right { text-align: right; }
td.org-left { text-align: left; }
td.org-center { text-align: center; }
dt { font-weight: bold; }
.footpara { display: inline; }
.footdef { margin-bottom: 1em; }
.figure { padding: 1em; }
.figure p { text-align: center; }
.equation-container {
display: table;
text-align: center;
width: 100%;
}
.equation {
vertical-align: middle;
}
.equation-label {
display: table-cell;
text-align: right;
vertical-align: middle;
}
.inlinetask {
padding: 10px;
border: 2px solid gray;
margin: 10px;
background: #ffffcc;
}
#org-div-home-and-up
{ text-align: right; font-size: 70%; white-space: nowrap; }
textarea { overflow-x: auto; }
.linenr { font-size: smaller }
.code-highlighted { background-color: #ffff00; }
.org-info-js_info-navigation { border-style: none; }
#org-info-js_console-label
{ font-size: 10px; font-weight: bold; white-space: nowrap; }
.org-info-js_search-highlight
{ background-color: #ffff00; color: #000000; font-weight: bold; }
.org-svg { }
</style>
<link rel="stylesheet" href="https://quantumish.github.io/admonition.css">
<link rel="stylesheet" href="https://quantumish.github.io/org.css">
<link rel="stylesheet" href="https://quantumish.github.io/org-htmlize.css">
<style>
/* From: https://endlessparentheses.com/public/css/endless.css */
/* See also: https://meta.superuser.com/questions/4788/css-for-the-new-kbd-style */
kbd
{
-moz-border-radius: 6px;
-moz-box-shadow: 0 1px 0 rgba(0,0,0,0.2),0 0 0 2px #fff inset;
-webkit-border-radius: 6px;
-webkit-box-shadow: 0 1px 0 rgba(0,0,0,0.2),0 0 0 2px #fff inset;
background-color: #f7f7f7;
border: 1px solid #ccc;
border-radius: 6px;
box-shadow: 0 1px 0 rgba(0,0,0,0.2),0 0 0 2px #fff inset;
color: #333;
display: inline-block;
font-family: 'Droid Sans Mono', monospace;
font-size: 80%;
font-weight: normal;
line-height: inherit;
margin: 0 .1em;
padding: .08em .4em;
text-shadow: 0 1px 0 #fff;
word-spacing: -4px;
box-shadow: 2px 2px 2px #222; /* MA: An extra I've added. */
}
</style>
<link rel="stylesheet" type="text/css" href="https://alhassy.github.io/org-special-block-extras/tooltipster/dist/css/tooltipster.bundle.min.css"/>
<link rel="stylesheet" type="text/css" href="https://alhassy.github.io/org-special-block-extras/tooltipster/dist/css/plugins/tooltipster/sideTip/themes/tooltipster-sideTip-punk.min.css" />
<script type="text/javascript">
if (typeof jQuery == 'undefined') {
document.write(unescape('%3Cscript src="https://code.jquery.com/jquery-1.10.0.min.js"%3E%3C/script%3E'));
}
</script>
<script type="text/javascript" src="https://alhassy.github.io/org-special-block-extras/tooltipster/dist/js/tooltipster.bundle.min.js"></script>
<script>
$(document).ready(function() {
$('.tooltip').tooltipster({
theme: 'tooltipster-punk',
contentAsHTML: true,
animation: 'grow',
delay: [100,500],
// trigger: 'click'
trigger: 'custom',
triggerOpen: {
mouseenter: true
},
triggerClose: {
originClick: true,
scroll: true
}
});
});
</script>
<style>
abbr {color: red;}
.tooltip { border-bottom: 1px dotted #000;
color:red;
text-decoration: none;}
</style>
</head>
<body>
<div id="content" class="content">
<h1 class="title">Image Manipulation</h1>
<p>
This is my writeup for the first assignment! Please run the associated code in the root directory first by running:
</p>
<div class="org-src-container">
<pre class="src src-sh"><span class="org-comment-delimiter"># </span><span class="org-comment">download needed images</span>
wget https://i.imgur.com/fyDOvfz.jpg image1.jpg
wget https://i.imgur.com/0DANhnn.jpg image2.jpg
<span class="org-comment-delimiter"># </span><span class="org-comment">run generator script for this assignment</span>
cargo run --example image-manipulation
</pre>
</div>
<p>
This will generate the images referenced by this document. Alternatively, see the online copy <a href="https://quantumish.github.io/images.html">here</a> (if <i>this</i> is the online copy, you can ignore all of this).
</p>
<p>
I used <code>image-rs</code> for my base implementation of the exercises: it's a handy high level library for working with images in Rust, although its abstractions come with some annoyances sometimes.
</p>
<div id="outline-container-org6894541" class="outline-2">
<h2 id="org6894541">Exercise 1: dimming</h2>
<div class="outline-text-2" id="text-org6894541">
<blockquote>
<p>
Recall from lecture that the value of each pixel represents its brightness. Implement a function that takes in an image and returns the same image, but half as bright as the original image.
</p>
</blockquote>
<p>
Writing such a function is pretty straightforward - although I do a bit more than I have to. I chose to preemptively allocate the correct amount of space for the vector so that I wouldn't have to lose a bit of time to reallocation. I then add all the values to the vector using <code>extend</code> to consume the entire iterator. I also opted to take a integer "division factor" instead of just an arbitrary fraction, since then I could stick to simple integer division and not worry about casting to a float and back.
</p>
<div class="org-src-container">
<pre class="src src-rust"><span class="org-keyword">pub</span> <span class="org-keyword">fn</span> <span class="org-function-name">dim</span>(<span class="org-variable-name">img</span>: <span class="org-type">DynamicImage</span>, <span class="org-variable-name">factor</span>: <span class="org-type">u8</span>) -> <span class="org-type">Result</span><<span class="org-type">DynamicImage</span>> {
<span class="org-keyword">let</span> (w, h) = img.dimensions();
<span class="org-keyword">let</span> <span class="org-keyword">mut</span> <span class="org-variable-name">out</span>: <span class="org-type">Vec</span><<span class="org-type">u8</span>> = <span class="org-type">Vec</span>::with_capacity((w*h*3) <span class="org-keyword">as</span> <span class="org-type">usize</span>);
out.extend(img.as_bytes().iter().map(|i| i/factor));
<span class="org-keyword">let</span> <span class="org-variable-name">buf</span> = <span class="org-type">ImageBuffer</span>::from_vec(w, h, out)
.ok_or(<span class="org-preprocessor">anyhow!</span>(<span class="org-string">"Couldn't convert buffer."</span>))<span class="org-rust-question-mark">?</span>;
<span class="org-type">Ok</span>(<span class="org-type">DynamicImage</span>::<span class="org-type">ImageRgb8</span>(buf))
}
</pre>
</div>
<div id="org9a46a96" class="figure">
<p><img src="./imgs/dim.png" alt="dim.png" />
</p>
</div>
</div>
<div id="outline-container-orgfb9e99c" class="outline-3">
<h3 id="orgfb9e99c">Optimized</h3>
<div class="outline-text-3" id="text-orgfb9e99c">
<p>
How do we make this function quick? It's actually not that hard! The compiler does most of the work for us - and in general trying to out-optimize the compiler can be a long and painful battle not often worth fighting. The one big change though is that we get a whole lot simpler: let the user handle the <code>image-rs</code> stuff, and just give the the function an input and output buffer.
</p>
<div class="org-src-container">
<pre class="src src-rust"><span class="org-keyword">pub</span> <span class="org-keyword">fn</span> <span class="org-function-name">dim</span>(<span class="org-variable-name">bytes</span>: <span class="org-rust-ampersand">&</span>[<span class="org-type">u8</span>], <span class="org-variable-name">out</span>: <span class="org-rust-ampersand">&</span><span class="org-keyword">mut</span> [<span class="org-type">u8</span>], <span class="org-variable-name">factor</span>: <span class="org-type">u8</span>) {
<span class="org-keyword">for</span> (n, i) <span class="org-keyword">in</span> bytes.iter().enumerate() {
out[n] = i/factor;
}
}
</pre>
</div>
<p>
Glancing at the assembly output of <code>cargo asm</code> (an awesome tool you can install with <code>cargo install cargo-asm</code>!) we might be disappointed to see that the compiler is <i>not</i> using SIMD instructions to dim many bytes of RGB at once!
</p>
<div class="org-src-container">
<pre class="src src-asm"><span class="org-comment-delimiter">; </span><span class="org-comment">... stuff above</span>
<span class="org-comment-delimiter">; </span><span class="org-comment">out[n] = i/factor;</span>
<span class="org-function-name">ldrb</span> <span class="org-keyword">w11</span>, [x9]
<span class="org-function-name">add</span> <span class="org-keyword">x12</span>, x9, #1
<span class="org-function-name">and</span> <span class="org-keyword">w9</span>, w4, #0xff
<span class="org-function-name">udiv</span> <span class="org-keyword">w9</span>, w11, w9 <span class="org-comment-delimiter">; </span><span class="org-comment"><-- only a udiv?? really?</span>
<span class="org-comment-delimiter">; </span><span class="org-comment">stuff below...</span>
</pre>
</div>
<p>
This is likely due to the fact that ARM's NEON intrinsics (their version of SIMD) don't have an instruction for unsigned 8-bit integer divide, which I would only find out later.
</p>
<p>
We can do a bit better though, since the assignment does specifically say we want to dim by half, and so the generality of a <code>factor</code> argument is technically not needed. We can then instead hard code division by 2 into a <code>dim2</code> function like so:
</p>
<div class="org-src-container">
<pre class="src src-rust"><span class="org-keyword">pub</span> <span class="org-keyword">fn</span> <span class="org-function-name">dim2</span>(<span class="org-variable-name">bytes</span>: <span class="org-rust-ampersand">&</span>[<span class="org-type">u8</span>], <span class="org-variable-name">out</span>: <span class="org-rust-ampersand">&</span><span class="org-keyword">mut</span> [<span class="org-type">u8</span>]) {
<span class="org-keyword">for</span> (n, i) <span class="org-keyword">in</span> bytes.iter().enumerate() {
out[n] = i/2;
}
}
</pre>
</div>
<p>
Looking at the assembly output there shows that it now uses the SIMD we desired: dimming 16 bytes of the image at a time! It also uses a slightly faster right shift instruction, which makes sense since dividing by two is equivalent to shifting a number right in binary (just like how 12/10 = 1.2)!
</p>
<div class="org-src-container">
<pre class="src src-asm"><span class="org-comment-delimiter">; </span><span class="org-comment">... stuff above</span>
<span class="org-comment-delimiter">; </span><span class="org-comment">out[n] = i/2;</span>
<span class="org-function-name">ldr</span> <span class="org-keyword">q0</span>, [x10], #16
<span class="org-function-name">ushr</span>.16b v0, v0, #1 <span class="org-comment-delimiter">; </span><span class="org-comment"><-- yay! SIMD and a faster instruction</span>
<span class="org-comment-delimiter">; </span><span class="org-comment">stuff below ...</span>
</pre>
</div>
<p>
We can further demonstrate the improvement by using <code>criterion</code>, another great Rust tool for benchmarking. Let's quickly try generating random images of exponentially increasing size and see how they compare!
</p>
<p>
You may notice I put the number two in a <code>black_box</code>, which is a utility from <code>criterion</code> that makes values opaque to the compiler so it doesn't be too clever when optimizing. It's likely an overly paranoid usage here though, as as it shouldn't be able to do much about it.
</p>
<div class="org-src-container">
<pre class="src src-rust"><span class="org-keyword">fn</span> <span class="org-function-name">bench_dims</span>(<span class="org-variable-name">c</span>: <span class="org-rust-ampersand">&</span><span class="org-keyword">mut</span> <span class="org-type">Criterion</span>) {
<span class="org-keyword">let</span> <span class="org-keyword">mut</span> <span class="org-variable-name">group</span> = c.benchmark_group(<span class="org-string">"Dimming"</span>);
<span class="org-keyword">for</span> <span class="org-variable-name">sz</span> <span class="org-keyword">in</span> 8..14 {
<span class="org-keyword">let</span> <span class="org-variable-name">sz</span> = 2_<span class="org-type">u32</span>.pow(sz);
<span class="org-keyword">let</span> <span class="org-variable-name">img</span> = <span class="org-constant">utils</span>::gen_image(sz);
group.bench_with_input(<span class="org-type">BenchmarkId</span>::new(<span class="org-string">"dim"</span>, sz), <span class="org-rust-ampersand">&</span>img, |b, i| {
<span class="org-keyword">let</span> (w, h) = i.dimensions();
<span class="org-keyword">let</span> <span class="org-keyword">mut</span> <span class="org-variable-name">out</span>: <span class="org-type">Vec</span><<span class="org-type">u8</span>> = <span class="org-preprocessor">vec!</span>[0; (w*h*3) <span class="org-keyword">as</span> <span class="org-type">usize</span>];
<span class="org-keyword">let</span> <span class="org-variable-name">bytes</span> = i.as_bytes();
b.iter(|| <span class="org-constant">optimized</span>::<span class="org-constant">cpu</span>::dim(<span class="org-rust-ampersand">&</span>bytes[..], <span class="org-rust-ampersand">&</span><span class="org-keyword">mut</span> out[..], black_box(2)))
});
group.bench_with_input(<span class="org-type">BenchmarkId</span>::new(<span class="org-string">"dim2"</span>, sz), <span class="org-rust-ampersand">&</span>img, |b, i| {
<span class="org-keyword">let</span> (w, h) = i.dimensions();
<span class="org-keyword">let</span> <span class="org-keyword">mut</span> <span class="org-variable-name">out</span>: <span class="org-type">Vec</span><<span class="org-type">u8</span>> = <span class="org-preprocessor">vec!</span>[0; (w*h*3) <span class="org-keyword">as</span> <span class="org-type">usize</span>];
<span class="org-keyword">let</span> <span class="org-variable-name">bytes</span> = i.as_bytes();
b.iter(|| <span class="org-constant">optimized</span>::<span class="org-constant">cpu</span>::dim2(<span class="org-rust-ampersand">&</span>bytes[..], <span class="org-rust-ampersand">&</span><span class="org-keyword">mut</span> out[..]))
});
}
}
</pre>
</div>
<p>
We can then visualize the difference:
</p>
<div class="org-center">
<div id="org2a22375" class="figure">
<p><img src="./imgs/dimming.svg" alt="dimming.svg" class="org-svg" />
</p>
</div>
</div>
<p>
Woah! That's a pretty serious difference, although it makes some sense given how <code>dim2</code> not only processes 16 bytes at a time but also uses a right shift. They're both still increasing at the same rate, but even that linear speedup has a very distinct difference in real world cases.
</p>
</div>
</div>
</div>
<div id="outline-container-orgced8d7f" class="outline-2">
<h2 id="orgced8d7f">Exercise 2: Convert to greyscale</h2>
<div class="outline-text-2" id="text-orgced8d7f">
<blockquote>
<p>
Implement a function that takes in an RGB color image and outputs that same image in grayscale.
</p>
</blockquote>
<p>
Mostly the same boilerplate, although I use <code>image-rs</code>' direct pixel grabbing interface this time. Addition of the R, G, and B values requires widening the bytes to 16-bit so there aren't any overflows and then casting back to an 8-bit int in the end.
</p>
<div class="org-src-container">
<pre class="src src-rust"><span class="org-keyword">pub</span> <span class="org-keyword">fn</span> <span class="org-function-name">greyscale</span>(<span class="org-variable-name">img</span>: <span class="org-type">DynamicImage</span>) -> <span class="org-type">Result</span><<span class="org-type">DynamicImage</span>> {
<span class="org-keyword">let</span> (w, h) = img.dimensions();
<span class="org-keyword">let</span> <span class="org-keyword">mut</span> <span class="org-variable-name">out</span>: <span class="org-type">Vec</span><<span class="org-type">u8</span>> = <span class="org-preprocessor">vec!</span>[0; (w*h) <span class="org-keyword">as</span> <span class="org-type">usize</span>];
<span class="org-keyword">for</span> (n, i) <span class="org-keyword">in</span> img.pixels().enumerate() {
<span class="org-keyword">let</span> <span class="org-variable-name">vals</span> = i.2.0;
<span class="org-keyword">let</span> <span class="org-variable-name">sum</span> = vals[0] <span class="org-keyword">as</span> <span class="org-type">u16</span>
+ vals[1] <span class="org-keyword">as</span> <span class="org-type">u16</span>
+ vals[2] <span class="org-keyword">as</span> <span class="org-type">u16</span>;
out[n] = (sum/3) <span class="org-keyword">as</span> <span class="org-type">u8</span>;
}
<span class="org-keyword">let</span> <span class="org-variable-name">buf</span> = <span class="org-type">ImageBuffer</span>::from_vec(w, h, out)
.ok_or(<span class="org-preprocessor">anyhow!</span>(<span class="org-string">"Couldn't convert buffer."</span>))<span class="org-rust-question-mark">?</span>;
<span class="org-type">Ok</span>(<span class="org-type">DynamicImage</span>::<span class="org-type">ImageLuma8</span>(buf)) <span class="org-comment-delimiter">// </span><span class="org-comment">encode image as greyscale </span>
}
</pre>
</div>
<div id="orgecd58f5" class="figure">
<p><img src="./imgs/grey.png" alt="grey.png" />
</p>
</div>
</div>
<div id="outline-container-org6788352" class="outline-3">
<h3 id="org6788352">Optimized</h3>
<div class="outline-text-3" id="text-org6788352">
<p>
If you thought the last optimization was a long side tangent, get ready for a whole lot more. I spent most of my time in this assignment trying to make greyscaling quick. Feel free to skip this section.
</p>
<p>
To begin, it's not immediately obvious <i>how</i> one would actually SIMD-optimize a greyscale when the bytes are laid out as [r g b r g b … r g b] and we need to process 3 (not even 4, which would be more palatable) components at once.
</p>
</div>
<div id="outline-container-org7043152" class="outline-4">
<h4 id="org7043152">First Attempt</h4>
<div class="outline-text-4" id="text-org7043152">
<p>
After searching around for a bit, I found an interesting technique detailed <a href="http://ftp.cvut.cz/kernel/people/geoff/cell/ps3-linux-docs/CellProgrammingTutorial/BasicsOfSIMDProgramming.html">here</a> that essentially processes chunks of 12 bytes at a time (or 4 pixels), loads all of the red bytes into a SIMD register, all of the blue into another, and all of the green into a third.
</p>
<p>
This has some downsides though: mainly that we're doing a strided access of memory which is a little awkward to implement. Doing manual SIMD is also a journey, especially on ARM. Rust has unsafe wrappers around the NEON instrinsics (thin wrappers around assembly) in <code>std::aarch64</code>, but this means that I spent a good amount of time combing through lists of functions to figure out which one corresponded to the operation I wanted. Since I originally hoped to work with a modified greyscale algorithm that had a weighted average of the R, G, and B values I opted to cast to 32-bit floats and use the intrinsics there to multiply by constants.
</p>
<div class="org-src-container">
<pre class="src src-rust"><span class="org-keyword">pub</span> <span class="org-keyword">fn</span> <span class="org-function-name">simd4_greyscale</span>(<span class="org-variable-name">buf</span>: <span class="org-rust-ampersand">&</span>[<span class="org-type">u8</span>], <span class="org-variable-name">out</span>: <span class="org-rust-ampersand">&</span><span class="org-keyword">mut</span> [<span class="org-type">u8</span>]) {
<span class="org-keyword">for</span> <span class="org-variable-name">i</span> <span class="org-keyword">in</span> 0..buf.len()/12 {
<span class="org-keyword">let</span> <span class="org-variable-name">off</span> = i*12;
<span class="org-keyword">let</span> <span class="org-variable-name">r</span> = [buf[off + 0] <span class="org-keyword">as</span> <span class="org-type">f32</span>, buf[off + 3] <span class="org-keyword">as</span> <span class="org-type">f32</span>, buf[off + 6] <span class="org-keyword">as</span> <span class="org-type">f32</span>, buf[off + 9] <span class="org-keyword">as</span> <span class="org-type">f32</span>];
<span class="org-keyword">let</span> <span class="org-variable-name">g</span> = [buf[off + 1] <span class="org-keyword">as</span> <span class="org-type">f32</span>, buf[off + 4] <span class="org-keyword">as</span> <span class="org-type">f32</span>, buf[off + 7] <span class="org-keyword">as</span> <span class="org-type">f32</span>, buf[off + 10] <span class="org-keyword">as</span> <span class="org-type">f32</span>];
<span class="org-keyword">let</span> <span class="org-variable-name">b</span> = [buf[off + 2] <span class="org-keyword">as</span> <span class="org-type">f32</span>, buf[off + 5] <span class="org-keyword">as</span> <span class="org-type">f32</span>, buf[off + 8] <span class="org-keyword">as</span> <span class="org-type">f32</span>, buf[off + 11] <span class="org-keyword">as</span> <span class="org-type">f32</span>];
<span class="org-keyword">let</span> <span class="org-keyword">mut</span> <span class="org-variable-name">ret</span> = [0.0; 4];
<span class="org-rust-unsafe">unsafe</span> {
<span class="org-keyword">let</span> <span class="org-variable-name">r_simd</span> = vld1q_f32(r.as_ptr());
<span class="org-keyword">let</span> <span class="org-variable-name">g_simd</span> = vld1q_f32(g.as_ptr());
<span class="org-keyword">let</span> <span class="org-variable-name">b_simd</span> = vld1q_f32(b.as_ptr());
<span class="org-keyword">let</span> <span class="org-variable-name">r_simd</span> = vmulq_n_f32(r_simd, 0.33);
<span class="org-keyword">let</span> <span class="org-variable-name">r_simd</span> = vmlaq_n_f32(g_simd, r_simd, 0.33);
<span class="org-keyword">let</span> <span class="org-variable-name">r_simd</span> = vmlaq_n_f32(b_simd, r_simd, 0.33);
vst1q_f32(ret.as_mut_ptr(), r_simd);
}
<span class="org-keyword">for</span> <span class="org-variable-name">j</span> <span class="org-keyword">in</span> 0..4 {
out[i*4 + j] = ret[j] <span class="org-keyword">as</span> <span class="org-type">u8</span>;
}
}
}
</pre>
</div>
<p>
I'm gonna dive into a bit more depth with this function, mostly because it's quite a bit more unreadable than everything else I've shown thus far. First off (pun intended), the loop and <code>off</code> calculation is used for loading the image data 12 bytes at a time as mentioned earlier. The next thing you notice is the huge block of array logic:
</p>
<div class="org-src-container">
<pre class="src src-rust"><span class="org-keyword">let</span> <span class="org-variable-name">r</span> = [buf[off + 0] <span class="org-keyword">as</span> <span class="org-type">f32</span>, buf[off + 3] <span class="org-keyword">as</span> <span class="org-type">f32</span>, buf[off + 6] <span class="org-keyword">as</span> <span class="org-type">f32</span>, buf[off + 9] <span class="org-keyword">as</span> <span class="org-type">f32</span>];
<span class="org-keyword">let</span> <span class="org-variable-name">g</span> = [buf[off + 1] <span class="org-keyword">as</span> <span class="org-type">f32</span>, buf[off + 4] <span class="org-keyword">as</span> <span class="org-type">f32</span>, buf[off + 7] <span class="org-keyword">as</span> <span class="org-type">f32</span>, buf[off + 10] <span class="org-keyword">as</span> <span class="org-type">f32</span>];
<span class="org-keyword">let</span> <span class="org-variable-name">b</span> = [buf[off + 2] <span class="org-keyword">as</span> <span class="org-type">f32</span>, buf[off + 5] <span class="org-keyword">as</span> <span class="org-type">f32</span>, buf[off + 8] <span class="org-keyword">as</span> <span class="org-type">f32</span>, buf[off + 11] <span class="org-keyword">as</span> <span class="org-type">f32</span>];
</pre>
</div>
<p>
This is used to extract each of the red, green, and blue bytes from the 12-byte subsequence we're processing and cast them to <code>f32</code> so we can use them. You might wonder why this is all manually typed out instead of written as a nice loop. All of this logic is run every time we process four pixels, and so adding extra conditionals and logic actually has an impact on the runtime.
</p>
<p>
Then, there's the big <code>unsafe</code> block with a bunch of terse function names. These are the NEON intrinsics! We start off by loading the r, g, and b arrays we made into SIMD registers.
</p>
<div class="org-src-container">
<pre class="src src-rust"><span class="org-keyword">let</span> <span class="org-variable-name">r_simd</span> = vld1q_f32(r.as_ptr());
<span class="org-keyword">let</span> <span class="org-variable-name">g_simd</span> = vld1q_f32(g.as_ptr());
<span class="org-keyword">let</span> <span class="org-variable-name">b_simd</span> = vld1q_f32(b.as_ptr());
</pre>
</div>
<p>
Next, we multiply each of the R values by 0.33 (approximating division by 1/3 + mostly a legacy from me originally trying to use a different algorithm).
</p>
<div class="org-src-container">
<pre class="src src-rust"><span class="org-keyword">let</span> <span class="org-variable-name">r_simd</span> = vmulq_n_f32(r_simd, 0.33);
</pre>
</div>
<p>
We then do the same to the G and B channels, but continue accumulating the results in the <code>r_simd</code> register:
</p>
<div class="org-src-container">
<pre class="src src-rust"><span class="org-keyword">let</span> <span class="org-variable-name">r_simd</span> = vmlaq_n_f32(g_simd, r_simd, 0.33);
<span class="org-keyword">let</span> <span class="org-variable-name">r_simd</span> = vmlaq_n_f32(b_simd, r_simd, 0.33);
</pre>
</div>
<p>
Then, we finally store the contents of <code>r_simd</code> (which are now each of the greyscaled pixels) into our <code>ret</code> array, which we later use to add pixels to the output image.
</p>
<div class="org-src-container">
<pre class="src src-rust">vst1q_f32(ret.as_mut_ptr(), r_simd);
</pre>
</div>
<p>
Alright! Now we have <i>something</i> to work with. All this casting to <code>f32</code> isn't ideal, and there exist registers than can act on eight <code>u8</code> at once, which should theoretically be way better!
</p>
</div>
</div>
<div id="outline-container-orgd60cb4b" class="outline-4">
<h4 id="orgd60cb4b">Second Attempt</h4>
<div class="outline-text-4" id="text-orgd60cb4b">
<p>
Let's just do what we did before but with 8 pixels (24 bytes) at a time! This immediately makes the array loading step much nastier, but the performance tradeoff is still there, so the code stays:
</p>
<div class="org-src-container">
<pre class="src src-rust">r = [buf[off+0], buf[off+3], buf[off+6], buf[off+ 9], buf[off+12], buf[off+15], buf[off+18], buf[off+21]];
g = [buf[off+1], buf[off+4], buf[off+7], buf[off+10], buf[off+13], buf[off+16], buf[off+19], buf[off+22]];
b = [buf[off+2], buf[off+5], buf[off+8], buf[off+11], buf[off+14], buf[off+17], buf[off+20], buf[off+23]];
</pre>
</div>
<p>
We obviously can't multiply by a float like before since we're working with a bunch of <code>u8</code> now, but that isn't a problem, since that system wasn't very necessary to begin with. If we stick to the simple averaging RGB strategy, all we need is integer division, which we have.
</p>
<div id="org120a440" class="figure">
<p><img src="https://i.imgur.com/IKpPkDV.png" alt="IKpPkDV.png" />
</p>
</div>
<div class="org-center">
<p>
Pictured: all ARM NEON division instructions
</p>
<p>
(excluding reciprocal estimation functions, which are also for <code>f32</code> data)
</p>
</div>
<p>
…right? right?
</p>
<blockquote>
<p>
NEON doesn't have any integer division instructions, because they are expensive to implement in hardware. - <a href="https://tttapa.github.io/Pages/Raspberry-Pi/NEON/Division.html">https://tttapa.github.io/Pages/Raspberry-Pi/NEON/Division.html</a>
</p>
</blockquote>
<p>
Amazing. Well, one alternative strategy often used when there is no hardware multiply/divide (which is also recommended by this source) is to work with bit shifts and other arithmetic operations. After some searching, it seemed as if most ways of doing this either required widening the type to a <code>u16</code> (not great) or doing some really confusing bit math.
</p>
<p>
<i>Alternatively</i>, we could divide by four.
</p>
<p>
Averaging three numbers by dividing their sum by four is not recommended<sup>[citation needed]</sup>, but we don't need amazing precision: we just need the image to look grey. Dividing by <i>four</i> is substantially easier: we just bit shift right twice. Since we're staying in <code>u8</code> form the entire time we have to divide before rather than after (or else we'll overflow), so we simply shift all of the register and then add them:
</p>
<div class="org-src-container">
<pre class="src src-rust"><span class="org-keyword">let</span> <span class="org-variable-name">res</span> = vadd_u8(
vadd_u8(
vshr_n_u8(r_simd, 2),
vshr_n_u8(g_simd, 2)
),
vshr_n_u8(b_simd, 2)
);
</pre>
</div>
<p>
This gives us our complete 8x SIMD function:
</p>
<div class="org-src-container">
<pre class="src src-rust"><span class="org-keyword">pub</span> <span class="org-keyword">fn</span> <span class="org-function-name">simd8_greyscale</span>(<span class="org-variable-name">buf</span>: <span class="org-rust-ampersand">&</span>[<span class="org-type">u8</span>], <span class="org-variable-name">out</span>: <span class="org-rust-ampersand">&</span><span class="org-keyword">mut</span> [<span class="org-type">u8</span>]) {
<span class="org-keyword">let</span> (<span class="org-keyword">mut</span> r, <span class="org-keyword">mut</span> g, <span class="org-keyword">mut</span> b) = ([0; 8], [0; 8], [0; 8]);
<span class="org-keyword">let</span> <span class="org-variable-name">ptr</span> = out.as_mut_ptr();
<span class="org-keyword">for</span> <span class="org-variable-name">i</span> <span class="org-keyword">in</span> 0..buf.len()/24 {
<span class="org-keyword">let</span> <span class="org-variable-name">off</span> = i*24;
r = [buf[off+0], buf[off+3], buf[off+6], buf[off+ 9], buf[off+12], buf[off+15], buf[off+18], buf[off+21]];
g = [buf[off+1], buf[off+4], buf[off+7], buf[off+10], buf[off+13], buf[off+16], buf[off+19], buf[off+22]];
b = [buf[off+2], buf[off+5], buf[off+8], buf[off+11], buf[off+14], buf[off+17], buf[off+20], buf[off+23]];
<span class="org-rust-unsafe">unsafe</span> {
<span class="org-keyword">let</span> <span class="org-variable-name">r_simd</span> = vld1_u8(r.as_ptr());
<span class="org-keyword">let</span> <span class="org-variable-name">g_simd</span> = vld1_u8(g.as_ptr());
<span class="org-keyword">let</span> <span class="org-variable-name">b_simd</span> = vld1_u8(b.as_ptr());
<span class="org-keyword">let</span> <span class="org-variable-name">res</span> = vadd_u8(
vadd_u8(
vshr_n_u8(r_simd, 2),
vshr_n_u8(g_simd, 2)
),
vshr_n_u8(b_simd, 2)
);
vst1_u8(ptr.add(i*8), res);
}
}
}
</pre>
</div>
</div>
</div>
<div id="outline-container-org70217c4" class="outline-4">
<h4 id="org70217c4">Benchmarking</h4>
<div class="outline-text-4" id="text-org70217c4">
<p>
After talking some with my friend Riley, he suggested a third, simpler approach that hopefully let the compiler do the work for me (that unfortunately only worked on RGBA images, wasting a byte per pixel):
</p>
<div class="org-src-container">
<pre class="src src-rust"><span class="org-keyword">pub</span> <span class="org-keyword">fn</span> <span class="org-function-name">riley_greyscale</span>(<span class="org-variable-name">buf</span>: <span class="org-rust-ampersand">&</span>[<span class="org-type">u8</span>], <span class="org-variable-name">out</span>: <span class="org-rust-ampersand">&</span><span class="org-keyword">mut</span> [<span class="org-type">u8</span>]) {
<span class="org-keyword">let</span> <span class="org-variable-name">pixels</span>: <span class="org-rust-ampersand">&</span>[<span class="org-type">u32</span>] = <span class="org-constant">bytemuck</span>::cast_slice::<<span class="org-type">u8</span>, <span class="org-type">u32</span>>(buf);
<span class="org-keyword">for</span> (n, pixel) <span class="org-keyword">in</span> pixels.enumerate() {
<span class="org-keyword">let</span> [r, g, b, _a] = pixel.to_be_bytes();
<span class="org-keyword">let</span> <span class="org-variable-name">comp</span> = ((r <span class="org-keyword">as</span> <span class="org-type">u32</span> + g <span class="org-keyword">as</span> <span class="org-type">u32</span> + b <span class="org-keyword">as</span> <span class="org-type">u32</span>) / 3) <span class="org-keyword">as</span> <span class="org-type">u8</span>;
out[n] = comp;
}
}
</pre>
</div>
<p>
Benchmarking all 3 of these functions gives the following plot:
</p>
<div id="org886fa78" class="figure">
<p><img src="https://i.imgur.com/BQK0kxU.png" alt="BQK0kxU.png" />
</p>
</div>
<p>
Not great. We'd expect <code>simd8</code> at the very least to be twice as fast as <code>simd4</code>. On top of that, peeking at the assembly for <code>riley</code> shows that it wasn't even vectorized! It's hard to tell without line-by-line profiling, but my bet is that the awkward strided memory loads probably offset most of the bonus given by SIMD. On top of that, all those shift operations might also cancel some stuff out when it comes to <code>simd8</code> (or the casts for <code>simd4</code>).
</p>
</div>
</div>
</div>
</div>
<div id="outline-container-org251be1e" class="outline-2">
<h2 id="org251be1e">Exercise 3: RGB exclusion</h2>
<div class="outline-text-2" id="text-org251be1e">
<blockquote>
<p>
Implement a function that takes in an image and a channel, and returns an image without the specified channel.
</p>
</blockquote>
<p>
For convienence, this function takes a character instead of an index, and then just maps it to one using a small switch (<code>match</code> really) statement. This is also handleable with a good <code>map</code> call, and so for succinctness I went with that again.
</p>
<div class="org-src-container">
<pre class="src src-rust"><span class="org-keyword">pub</span> <span class="org-keyword">fn</span> <span class="org-function-name">rgb_restrict</span>(<span class="org-variable-name">img</span>: <span class="org-type">DynamicImage</span>, <span class="org-variable-name">channel</span>: <span class="org-type">char</span>) -> <span class="org-type">Result</span><<span class="org-type">DynamicImage</span>> {
<span class="org-keyword">let</span> (w, h) = img.dimensions();
<span class="org-keyword">let</span> <span class="org-keyword">mut</span> <span class="org-variable-name">out</span>: <span class="org-type">Vec</span><<span class="org-type">u8</span>> = <span class="org-type">Vec</span>::with_capacity((w*h*3) <span class="org-keyword">as</span> <span class="org-type">usize</span>);
<span class="org-keyword">let</span> <span class="org-variable-name">index</span> = <span class="org-keyword">match</span> channel {
<span class="org-string">'R'</span> => 0,
<span class="org-string">'G'</span> => 1,
<span class="org-string">'B'</span> => 2,
_ => { <span class="org-keyword">return</span> <span class="org-type">Err</span>(<span class="org-preprocessor">anyhow!</span>(<span class="org-string">"Invalid color channel"</span>)); }
};
out.extend(<span class="org-rust-ampersand">&</span><span class="org-keyword">mut</span>
img.as_bytes()
.iter()
.enumerate()
.map(|(n,i)| <span class="org-keyword">if</span> n % 3 == index { 0 } <span class="org-keyword">else</span> { *i })
);
<span class="org-keyword">let</span> <span class="org-variable-name">buf</span> = <span class="org-type">ImageBuffer</span>::from_vec(w, h, out)
.ok_or(<span class="org-preprocessor">anyhow!</span>(<span class="org-string">"Couldn't convert buffer"</span>))<span class="org-rust-question-mark">?</span>;
<span class="org-type">Ok</span>(<span class="org-type">DynamicImage</span>::<span class="org-type">ImageRgb8</span>(buf))
}
</pre>
</div>
<p>
Running this with each of the channels R, G, B gives us the following images:
</p>
<div class="flexbox" id="orgd12b62c">
<div class="flexitem" id="org090ac8a">
<div id="orgc5927d5" class="figure">
<p><img src="./imgs/rgb_r.png" alt="rgb_r.png" />
</p>
</div>
</div>
<div class="flexitem" id="org31d131d">
<div id="orge6341a5" class="figure">
<p><img src="./imgs/rgb_g.png" alt="rgb_g.png" />
</p>
</div>
</div>
<div class="flexitem" id="orge7d0e56">
<div id="orge33ae39" class="figure">
<p><img src="./imgs/rgb_b.png" alt="rgb_b.png" />
</p>
</div>
</div>
</div>
</div>
<div id="outline-container-orgf6bd16e" class="outline-3">
<h3 id="orgf6bd16e">Optimized</h3>
<div class="outline-text-3" id="text-orgf6bd16e">
<p>
I didn't forsee there being a nice way to optimize this any more, so I once again just went for the simplification route, letting the compiler do its best and stripping away unnecessary features (like the nice character to channel index converter).
</p>
<div class="org-src-container">
<pre class="src src-rust"><span class="org-keyword">pub</span> <span class="org-keyword">fn</span> <span class="org-function-name">exclude</span>(<span class="org-variable-name">bytes</span>: <span class="org-rust-ampersand">&</span>[<span class="org-type">u8</span>], <span class="org-variable-name">out</span>: <span class="org-rust-ampersand">&</span><span class="org-keyword">mut</span> [<span class="org-type">u8</span>], <span class="org-variable-name">index</span>: <span class="org-type">usize</span>) {
<span class="org-keyword">for</span> <span class="org-variable-name">n</span> <span class="org-keyword">in</span> 0..bytes.len() {
<span class="org-keyword">if</span> n % 3 == index {
out[n] = 0;
}
}
}
</pre>
</div>
<p>
No SIMD to gain here, unfortunately.
</p>
</div>
</div>
</div>
<div id="outline-container-org8ff8c77" class="outline-2">
<h2 id="org8ff8c77">Advanced Exercise 1</h2>
<div class="outline-text-2" id="text-org8ff8c77">
<blockquote>
<p>
Implement a function that takes in an image and an LAB channel, and returns an image without the specified channel.
</p>
</blockquote>
<p>
I used a rust library for color space handling called <code>palette</code> - it provides <code>IntoColor</code> and <code>FromColor</code> traits that allow for conversion between a number of predefined color sets: <code>Lab</code>, <code>Srgb</code>, <code>Hsv</code>, etc. Reading ahead a little bit, I noticed the next exercise had us do something very similar but with HSV, so I went ahead and did a bit of generalization.
</p>
<p>
Let's define a <code>ColorChannel</code> trait that requires a struct be convertible to and from <code>Srgb</code> as well as support zeroing out a user-supplied channel.
</p>
<div class="org-src-container">
<pre class="src src-rust"><span class="org-keyword">pub</span> <span class="org-keyword">trait</span> <span class="org-variable-name">ColorChannel</span>: <span class="org-type">IntoColor</span><<span class="org-type">Srgb</span>> + <span class="org-type">FromColor</span><<span class="org-type">Srgb</span>> {
<span class="org-keyword">fn</span> <span class="org-function-name">zero_channel</span>(<span class="org-rust-ampersand">&</span><span class="org-keyword">mut</span> <span class="org-keyword">self</span>, <span class="org-variable-name">channel</span>: <span class="org-type">char</span>) -> <span class="org-type">Result</span><()>;
}
</pre>
</div>
<p>
We can then quickly implement this trait for <code>Lab</code>:
</p>
<div class="org-src-container">
<pre class="src src-rust"><span class="org-keyword">impl</span> <span class="org-type">ColorChannel</span> <span class="org-keyword">for</span> <span class="org-type">Lab</span> {
<span class="org-keyword">fn</span> <span class="org-function-name">zero_channel</span>(<span class="org-rust-ampersand">&</span><span class="org-keyword">mut</span> <span class="org-keyword">self</span>, <span class="org-variable-name">channel</span>: <span class="org-type">char</span>) -> <span class="org-type">Result</span><()> {
<span class="org-keyword">match</span> channel.to_ascii_uppercase() {
<span class="org-string">'L'</span> => <span class="org-keyword">self</span>.l = 0.0,
<span class="org-string">'A'</span> => <span class="org-keyword">self</span>.a = 0.0,
<span class="org-string">'B'</span> => <span class="org-keyword">self</span>.b = 0.0,
_ => { <span class="org-keyword">return</span> <span class="org-type">Err</span>(<span class="org-preprocessor">anyhow!</span>(<span class="org-string">"Invalid color channel"</span>)); }
}
<span class="org-type">Ok</span>(())
}
}
</pre>
</div>
<p>
Now with this out of the way, we can implement the restriction function generically for any color space <code>Space</code> by converting each pixel's RGB value to it, zeroing out the user supplied channel, and converting it back to RGB.
</p>
<div class="org-src-container">
<pre class="src src-rust"><span class="org-keyword">pub</span> <span class="org-keyword">fn</span> <span class="org-function-name">restrict</span><<span class="org-variable-name">Space</span>: <span class="org-type">ColorChannel</span>>(<span class="org-variable-name">img</span>: <span class="org-type">DynamicImage</span>, <span class="org-variable-name">channel</span>: <span class="org-type">char</span>) -> <span class="org-type">Result</span><<span class="org-type">DynamicImage</span>> {
<span class="org-keyword">let</span> (w, h) = img.dimensions();
<span class="org-keyword">let</span> <span class="org-keyword">mut</span> <span class="org-variable-name">out</span>: <span class="org-type">Vec</span><<span class="org-type">u8</span>> = <span class="org-type">Vec</span>::with_capacity((w*h*3) <span class="org-keyword">as</span> <span class="org-type">usize</span>);
<span class="org-keyword">for</span> <span class="org-variable-name">i</span> <span class="org-keyword">in</span> img.pixels() {
<span class="org-keyword">let</span> <span class="org-variable-name">rgb</span> = <span class="org-type">Srgb</span>::from_components(
(i.2.0[0], i.2.0[1], i.2.0[2])
).into_format::<<span class="org-type">f32</span>>();
<span class="org-keyword">let</span> <span class="org-keyword">mut</span> <span class="org-variable-name">color</span>: <span class="org-type">Space</span> = rgb.into_color();
color.set_channel(channel)<span class="org-rust-question-mark">?</span>;
<span class="org-keyword">let</span> <span class="org-variable-name">orig</span>: <span class="org-type">Srgb</span> = color.into_color();
<span class="org-keyword">let</span> <span class="org-variable-name">orig</span> = orig.into_format::<<span class="org-type">u8</span>>().into_components();
out.extend([orig.0, orig.1, orig.2]);
}
<span class="org-keyword">let</span> <span class="org-variable-name">buf</span> = <span class="org-type">ImageBuffer</span>::from_vec(w, h, out)
.ok_or(<span class="org-preprocessor">anyhow!</span>(<span class="org-string">"Couldn't convert buffer"</span>))<span class="org-rust-question-mark">?</span>;
<span class="org-type">Ok</span>(<span class="org-type">DynamicImage</span>::<span class="org-type">ImageRgb8</span>(buf))
}
</pre>
</div>
<p>
We can then restrict an image's L channel in LAB space with the following code:
</p>
<div class="org-src-container">
<pre class="src src-rust"><span class="org-keyword">let</span> <span class="org-variable-name">out</span> = restrict::<<span class="org-type">Lab</span>>(img, <span class="org-string">'L'</span>).unwrap();
</pre>
</div>
<p>
Doing this for each of the channels yields the following images:
</p>
<div class="flexbox" id="org674de41">
<div class="flexitem" id="org9fab87a">
<div id="orgcaf3c86" class="figure">
<p><img src="./imgs/lab_l.png" alt="lab_l.png" />
</p>
</div>
</div>
<div class="flexitem" id="orgec090d6">
<div id="org226ad1d" class="figure">
<p><img src="./imgs/lab_a.png" alt="lab_a.png" />
</p>
</div>
</div>
<div class="flexitem" id="orgd678457">
<div id="orgff3cf34" class="figure">
<p><img src="./imgs/lab_b.png" alt="lab_b.png" />
</p>
</div>
</div>
</div>
</div>
<div id="outline-container-org432b012" class="outline-3">
<h3 id="org432b012">What is LAB?</h3>
<div class="outline-text-3" id="text-org432b012">
<blockquote>
<p>
Explain what the L, A and B channels are and what happens when you take away the L and A channels.
</p>
</blockquote>
<p>
The LAB colorspace (CIELAB? L*a*b*?) is one designed to better match human perception: the L channel represents the <i>lightness</i> of the image, the channel is a color scale from red to green, and the B channel is a color scale from orange to blue. This is because humans generally process color in this manner: you can't picture an "orangish blue" or a "reddish green" because your brain perceives colors as a scale between them.
</p>
<p>
We can expect taking away the L (lightness) and A (red-green) scales to provide us with a very dim image that primarily consists of orange and blue.
</p>
<div id="org12873c2" class="figure">
<p><img src="./imgs/lab_la.png" alt="lab_la.png" />
</p>
</div>
<p>
And that's what we see!
</p>
</div>
</div>
</div>
<div id="outline-container-org13845af" class="outline-2">
<h2 id="org13845af">Advanced Exercise 2</h2>
<div class="outline-text-2" id="text-org13845af">
<blockquote>
<p>
Explain what the H, S and V channels are and what happens when you take away the both the H and S channels.
</p>
<p>
It may help you to implement a function that performs HSV decomposition and removes these channels; this is optional.
</p>
</blockquote>
<p>
Since we implemented the <code>restrict</code> function in a generic manner, all we need to do is implement the <code>ColorChannel</code> trait for HSV! The one notable difference is that since hue is an angle we have to initialize it more intentionally.
</p>
<div class="org-src-container">
<pre class="src src-rust"><span class="org-keyword">impl</span> <span class="org-type">ColorChannel</span> <span class="org-keyword">for</span> <span class="org-type">Hsv</span> {
<span class="org-keyword">fn</span> <span class="org-function-name">zero_channel</span>(<span class="org-rust-ampersand">&</span><span class="org-keyword">mut</span> <span class="org-keyword">self</span>, <span class="org-variable-name">channel</span>: <span class="org-type">char</span>) -> <span class="org-type">Result</span><()> {
<span class="org-keyword">match</span> channel.to_ascii_uppercase() {
<span class="org-string">'H'</span> => <span class="org-keyword">self</span>.hue = <span class="org-type">RgbHue</span>::from_degrees(0.0),
<span class="org-string">'S'</span> => <span class="org-keyword">self</span>.saturation = 0.0,
<span class="org-string">'V'</span> => <span class="org-keyword">self</span>.value = 0.0,
_ => { <span class="org-keyword">return</span> <span class="org-type">Err</span>(<span class="org-preprocessor">anyhow!</span>(<span class="org-string">"Invalid color channel"</span>)); }
}
<span class="org-type">Ok</span>(())
}
}
</pre>
</div>
<p>
The H channel of an HSV color is <i>hue</i>, an angle describing a position in a standard color wheel. The S channel, <i>saturation</i>, is roughly a measure of the intensity of the color. Finally, the V channel represents <i>value</i> which is a measure of how bright the color is. We can see this by dropping off each of the channels respectively:
</p>
<div class="flexbox" id="org24cb3be">
<div class="flexitem" id="orgbf80ec6">
<div id="orgda89112" class="figure">
<p><img src="./imgs/hsv_h.png" alt="hsv_h.png" />
</p>
</div>
</div>
<div class="flexitem" id="orgbee08dc">
<div id="orge723e36" class="figure">
<p><img src="./imgs/hsv_s.png" alt="hsv_s.png" />
</p>
</div>
</div>
<div class="flexitem" id="org71d9739">
<div id="orgb1f6be8" class="figure">
<p><img src="./imgs/hsv_v.png" alt="hsv_v.png" />
</p>
</div>
</div>