-
Notifications
You must be signed in to change notification settings - Fork 0
/
hw2.jl
1235 lines (963 loc) · 35.6 KB
/
hw2.jl
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
### A Pluto.jl notebook ###
# v0.14.8
using Markdown
using InteractiveUtils
# This Pluto notebook uses @bind for interactivity. When running this notebook outside of Pluto, the following 'mock version' of @bind gives bound variables a default value (instead of an error).
macro bind(def, element)
quote
local el = $(esc(element))
global $(esc(def)) = Core.applicable(Base.get, el) ? Base.get(el) : missing
el
end
end
# ╔═╡ 65780f00-ed6b-11ea-1ecf-8b35523a7ac0
begin
import Pkg
Pkg.activate(mktempdir())
Pkg.add([
Pkg.PackageSpec(name="Images", version="0.22.4"),
Pkg.PackageSpec(name="ImageMagick", version="0.7"),
Pkg.PackageSpec(name="PlutoUI", version="0.7"),
Pkg.PackageSpec(name="HypertextLiteral", version="0.5"),
Pkg.PackageSpec(name="OffsetArrays"),
])
using Images
using PlutoUI
using HypertextLiteral
using OffsetArrays
end
# ╔═╡ f7a6d7c3-37b9-437d-8b8e-853665ddbae3
filter!(LOAD_PATH) do path
path != "@v#.#"
end;
# ╔═╡ 83eb9ca0-ed68-11ea-0bc5-99a09c68f867
md"_homework 2, version 1_"
# ╔═╡ ac8ff080-ed61-11ea-3650-d9df06123e1f
md"""
# **Homework 2** - _convolutions_
`18.S191`, Spring 2021
`Due Date`: **Friday Mar 5, 2021 at 11:59pm EST**
This notebook contains _built-in, live answer checks_! In some exercises you will see a coloured box, which runs a test case on your code, and provides feedback based on the result. Simply edit the code, run it, and the check runs again.
_For MIT students:_ there will also be some additional (secret) test cases that will be run as part of the grading process, and we will look at your notebook and write comments.
Feel free to ask questions!
"""
# ╔═╡ 5f95e01a-ee0a-11ea-030c-9dba276aba92
md"_Let's create a package environment:_"
# ╔═╡ e08781fa-ed61-11ea-13ae-91a49b5eb74a
md"""
## **Exercise 1** - _Convolutions in 1D_
As we have seen in the lectures, we can produce cool effects using the mathematical technique of **convolutions**. We input one image $M$ and get a new image $M'$ back.
Conceptually we think of $M$ as a matrix. In practice, in Julia it will be a `Matrix` of color objects, and we may need to take that into account. Ideally, however, we should write a **generic** function that will work for any type of data contained in the matrix.
A convolution works on a small **window** of an image, i.e. a region centered around a given point $(i, j)$. We will suppose that the window is a square region with odd side length $2\ell + 1$, running from $-\ell, \ldots, 0, \ldots, \ell$.
The result of the convolution over a given window, centred at the point $(i, j)$ is a *single number*; this number is the value that we will use for $M'_{i, j}$.
(Note that neighbouring windows overlap.)
To get started, in Exercise 1 we'll restrict ourselves to convolutions in 1D.
So a window is just a 1D region from $-\ell$ to $\ell$.
"""
# ╔═╡ 80108d80-ee09-11ea-0368-31546eb0d3cc
md"""
#### Exercise 1.1
Let's create a vector `v` of random numbers of length `n=100`.
"""
# ╔═╡ 7fcd6230-ee09-11ea-314f-a542d00d582e
n = 60
# ╔═╡ 7fdb34dc-ee09-11ea-366b-ffe10d1aa845
v = rand(n)
# ╔═╡ 7fe9153e-ee09-11ea-15b3-6f24fcc20734
md"_Feel free to experiment with different values!_
Let's use the function `colored_line` to view this 1D number array as a 1D image.
"
# ╔═╡ ff70782e-e8d2-4281-9b24-d45c925f55e2
begin
colored_line(x::Vector) = hcat(Gray.(Float64.(x)))'
colored_line(x::Any) = nothing
end
# ╔═╡ 01070e28-ee0f-11ea-1928-a7919d452bdd
colored_line(v)
# ╔═╡ 7522f81e-ee1c-11ea-35af-a17eb257ff1a
md"👉 Try changing `n` and `v` around. Notice that you can run the cell `v = rand(n)` again to regenerate new random values."
# ╔═╡ 801d90c0-ee09-11ea-28d6-61b806de26dc
md"""
#### Exercise 1.2
We need to decide how to handle the **boundary conditions**, i.e. what happens if we try to access a position in the vector `v` beyond `1:n`. The simplest solution is to assume that $v_{i}$ is 0 outside the original vector; however, this may lead to strange boundary effects.
A better solution is to use the *closest* value that is inside the vector. Effectively we are extending the vector and copying the extreme values into the extended positions. (Indeed, this is one way we could implement this; these extra positions are called **ghost cells**.)
👉 Write a function `extend(v, i)` that checks whether the position $i$ is inside `1:n`. If so, return the $(HTML("<br>")) ``i``th component of `v`; otherwise, return the nearest end value.
"""
# ╔═╡ 802bec56-ee09-11ea-043e-51cf1db02a34
function extend(v::AbstractVector, i)
if i <= length(v) && i>=1
return v[i]
elseif i<1
return v[1]
else
return v[length(v)]
end
end
# ╔═╡ b7f3994c-ee1b-11ea-211a-d144db8eafc2
md"_Some test cases:_"
# ╔═╡ 3492b164-7065-48e8-978b-6c96b965d376
example_vector = [0.8, 0.2, 0.1, 0.7, 0.6, 0.4]
# ╔═╡ 02123165-2a0a-49a8-b7a9-458955523511
colored_line(example_vector)
# ╔═╡ 806e5766-ee0f-11ea-1efc-d753cd83d086
md"- Extended with 0:"
# ╔═╡ 38da843a-ee0f-11ea-01df-bfa8b1317d36
colored_line([0, 0, example_vector..., 0, 0])
# ╔═╡ 9bde9f92-ee0f-11ea-27f8-ffef5fce2b3c
md"- Extended with your `extend` function:"
# ╔═╡ 431ba330-0f72-416a-92e9-55f51ff3bcd1
md"""
#### Exercise 1.3
👉 Write (or copy) the `mean` function from Homework 1, which takes a vector and returns the mean.
"""
# ╔═╡ 5fdc5d0d-a52c-476e-b3b5-3b6364b706e4
function mean(v)
return sum([i for i in v])/length(v)
end
# ╔═╡ e84c9cc2-e6e1-46f1-bf4e-9605da5e6f4a
md"""
👉 Write a function `box_blur(v, l)` that blurs a vector `v` with a window of length `l` by averaging the elements within a window from $-\ell$ to $\ell$. This is called a **box blur**. Use your function `extend` to handle the boundaries correctly.
Return a vector of the same size as `v`.
"""
# ╔═╡ 809f5330-ee09-11ea-0e5b-415044b6ac1f
md"""
#### Exercise 1.4
👉 Apply the box blur to your vector `v`. Show the original and the new vector by creating two cells that call `colored_line`. Make the parameter $\ell$ interactive, and call it `l_box` instead of `l` to avoid a naming conflict.
"""
# ╔═╡ 302f0842-453f-47bd-a74c-7942d8c96485
@bind l_box Slider((1:10), show_value=true)
# ╔═╡ 80ab64f4-ee09-11ea-29b4-498112ed0799
md"""
#### Exercise 1.5
The box blur is a simple example of a **convolution**, i.e. a linear function of a window around each point, given by
$$v'_{i} = \sum_{m} \, v_{i - m} \, k_{m},$$
where $k$ is a vector called a **kernel**.
Again, we need to take care about what happens if $v_{i -m }$ falls off the end of the vector.
👉 Write a function `convolve(v, k)` that performs this convolution. You need to think of the vector $k$ as being *centred* on the position $i$. So $m$ in the above formula runs between $-\ell$ and $\ell$, where $2\ell + 1$ is the length of the vector $k$.
You will either need to do the necessary manipulation of indices by hand, or use the `OffsetArrays.jl` package.
"""
# ╔═╡ cf73f9f8-ee12-11ea-39ae-0107e9107ef5
md"_Edit the cell above, or create a new cell with your own test cases!_"
# ╔═╡ fa463b71-5aa4-44a3-a67b-6b0776236243
md"""
#### Exercise 1.6
👉 Define a function `box_blur_kernel(l)` which returns a _kernel_ (i.e. a vector) which, when used as the kernel in `convolve`, will reproduce a box blur of length `l`.
"""
# ╔═╡ 8a7d3cfd-6f19-43f0-ae16-d5a236f148e7
function box_blur_kernel(l)
return [1/(2*l+1) for i in range(1,length=2*l+1)]
end
# ╔═╡ a39d0598-add2-4ffb-b614-7ed9a8aa5bec
Kernel.gaussian((1,))
# ╔═╡ a34d1ad8-3776-4bc4-93e5-72cfffc54f15
@bind box_kernel_l Slider(1:5,show_value=true)
# ╔═╡ 971a801d-9c46-417a-ad31-1144894fb4e1
box_blur_kernel_test = box_blur_kernel(box_kernel_l)
# ╔═╡ 5f13b1a5-8c7d-47c9-b96a-a09faf38fe5e
md"""
Let's apply your kernel to our test vector `v` (first cell), and compare the result to our previous box blur function (second cell). The two should be identical.
"""
# ╔═╡ 03f91a22-1c3e-4c42-9d78-1ee36851a120
md"""
#### Exercise 1.7
👉 Write a function `gaussian_kernel`.
The definition of a Gaussian in 1D is
$$G(x) = \frac{1}{\sqrt{2\pi \sigma^2}} \exp \left( \frac{-x^2}{2\sigma^2} \right),$$
or as a Julia function:
"""
# ╔═╡ 48530f0d-49b4-4aec-8109-d69f1ef7f0ee
md"""
Write a function `gauss` that takes `σ` as a keyword argument and implements this function.
"""
# ╔═╡ beb62fda-38a6-4528-a176-cfb726f4b5bd
gauss(x::Real; σ=1) = 1 / sqrt(2π*σ^2) * exp(-x^2 / (2 * σ^2))
# ╔═╡ f0d55cec-2e81-4cbb-b166-2cf4f2a0f43f
md"""
We need to **sample** (i.e. evaluate) this at each pixel in an interval of length $2n+1$,
and then **normalize** so that the sum of the resulting kernel is 1.
"""
# ╔═╡ 3ea44917-b2bc-4e9e-bad1-5fdf5b7b3c35
Kernel.gaussian((4,))
# ╔═╡ f8bd22b8-ee14-11ea-04aa-ab16fd01826e
md"""
You can edit the cell above to test your kernel function!
Let's try applying it in a convolution.
"""
# ╔═╡ 2a9dd06a-ee13-11ea-3f84-67bb309c77a8
@bind gaussian_kernel_size_1D Slider(0:6,show_value=true)
# ╔═╡ ce24e486-df27-4780-bc57-d3bf7bee83bb
function create_bar()
x = zeros(100)
x[41:60] .= 1
x
end
# ╔═╡ b01858b6-edf3-11ea-0826-938d33c19a43
md"""
## **Exercise 2** - _Convolutions in 2D_
Now let's move to 2D images. The convolution is then given by a **kernel matrix** $K$:
$$M'_{i, j} = \sum_{k, l} \, M_{i- k, j - l} \, K_{k, l},$$
where the sum is over the possible values of $k$ and $l$ in the window. Again we think of the window as being *centered* at $(i, j)$.
A common notation for this operation is $\star$:
```math
M' = M \star K
```
"""
# ╔═╡ 7c1bc062-ee15-11ea-30b1-1b1e76520f13
md"""
#### Exercise 2.1
👉 Write a new method for `extend` that takes a matrix `M` and indices `i` and `j`, and returns the closest element of the matrix.
"""
# ╔═╡ 7c2ec6c6-ee15-11ea-2d7d-0d9401a5e5d1
function extend(M::AbstractMatrix, i, j)
row_size = size(M,1)
col_size = size(M,2)
r=i
c=j
if i<1
r = 1
elseif i>row_size
r = row_size
end
if j<1
c = 1
elseif j>col_size
c = col_size
end
return M[r,c]
end
# ╔═╡ 803905b2-ee09-11ea-2d52-e77ff79693b0
extend([5,6,7], 1)
# ╔═╡ 80479d98-ee09-11ea-169e-d166eef65874
extend([5,6,7], -8)
# ╔═╡ 805691ce-ee09-11ea-053d-6d2e299ee123
extend([5,6,7], 10)
# ╔═╡ 45c4da9a-ee0f-11ea-2c5b-1f6704559137
if extend(v,1) === missing
missing
else
colored_line([extend(example_vector, i) for i in -1:length(example_vector)+2])
end
# ╔═╡ 807e5662-ee09-11ea-3005-21fdcc36b023
function box_blur(v::AbstractArray, l)
return [mean([extend(v,j) for j in range(i-l,i+l,step=1)]) for i in range(1,length=length(v))]
end
# ╔═╡ 68368f96-7af7-4e89-a5f4-2d48aa598100
box_blur(example_vector,1)
# ╔═╡ 4f08ebe8-b781-4a32-a218-5ecd8338561d
colored_line(box_blur(example_vector, 1))
# ╔═╡ 808deca8-ee09-11ea-0ee3-1586fa1ce282
let
try
test_v = rand(n)
original = copy(test_v)
box_blur(test_v, 5)
if test_v != original
md"""
!!! danger "Oopsie!"
It looks like your function _modifies_ `v`. Can you write it without doing so? Maybe you can use `copy`.
"""
end
catch
end
end
# ╔═╡ 7b18f88d-cba8-4fa5-9413-30ab35b3025a
box_blur(v,l_box)
# ╔═╡ 7d80a1ea-a0a9-41b2-9cfe-a334717ab2f4
colored_line(box_blur(v,l_box))
# ╔═╡ bbe1a562-8d97-4112-a88a-c45c260f574d
let
result = box_blur(v, box_kernel_l)
colored_line(result)
end
# ╔═╡ 28e20950-ee0c-11ea-0e0a-b5f2e570b56e
function convolve(v::AbstractVector, k)
l = (length(k)-1)÷2
# k = OffsetArray(k, OffsetArrays.Origin(1))
return [sum([extend(v,j) for j in range(i-l,i+l,step=1)] .* k) for i in range(1,length=length(v))]
end
# ╔═╡ 9afc4dca-ee16-11ea-354f-1d827aaa61d2
md"_Let's test it!_"
# ╔═╡ cf6b05e2-ee16-11ea-3317-8919565cb56e
small_image = Gray.(rand(5,5))
# ╔═╡ e3616062-ee27-11ea-04a9-b9ec60842a64
md"- Extended with `0`:"
# ╔═╡ e5b6cd34-ee27-11ea-0d60-bd4796540b18
[get(small_image, (i, j), Gray(0)) for (i,j) in Iterators.product(-1:7,-1:7)]
# ╔═╡ d06ea762-ee27-11ea-2e9c-1bcff86a3fe0
md"- Extended with your `extend` function:"
# ╔═╡ e1dc0622-ee16-11ea-274a-3b6ec9e15ab5
[extend(small_image, i, j) for (i,j) in Iterators.product(-1:7,-1:7)]
# ╔═╡ 4bbea325-35f8-4a51-bd66-153aba4aed96
md"""
### Extending Philip
"""
# ╔═╡ c4f5a867-74ba-4106-91d4-195f6ae644d0
url = "https://user-images.githubusercontent.com/6933510/107239146-dcc3fd00-6a28-11eb-8c7b-41aaf6618935.png"
# ╔═╡ c825ebe2-511b-43ba-afdf-6226dbac48d2
philip_filename = download(url) # download to a local file. The filename is returned
# ╔═╡ 2701ab0c-b91d-47fe-b36b-4e0036ecd4aa
philip = load(philip_filename);
# ╔═╡ 84a48984-9adb-40ab-a1f1-1ab7b76c9a19
philip_head = philip[470:800, 140:410];
# ╔═╡ 3cd535e4-ee26-11ea-2482-fb4ad43dda19
[
extend(philip_head, i, j) for
i in -50:size(philip_head,1)+51,
j in -50:size(philip_head,2)+51
]
# ╔═╡ 7c41f0ca-ee15-11ea-05fb-d97a836659af
md"""
#### Exercise 2.2
👉 Implement a new method `convolve(M, K)` that applies a convolution to a 2D array `M`, using a 2D kernel `K`. Use your new method `extend` from the last exercise.
"""
# ╔═╡ 8b96e0bc-ee15-11ea-11cd-cfecea7075a0
function convolve(M::AbstractMatrix, K::AbstractMatrix)
K = OffsetArray(K, OffsetArrays.Origin(1))
center_r = (size(K,1)-1)÷2
center_c = (size(K,2)-1)÷2
result =zeros(RGB,size(M,1),size(M,2))
for y in 1:size(M,1)
for x in 1:size(M,2)
result[y,x] = sum([extend(M,i,j) for
i in y - center_r:y+center_r,
j in x - center_c:x+center_c
] .* K)
end
end
return result
end
# ╔═╡ 93284f92-ee12-11ea-0342-833b1a30625c
test_convolution = let
v = [1, 10, 100, 1000, 10000]
k = [1, 1, 0]
convolve(v, k)
end
# ╔═╡ f0c10bb0-fb62-4450-8f70-0b5e33937199
test_convolution2 = let
k = [0.005, 0.1,0.4,0.1,0.005]
convolve(v, k)
end
# ╔═╡ 5eea882c-ee13-11ea-0d56-af81ecd30a4a
colored_line(test_convolution2)
# ╔═╡ 338b1c3f-f071-4f80-86c0-a82c17349828
let
result = convolve(v, box_blur_kernel_test)
colored_line(result)
end
# ╔═╡ 5a5135c6-ee1e-11ea-05dc-eb0c683c2ce5
md"_Let's test it out! 🎃_"
# ╔═╡ 577c6daa-ee1e-11ea-1275-b7abc7a27d73
test_image_with_border = [get(small_image, (i, j), Gray(0)) for (i,j) in Iterators.product(-1:7,-1:7)]
# ╔═╡ 275a99c8-ee1e-11ea-0a76-93e3618c9588
K_test = [
-0.5 -1 -0.5;
-1 7 -1;
-0.5 -1 -0.5;
]
# ╔═╡ 0bc17a54-8798-4474-b910-01d6dc6de553
sum(K_test)
# ╔═╡ 42dfa206-ee1e-11ea-1fcd-21671042064c
convolve(test_image_with_border, K_test)
# ╔═╡ 6e53c2e6-ee1e-11ea-21bd-c9c05381be07
md"_Edit_ `K_test` _to create your own test case!_"
# ╔═╡ e7f8b41a-ee25-11ea-287a-e75d33fbd98b
convolve(philip_head, K_test)
# ╔═╡ 8a335044-ee19-11ea-0255-b9391246d231
md"""
---
You can create all sorts of effects by choosing the kernel in a smart way. Today, we will implement two special kernels, to produce a **Gaussian blur** and a **Sobel edge detection** filter.
Make sure that you have watched the lecture about convolutions!
"""
# ╔═╡ 79eb0775-3582-446b-996a-0b64301394d0
md"""
#### Exercise 2.3
The 2D Gaussian kernel will be defined using
$$G(x,y)=\frac{1}{2\pi \sigma^2}\exp\left(\frac{-(x^2+y^2)}{2\sigma^2}\right)$$
How can you express this mathematically using the 1D Gaussian function that we defined before?
"""
# ╔═╡ f4d9fd6f-0f1b-4dec-ae68-e61550cee790
gauss(x, y; σ=1) = 2π*σ^2 * gauss(x; σ=σ) * gauss(y; σ=σ)
# ╔═╡ 1c8b4658-ee0c-11ea-2ede-9b9ed7d3125e
function gaussian_kernel_1D(n; σ=1)
g = [gauss(x, σ=σ) for x in -n:n]
return g ./ sum(g)
end
# ╔═╡ d4209f39-3760-4f6e-84e6-65ba5d4575f5
gaussian_kernel_1D(4; σ=2)
# ╔═╡ a6149507-d5ba-45c1-896a-3487070d36ec
colored_line(gaussian_kernel_1D(1; σ=1))
# ╔═╡ 38eb92f6-ee13-11ea-14d7-a503ac04302e
test_gauss_1D_a = let
k = gaussian_kernel_1D(gaussian_kernel_size_1D)
if k !== missing
convolve(v, k)
end
end
# ╔═╡ b424e2aa-ee14-11ea-33fa-35491e0b9c9d
colored_line(test_gauss_1D_a)
# ╔═╡ 24c21c7c-ee14-11ea-1512-677980db1288
test_gauss_1D_b = let
v = create_bar()
k = gaussian_kernel_1D(gaussian_kernel_size_1D)
if k !== missing
convolve(v, k)
end
end
# ╔═╡ bc1c20a4-ee14-11ea-3525-63c9fa78f089
colored_line(test_gauss_1D_b)
# ╔═╡ 7c50ea80-ee15-11ea-328f-6b4e4ff20b7e
md"""
👉 Write a function that applies a **Gaussian blur** to an image. Use your previous functions, and add cells to write helper functions as needed!
"""
# ╔═╡ b1b07a14-d5e0-4162-946f-b4ebdfc8c761
# g = [gauss(x, σ=σ) for x in -n:n]
# return g ./ sum(g)
# end
# ╔═╡ aad67fd0-ee15-11ea-00d4-274ec3cda3a3
function with_gaussian_blur(image; σ=1, l=1)
g = [gauss(x,y, σ=σ) for x in -l:l,y in -l:l]
kernel = g ./ sum(g)
return convolve(image,kernel)
end
# ╔═╡ dbb59f3a-d4e6-4d35-88cb-ab7b21ce8cfd
with_gaussian_blur(philip_head,l=5)
# ╔═╡ 8ae59674-ee18-11ea-3815-f50713d0fa08
md"_Let's make it interactive. 💫_"
# ╔═╡ 96146b16-79ea-401f-b8ba-e05663a18bd8
@bind face_σ Slider(0.1:0.1:10; show_value=true)
# ╔═╡ 2cc745ce-e145-4428-af3b-926fba271b67
@bind face_l Slider(0:20; show_value=true)
# ╔═╡ d5ffc6ab-156b-4d43-ac3d-1947d0176e7f
md"""
When you set `face_σ` to a low number (e.g. `2.0`), what effect does `face_l` have? And vice versa?
"""
# ╔═╡ 7c6642a6-ee15-11ea-0526-a1aac4286cdd
md"""
#### Exercise 2.4
👉 Create a **Sobel edge detection filter**.
Here, we will need to create two filters that separately detect edges in the horizontal and vertical directions, given by the following kernels:
```math
G_x = \begin{bmatrix}
1 & 0 & -1 \\
2 & 0 & -2 \\
1 & 0 & -1 \\
\end{bmatrix};
\qquad
G_y = \begin{bmatrix}
1 & 2 & 1 \\
0 & 0 & 0 \\
-1 & -2 & -1 \\
\end{bmatrix}
```
We can think of these filterrs as derivatives in the $x$ and $y$ directions, as we discussed in lectures.
Then we combine them by finding the magnitude of the **gradient** (in the sense of multivariate calculus) by defining
$$G_\text{total} = \sqrt{G_x^2 + G_y^2},$$
where each operation applies *element-wise* on the matrices.
Use your previous functions, and add cells to write helper functions as needed!
"""
# ╔═╡ 9eeb876c-ee15-11ea-1794-d3ea79f47b75
function with_sobel_edge_detect(image)
Gx = [1 0 -1;2 0 -2;1 0 -1] .^ 2
Gy = [1 2 1;0 0 0;-1 -2 -1] .^ 2
Gt = (Gx+Gy) .^ 0.5
# println(Gt)
return convolve(image,Gt)
end
# ╔═╡ 81560674-ca03-42ca-9120-76ae5ebb8713
Gray.(with_sobel_edge_detect(philip_head))
# ╔═╡ 2d9f3ae4-9e4c-49ce-aab0-5f87aba85c3e
md"## Function library
Just some helper functions used in the notebook."
# ╔═╡ 5516c800-edee-11ea-12cf-3f8c082ef0ef
hint(text) = Markdown.MD(Markdown.Admonition("hint", "Hint", [text]))
# ╔═╡ ea435e58-ee11-11ea-3785-01af8dd72360
hint(md"Have a look at the lecture notes to see examples of adding interactivity with a slider. You can read the Interactivity and the PlutoUI sample notebooks to learn more, you can find them in Pluto's main menu. _(Right click the Pluto logo in the top left -> Open in new tab)_.")
# ╔═╡ 32a07f1d-93cd-4bf3-bac1-91afa6bb88a6
md"""
You can use the `÷` operator (you type `\div<TAB>` to get it with autocomplete) to do _integer division_. For example:
```julia
8 / 6 ≈ 1.3333333 # a floating point number!
8 // 6 == 4 // 3 # a fraction!
8 ÷ 6 == 1 # an integer!
```
""" |> hint
# ╔═╡ 649df270-ee24-11ea-397e-79c4355e38db
hint(md"`num_rows, num_columns = size(M)`")
# ╔═╡ 0cabed84-ee1e-11ea-11c1-7d8a4b4ad1af
hint(md"`num_rows, num_columns = size(K)`")
# ╔═╡ 9def5f32-ee15-11ea-1f74-f7e6690f2efa
hint(md"Can we just copy the 1D code? What is different in 2D?")
# ╔═╡ 57360a7a-edee-11ea-0c28-91463ece500d
almost(text) = Markdown.MD(Markdown.Admonition("warning", "Almost there!", [text]))
# ╔═╡ dcb8324c-edee-11ea-17ff-375ff5078f43
still_missing(text=md"Replace `missing` with your answer.") = Markdown.MD(Markdown.Admonition("warning", "Here we go!", [text]))
# ╔═╡ 58af703c-edee-11ea-2963-f52e78fc2412
keep_working(text=md"The answer is not quite right.") = Markdown.MD(Markdown.Admonition("danger", "Keep working on it!", [text]))
# ╔═╡ f3d00a9a-edf3-11ea-07b3-1db5c6d0b3cf
yays = [md"Great!", md"Yay ❤", md"Great! 🎉", md"Well done!", md"Keep it up!", md"Good job!", md"Awesome!", md"You got the right answer!", md"Let's move on to the next exercise."]
# ╔═╡ 5aa9dfb2-edee-11ea-3754-c368fb40637c
correct(text=rand(yays)) = Markdown.MD(Markdown.Admonition("correct", "Got it!", [text]))
# ╔═╡ f0c3e99d-9eb9-459e-917a-c2338af6683c
let
result = gaussian_kernel_1D(5)
if ismissing(result)
still_missing()
elseif isnothing(result)
keep_working(md"Did you forget to write `return`?")
elseif !(result isa AbstractVector)
keep_working(md"The returned object is not a `Vector`.")
elseif size(result) != (11,)
hint(md"The returned vector has the wrong dimensions.")
elseif !(sum(result) ≈ 1.0)
keep_working(md"You need to _normalize_ the result.")
elseif gaussian_kernel_1D(3; σ=1) == gaussian_kernel_1D(3; σ=2)
keep_working(md"Use the keyword argument `σ` in your function.")
else
correct()
end
end
# ╔═╡ 74d44e22-edee-11ea-09a0-69aa0aba3281
not_defined(variable_name) = Markdown.MD(Markdown.Admonition("danger", "Oopsie!", [md"Make sure that you define a variable called **$(Markdown.Code(string(variable_name)))**"]))
# ╔═╡ bcf98dfc-ee1b-11ea-21d0-c14439500971
if !@isdefined(extend)
not_defined(:extend)
else
let
result = extend([6,7],-10)
if ismissing(result)
still_missing()
elseif isnothing(result)
keep_working(md"Did you forget to write `return`?")
elseif result != 6 || extend([6,7],10) != 7
keep_working()
else
correct()
end
end
end
# ╔═╡ 7ffd14f8-ee1d-11ea-0343-b54fb0333aea
if !@isdefined(convolve)
not_defined(:convolve)
else
let
x = [1, 10, 100]
result = convolve(x, [0, 1, 1])
shouldbe = [11, 110, 200]
shouldbe2 = [2, 11, 110]
if ismissing(result)
still_missing()
elseif isnothing(result)
keep_working(md"Did you forget to write `return`?")
elseif !(result isa AbstractVector)
keep_working(md"The returned object is not a `Vector`.")
elseif size(result) != size(x)
keep_working(md"The returned vector has the wrong dimensions.")
elseif result != shouldbe && result != shouldbe2
keep_working()
else
correct()
end
end
end
# ╔═╡ d93fa3f6-c361-4dfd-a2ea-f38e682bcd6a
if !@isdefined(box_blur_kernel)
not_defined(:box_blur_kernel)
else
let
result = box_blur_kernel(2)
if ismissing(result)
still_missing()
elseif isnothing(result)
keep_working(md"Did you forget to write `return`?")
elseif !(result isa AbstractVector)
keep_working(md"The returned object is not a `Vector`.")
elseif size(result) != (5,)
hint(md"The returned vector has the wrong dimensions.")
else
x = [1, 10, 100]
result1 = box_blur(x, 2)
result2 = convolve(x, result)
if result1 ≈ result2
correct()
else
keep_working()
end
end
end
end
# ╔═╡ efd1ceb4-ee1c-11ea-350e-f7e3ea059024
if !@isdefined(extend)
not_defined(:extend)
else
let
input = [42 37; 1 0]
result = extend(input, -2, -2)
if ismissing(result)
still_missing()
elseif isnothing(result)
keep_working(md"Did you forget to write `return`?")
elseif result != 42 || extend(input, -1, 3) != 37
keep_working()
else
correct()
end
end
end
# ╔═╡ 115ded8c-ee0a-11ea-3493-89487315feb7
bigbreak = html"<br><br><br><br><br>";
# ╔═╡ 54056a02-ee0a-11ea-101f-47feb6623bec
bigbreak
# ╔═╡ a3067222-a83a-47b8-91c3-24ad78dd65c5
bigbreak
# ╔═╡ 27847dc4-ee0a-11ea-0651-ebbbb3cfd58c
bigbreak
# ╔═╡ 0001f782-ee0e-11ea-1fb4-2b5ef3d241e2
bigbreak
# ╔═╡ 5842895a-ee10-11ea-119d-81e4c4c8c53b
bigbreak
# ╔═╡ dfb7c6be-ee0d-11ea-194e-9758857f7b20
function camera_input(;max_size=200, default_url="https://i.imgur.com/SUmi94P.png")
"""
<span class="pl-image waiting-for-permission">
<style>
.pl-image.popped-out {
position: fixed;
top: 0;
right: 0;
z-index: 5;
}
.pl-image #video-container {
width: 250px;
}
.pl-image video {
border-radius: 1rem 1rem 0 0;
}
.pl-image.waiting-for-permission #video-container {
display: none;
}
.pl-image #prompt {
display: none;
}
.pl-image.waiting-for-permission #prompt {
width: 250px;
height: 200px;
display: grid;
place-items: center;
font-family: monospace;
font-weight: bold;
text-decoration: underline;
cursor: pointer;
border: 5px dashed rgba(0,0,0,.5);
}
.pl-image video {
display: block;
}
.pl-image .bar {
width: inherit;
display: flex;
z-index: 6;
}
.pl-image .bar#top {
position: absolute;
flex-direction: column;
}
.pl-image .bar#bottom {
background: black;
border-radius: 0 0 1rem 1rem;
}
.pl-image .bar button {
flex: 0 0 auto;
background: rgba(255,255,255,.8);
border: none;
width: 2rem;
height: 2rem;
border-radius: 100%;
cursor: pointer;
z-index: 7;
}
.pl-image .bar button#shutter {
width: 3rem;
height: 3rem;
margin: -1.5rem auto .2rem auto;
}
.pl-image video.takepicture {
animation: pictureflash 200ms linear;
}
@keyframes pictureflash {
0% {
filter: grayscale(1.0) contrast(2.0);
}
100% {
filter: grayscale(0.0) contrast(1.0);
}
}
</style>
<div id="video-container">
<div id="top" class="bar">
<button id="stop" title="Stop video">✖</button>
<button id="pop-out" title="Pop out/pop in">⏏</button>
</div>
<video playsinline autoplay></video>
<div id="bottom" class="bar">
<button id="shutter" title="Click to take a picture">📷</button>
</div>
</div>
<div id="prompt">
<span>
Enable webcam
</span>
</div>
<script>
// based on https://github.com/fonsp/printi-static (by the same author)
const span = currentScript.parentElement
const video = span.querySelector("video")
const popout = span.querySelector("button#pop-out")
const stop = span.querySelector("button#stop")
const shutter = span.querySelector("button#shutter")
const prompt = span.querySelector(".pl-image #prompt")
const maxsize = $(max_size)
const send_source = (source, src_width, src_height) => {
const scale = Math.min(1.0, maxsize / src_width, maxsize / src_height)
const width = Math.floor(src_width * scale)
const height = Math.floor(src_height * scale)
const canvas = html`<canvas width=\${width} height=\${height}>`
const ctx = canvas.getContext("2d")
ctx.drawImage(source, 0, 0, width, height)
span.value = {
width: width,
height: height,
data: ctx.getImageData(0, 0, width, height).data,
}
span.dispatchEvent(new CustomEvent("input"))
}
const clear_camera = () => {
window.stream.getTracks().forEach(s => s.stop());
video.srcObject = null;
span.classList.add("waiting-for-permission");
}
prompt.onclick = () => {
navigator.mediaDevices.getUserMedia({
audio: false,
video: {
facingMode: "environment",
},
}).then(function(stream) {
stream.onend = console.log
window.stream = stream
video.srcObject = stream
window.cameraConnected = true
video.controls = false
video.play()
video.controls = false
span.classList.remove("waiting-for-permission");