-
Notifications
You must be signed in to change notification settings - Fork 0
/
homework1.jl
2404 lines (1949 loc) · 75.4 KB
/
homework1.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.19.46
#> [frontmatter]
#> chapter = 1
#> section = 2.5
#> order = 2.5
#> homework_number = 1
#> title = "Images and Arrays"
#> layout = "layout.jlhtml"
#> tags = ["homework", "module1", "image", "track_julia", "track_math", "track_climate", "track_data", "programming", "interactive", "type", "matrix"]
#> description = "Practice Julia basics by working with arrays of colors. At the end of this homework, you can see all of your filters applied to your webcam image!"
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 iv = try Base.loaded_modules[Base.PkgId(Base.UUID("6e696c72-6542-2067-7265-42206c756150"), "AbstractPlutoDingetjes")].Bonds.initial_value catch; b -> missing; end
local el = $(esc(element))
global $(esc(def)) = Core.applicable(Base.get, el) ? Base.get(el) : iv(el)
el
end
end
# ╔═╡ 65780f00-ed6b-11ea-1ecf-8b35523a7ac0
begin
import ImageMagick
using Images
using PlutoUI
using HypertextLiteral
end
# ╔═╡ ac8ff080-ed61-11ea-3650-d9df06123e1f
md"""
# **Homework 1** - _images and arrays_
`18.S191`, Fall 2023
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.
Feel free to ask questions!
"""
# ╔═╡ 5f95e01a-ee0a-11ea-030c-9dba276aba92
md"""
#### Initializing packages
_When running this notebook for the first time, this could take up to 15 minutes. Hang in there!_
"""
# ╔═╡ 540ccfcc-ee0a-11ea-15dc-4f8120063397
md"""
## **Exercise 1** - _Manipulating vectors (1D images)_
A `Vector` is a 1D array. We can think of that as a 1D image.
"""
# ╔═╡ 467856dc-eded-11ea-0f83-13d939021ef3
example_vector = [0.5, 0.4, 0.3, 0.2, 0.1, 0.0, 0.7, 0.0, 0.7, 0.9]
# ╔═╡ ad6a33b0-eded-11ea-324c-cfabfd658b56
md"""
$(html"<br>")
#### Exercise 1.1
👉 Make a random vector `random_vect` of length 10 using the `rand` function.
"""
# ╔═╡ f51333a6-eded-11ea-34e6-bfbb3a69bcb0
random_vect = missing # replace `missing` with your code!
# ╔═╡ 5da8cbe8-eded-11ea-2e43-c5b7cc71e133
begin
colored_line(x::Vector) = hcat(Gray.(Float64.(x)))'
colored_line(x::Any) = nothing
end
# ╔═╡ 56ced344-eded-11ea-3e81-3936e9ad5777
colored_line(example_vector)
# ╔═╡ b18e2c54-edf1-11ea-0cbf-85946d64b6a2
colored_line(random_vect)
# ╔═╡ 77adb065-bfd4-4680-9c2a-ad4d92689dbf
md"#### Exercise 1.2
👉 Make a function `my_sum` using a `for` loop, which computes the total of a vector of numbers."
# ╔═╡ bd907ee1-5253-4cae-b5a5-267dac24362a
function my_sum(xs)
# your code here!
return missing
end
# ╔═╡ 6640110a-d171-4b32-8d12-26979a36b718
my_sum([1,2,3])
# ╔═╡ cf738088-eded-11ea-2915-61735c2aa990
md"#### Exercise 1.3
👉 Use your `my_sum` function to write a function `mean`, which computes the mean/average of a vector of numbers."
# ╔═╡ 0ffa8354-edee-11ea-2883-9d5bfea4a236
function mean(xs)
# your code here!
return missing
end
# ╔═╡ 1f104ce4-ee0e-11ea-2029-1d9c817175af
mean([1, 2, 3])
# ╔═╡ 1f229ca4-edee-11ea-2c56-bb00cc6ea53c
md"👉 Define `m` to be the mean of `random_vect`."
# ╔═╡ 2a391708-edee-11ea-124e-d14698171b68
m = missing # replace `missing` with your code!
# ╔═╡ e2863d4c-edef-11ea-1d67-332ddca03cc4
md"""#### Exercise 1.4
👉 Write a function `demean`, which takes a vector `xs` and subtracts the mean from each value in `xs`. Use your `mean` function!"""
# ╔═╡ ea8d92f8-159c-4161-8c54-bab7bc00f290
md"""
> ### Note about _mutation_
> There are two ways to think about this exercise, you could _modify_ the original vector, or you can _create a new vector_. We often prefer the second version, so that the original data is preserved. We generally only use code of the first variant in the most performance-sensitive parts of a program, as it requires more care to write and use correctly. _**Be careful not to get carried away in optimizing code**, especially when learning a new language!_
>
> There is a convention among Julians that functions that modify their argument have a `!` in their name. For example, `sort(x)` returns a sorted _copy_ of `x`, while `sort!(x)` _modifies_ `x` to be sorted.
>
> #### Tips for writing non-mutating code
> 1. _Rewriting_ an existing mutating function to be non-mutating can feel like a 'tedious' and 'inefficient' process. Often, instead of trying to **rewrite** a mutating function, it's best to take a step back and try to think of your problem as _constructing something new_. Instead of a `for` loop, it might make more sense to use **descriptive** primitives like [broadcasting with the dot syntax](https://docs.julialang.org/en/v1/manual/functions/#man-vectorized) (also for [math operators](https://docs.julialang.org/en/v1/manual/mathematical-operations/#man-dot-operators)), and [map and filter](https://www.youtube.com/watch?v=_O-HBDZMLrM).
>
>
> 2. If a mutating algorithm makes the most sense for your problem, then you can first use `copy` to create a copy of an array, and then modify that copy.
>
> We will cover this topic more in the later exercises!
"""
# ╔═╡ ec5efe8c-edef-11ea-2c6f-afaaeb5bc50c
function demean(xs)
# your code here!
return missing
end
# ╔═╡ d6ddafdd-1a44-48c7-b49a-554073cdf331
test_vect = let
# feel free to change your test case here!
to_create = [-1.0, -1.5, 8.5]
####
# this cell is a bit funky to deal with a common pitfall from last year
# it regenerates the vector if you accidentally wrote a mutating function
# don't worry about how it works for this exercise!
demean
to_create
end
# ╔═╡ 29e10640-edf0-11ea-0398-17dbf4242de3
md"To verify our function, let's check that the mean of the `demean(test_vect)` is 0: (_Due to floating-point round-off error it may *not* be *exactly* 0._)"
# ╔═╡ 38155b5a-edf0-11ea-3e3f-7163da7433fb
demeaned_test_vect = demean(test_vect)
# ╔═╡ 1267e961-5b75-4b55-8080-d45316a03b9b
mean(demeaned_test_vect)
# ╔═╡ a5f8bafe-edf0-11ea-0da3-3330861ae43a
md"""
#### Exercise 1.5
👉 Generate a vector of 100 elements. Where:
- the center 20 elements are set to `1`, and
- all other elements are `0`.
"""
# ╔═╡ b6b65b94-edf0-11ea-3686-fbff0ff53d08
function create_bar()
# your code here!
return missing
end
# ╔═╡ 4a5e9d2c-dd90-4bb0-9e31-3f5c834406b4
create_bar()
# ╔═╡ d862fb16-edf1-11ea-36ec-615d521e6bc0
colored_line(create_bar())
# ╔═╡ 59414833-a108-4b1e-9a34-0f31dc907c6e
url = "https://user-images.githubusercontent.com/6933510/107239146-dcc3fd00-6a28-11eb-8c7b-41aaf6618935.png"
# ╔═╡ c5484572-ee05-11ea-0424-f37295c3072d
philip_filename = download(url) # download to a local file. The filename is returned
# ╔═╡ c8ecfe5c-ee05-11ea-322b-4b2714898831
philip = load(philip_filename)
# ╔═╡ e86ed944-ee05-11ea-3e0f-d70fc73b789c
md"_Hi there Philip_"
# ╔═╡ 6ccd8902-0dd9-4335-a11a-ee7f9a1a6c09
philip_head = philip[470:800, 140:410]
# ╔═╡ 15088baa-c337-405d-8885-19a6e2bfd6aa
md"""
Recall from [Section 1.1](https://computationalthinking.mit.edu/Spring21/week1/) that in Julia, an _image_ is just a 2D array of color objects:
"""
# ╔═╡ 7ad4f6bc-588e-44ab-8ca9-c87cd1048442
typeof(philip)
# ╔═╡ a55bb5ca-600b-4aa0-b95f-7ece20845c9b
md"""
Every pixel (i.e. _element of the 2D array_) is of the `RGB` type:
"""
# ╔═╡ c5dc0cc8-9305-47e6-8b20-a9f8ef867799
philip_pixel = philip[100,100]
# ╔═╡ de772e21-0bea-4fd2-868a-9a7d32550bc9
typeof(philip_pixel)
# ╔═╡ 21bdc692-91ee-474d-ae98-455913a2342e
md"""
To get the values of its individual color channels, use the `r`, `g` and `b` _attributes_:
"""
# ╔═╡ 2ae3f379-96ce-435d-b863-deba4586ec71
philip_pixel.r, philip_pixel.g, philip_pixel.b
# ╔═╡ c49ba901-d798-489a-963c-4cc113c7abfd
md"""
And to create an `RGB` object yourself:
"""
# ╔═╡ 93451c37-77e1-4d4f-9788-c2a3da1401ee
RGB(0.1, 0.4, 0.7)
# ╔═╡ f52e4914-2926-4a42-9e45-9caaace9a7db
md"""
#### Exercise 2.1
👉 Write a function **`get_red`** that takes a single pixel, and returns the value of its red channel.
"""
# ╔═╡ a8b2270a-600c-4f83-939e-dc5ab35f4735
function get_red(pixel::AbstractRGB)
# your code here!
return missing
end
# ╔═╡ c320b39d-4cea-4fa1-b1ce-053c898a67a6
get_red(RGB(0.8, 0.1, 0.0))
# ╔═╡ d8cf9bd5-dbf7-4841-acf9-eef7e7cabab3
md"""
#### Exercise 2.2
👉 Write a function **`get_reds`** (note the extra `s`) that accepts a 2D color array called `image`, and returns a 2D array with the red channel value of each pixel. (The result should be a 2D array of _numbers_.) Use your function `get_red` from the previous exercise.
"""
# ╔═╡ ebe1d05c-f6aa-437d-83cb-df0ba30f20bf
function get_reds(image::AbstractMatrix)
# your code here!
return missing
end
# ╔═╡ c427554a-6f6a-43f1-b03b-f83239887cee
get_reds(philip_head)
# ╔═╡ 4fd07e01-2f8b-4ec9-9f4f-8a9e5ff56fb6
md"""
Great! By extracting the red channel value of each pixel, we get a 2D array of numbers. We went from an image (2D array of RGB colors) to a matrix (2D array of numbers).
#### Exercise 2.3
Let's try to visualize this matrix. Right now, it is displayed in text form, but because the image is quite large, most rows and columns don't fit on the screen. Instead, a better way to visualize it is to **view a number matrix as an image**.
This is easier than you might think! We just want to map each number to an `RGB` object, and the result will be a 2D array of `RGB` objects, which Julia will display as an image.
First, let's define a function that turns a _number_ into a _color_.
"""
# ╔═╡ 97c15896-6d99-4292-b7d7-4fcd2353656f
function value_as_color(x)
return RGB(x, 0, 0)
end
# ╔═╡ cbb9bf41-4c21-42c7-b0e0-fc1ce29e0eb1
value_as_color(0.0), value_as_color(0.6), value_as_color(1.0)
# ╔═╡ 3f1a670b-44c2-4cab-909c-65f4ae9ed14b
md"""
👉 Use the functions `get_reds` and `value_as_color` to visualize the red channel values of `philip_head`. Tip: Like in previous exercises, use broadcasting ('dot syntax') to apply a function _element-wise_.
Use the ➕ button at the bottom left of this cell to add more cells.
"""
# ╔═╡ 21ba6e75-55a2-4614-9b5d-ea6378bf1d98
# ╔═╡ f7825c18-ff28-4e23-bf26-cc64f2f5049a
md"""
#### Exercise 2.4
👉 Write four more functions, `get_green`, `get_greens`, `get_blue` and `get_blues`, to be the equivalents of `get_red` and `get_reds`. Use the ➕ button at the bottom left of this cell to add new cells.
"""
# ╔═╡ d994e178-78fd-46ab-a1bc-a31485423cad
# ╔═╡ c54ccdea-ee05-11ea-0365-23aaf053b7d7
md"""
#### Exercise 2.5
👉 Write a function **`mean_color`** that accepts an object called `image`. It should calculate the mean amounts of red, green and blue in the image and return the average color. Be sure to use functions from previous exercises!
"""
# ╔═╡ f6898df6-ee07-11ea-2838-fde9bc739c11
function mean_color(image)
# your code here!
return missing
end
# ╔═╡ 5be9b144-ee0d-11ea-2a8d-8775de265a1d
mean_color(philip)
# ╔═╡ 5f6635b4-63ed-4a62-969c-bd4084a8202f
md"""
_At the end of this homework, you can see all of your filters applied to your webcam image!_
"""
# ╔═╡ 63e8d636-ee0b-11ea-173d-bd3327347d55
function invert(color::AbstractRGB)
# your code here!
return missing
end
# ╔═╡ 2cc2f84e-ee0d-11ea-373b-e7ad3204bb00
md"Let's invert some colors:"
# ╔═╡ b8f26960-ee0a-11ea-05b9-3f4bc1099050
color_black = RGB(0.0, 0.0, 0.0)
# ╔═╡ 5de3a22e-ee0b-11ea-230f-35df4ca3c96d
invert(color_black)
# ╔═╡ 4e21e0c4-ee0b-11ea-3d65-b311ae3f98e9
color_red = RGB(0.8, 0.1, 0.1)
# ╔═╡ 6dbf67ce-ee0b-11ea-3b71-abc05a64dc43
invert(color_red)
# ╔═╡ 846b1330-ee0b-11ea-3579-7d90fafd7290
md"👉 Can you invert the picture of Philip?"
# ╔═╡ 943103e2-ee0b-11ea-33aa-75a8a1529931
philip_inverted = missing # replace `missing` with your code!
# ╔═╡ 55b138b7-19fb-4da1-9eb1-1e8304528251
md"""
_At the end of this homework, you can see all of your filters applied to your webcam image!_
"""
# ╔═╡ f68d4a36-ee07-11ea-0832-0360530f102e
md"""
#### Exercise 3.2
👉 Look up the documentation on the `floor` function. Use it to write a function `quantize(x::Number)` that takes in a value $x$ (which you can assume is between 0 and 1) and "quantizes" it into bins of width 0.1. For example, check that 0.267 gets mapped to 0.2.
"""
# ╔═╡ fbd1638d-8d7a-4d12-aff9-9c160cc3fd74
function quantize(x::Number)
# your code here!
return missing
end
# ╔═╡ 7720740e-2d2b-47f7-98fd-500ed3eee479
md"""
#### Intermezzo: _multiple methods_
In Julia, we often write multiple methods for the same function. When a function is called, the method is chosen based on the input arguments. Let's look at an example:
These are two _methods_ to the same function, because they have
> **the same name, but different input types**
"""
# ╔═╡ 90421bca-0804-4d6b-8bd0-3ddbd54cc5fe
function double(x::Number)
return x * 2
end
# ╔═╡ b2329e4c-6204-453e-8998-2414b869b808
function double(x::Vector)
return [x..., x...]
end
# ╔═╡ 23fcd65f-0182-41f3-80ec-d85b05136c47
md"""
When we call the function `double`, Julia will decide which method to call based on the given input argument!
"""
# ╔═╡ 5055b74c-b98d-41fa-a0d8-cb36200d82cc
double(24)
# ╔═╡ 8db17b2b-0cf9-40ba-8f6f-2e53be7b6355
double([1,2,37])
# ╔═╡ a8a597e0-a01c-40cd-9902-d56430afd938
md"""
We call this **multiple dispatch**, and it is one of Julia's key features. Throughout this course, you will see lots of real-world application, and learn to use multiple dispatch to create flexible and readable abstractions!
"""
# ╔═╡ f6b218c0-ee07-11ea-2adb-1968c4fd473a
md"""
#### Exercise 3.3
👉 Write the second **method** of the function `quantize`, i.e. a new *version* of the function with the *same* name. This method will accept a color object called `color`, of the type `AbstractRGB`.
Here, `::AbstractRGB` is a **type annotation**. This ensures that this version of the function will be chosen when passing in an object whose type is a **subtype** of the `AbstractRGB` abstract type. For example, both the `RGB` and `RGBX` types satisfy this.
The method you write should return a new `RGB` object, in which each component ($r$, $g$ and $b$) are quantized. Use your previous method for `quantize`!
"""
# ╔═╡ 04e6b486-ceb7-45fe-a6ca-733703f16357
function quantize(color::AbstractRGB)
# your code here!
return missing
end
# ╔═╡ f6bf64da-ee07-11ea-3efb-05af01b14f67
md"""
#### Exercise 3.4
👉 Write a method `quantize(image::AbstractMatrix)` that quantizes an image by quantizing each pixel in the image. (You may assume that the matrix is a matrix of color objects.)
"""
# ╔═╡ 13e9ec8d-f615-4833-b1cf-0153010ccb65
function quantize(image::AbstractMatrix)
# your code here!
return missing
end
# ╔═╡ f6a655f8-ee07-11ea-13b6-43ca404ddfc7
quantize(0.267), quantize(0.91)
# ╔═╡ 25dad7ce-ee0b-11ea-3e20-5f3019dd7fa3
md"Let's apply your method!"
# ╔═╡ 9751586e-ee0c-11ea-0cbb-b7eda92977c9
quantize(philip)
# ╔═╡ f6d6c71a-ee07-11ea-2b63-d759af80707b
md"""
#### Exercise 3.5
👉 Write a function `noisify(x::Number, s)` to add randomness of intensity $s$ to a value $x$, i.e. to add a random value between $-s$ and $+s$ to $x$. If the result falls outside the range $[0, 1]$ you should "clamp" it to that range. (Julia has a built-in `clamp` function, or you can write your own function.)
"""
# ╔═╡ f38b198d-39cf-456f-a841-1ba08f206010
function noisify(x::Number, s)
# your code here!
return missing
end
# ╔═╡ f6fc1312-ee07-11ea-39a0-299b67aee3d8
md"""
👉 Write the second method `noisify(c::AbstractRGB, s)` to add random noise of intensity $s$ to each of the $(r, g, b)$ values in a colour.
Use your previous method for `noisify`. _(Remember that Julia chooses which method to use based on the input arguments. So to call the method from the previous exercise, the first argument should be a number.)_
"""
# ╔═╡ db4bad9f-df1c-4640-bb34-dd2fe9bdce18
function noisify(color::AbstractRGB, s)
# your code here!
return missing
end
# ╔═╡ 0000b7f8-4c43-4dd8-8665-0dfe59e74c0a
md"""
Noise strength:
"""
# ╔═╡ 774b4ce6-ee1b-11ea-2b48-e38ee25fc89b
@bind color_noise Slider(0:0.01:1, show_value=true)
# ╔═╡ 48de5bc2-72d3-11eb-3fd9-eff2b686cb75
md"""
> ### Note about _array comprehension_
> At this point, you already know of a few ways to make a new array based on one that already exists.
> 1. you can use a for loop to go through a array
> 1. you can use function broadcasting over a array
> 1. you can use _**array comprehension**_!
>
> The third option you are about to see demonstrated below and following the following syntax:
>
> ```[function_to_apply(args) for args in some_iterable_of_your_choice]```
>
> This creates a new iterable that matches what you iterate through in the second part of the comprehension. Below is an example with `for` loops through two iterables that creates a 2-dimensional `Array`.
"""
# ╔═╡ f70823d2-ee07-11ea-2bb3-01425212aaf9
md"""
👉 Write the third method `noisify(image::AbstractMatrix, s)` to noisify each pixel of an image. This function should be a single line!
"""
# ╔═╡ 21a5885d-00ab-428b-96c3-c28c98c4ca6d
function noisify(image::AbstractMatrix, s)
# your code here!
return missing
end
# ╔═╡ 1ea53f41-b791-40e2-a0f8-04e13d856829
noisify(0.5, 0.1) # edit this test case!
# ╔═╡ 7e4aeb70-ee1b-11ea-100f-1952ba66f80f
(original=color_red, with_noise=noisify(color_red, color_noise))
# ╔═╡ 8e848279-1b3e-4f32-8c0c-45693d12de96
[
noisify(color_red, strength)
for
strength in 0 : 0.05 : 1,
row in 1:10
]'
# ╔═╡ d896b7fd-20db-4aa9-bbcf-81b1cd44ec46
md"""
#### Exercise 3.6
Move the slider below to set the amount of noise applied to the image of Philip.
"""
# ╔═╡ e70a84d4-ee0c-11ea-0640-bf78653ba102
@bind philip_noise Slider(0:0.01:1, show_value=true)
# ╔═╡ ac15e0d0-ee0c-11ea-1eaf-d7f88b5df1d7
noisify(philip_head, philip_noise)
# ╔═╡ 9604bc44-ee1b-11ea-28f8-7f7af8d0cbb2
if philip_noise == 1
md"""
> #### What's this?
>
> The noise intensity is `1.0`, but we can still recognise Philip in the picture...
>
> 👉 Modify the definition of the slider to go further than `1.0`.
"""
end
# ╔═╡ f714699e-ee07-11ea-08b6-5f5169861b57
md"""
👉 For which noise intensity does it become unrecognisable?
You may need noise intensities larger than 1. Why?
"""
# ╔═╡ bdc2df7c-ee0c-11ea-2e9f-7d2c085617c1
answer_about_noise_intensity = md"""
The image is unrecognisable with intensity ...
"""
# ╔═╡ e87e0d14-43a5-490d-84d9-b14ece472061
md"""
### Results
"""
# ╔═╡ ee5f21fb-1076-42b6-8926-8bbb6ed0ad67
function custom_filter(pixel::AbstractRGB)
# your code here!
return pixel
end
# ╔═╡ 9e5a08dd-332a-486b-94ab-15c49e72e522
function custom_filter(image::AbstractMatrix)
return custom_filter.(image)
end
# ╔═╡ 756d150a-b7bf-4bf5-b372-5b0efa80d987
md"## Function library
Just some helper functions used in the notebook."
# ╔═╡ 4bc94bec-da39-4f8a-82ee-9953ed73b6a4
hint(text) = Markdown.MD(Markdown.Admonition("hint", "Hint", [text]))
# ╔═╡ b1d5ca28-edf6-11ea-269e-75a9fb549f1d
md"""
You can find out more about any function (like `rand`) by clicking on the Live Docs in the bottom right of this Pluto window, and typing a function name in the top.
![image](https://user-images.githubusercontent.com/6933510/107848812-c934df80-6df6-11eb-8a32-663d802f5d11.png)
![image](https://user-images.githubusercontent.com/6933510/107848846-0f8a3e80-6df7-11eb-818a-7271ecb9e127.png)
We recommend that you leave the window open while you work on Julia code. It will continually look up documentation for anything you type!
#### Help, I don't see the Live Docs!
Try the following:
🙋 **Are you viewing a static preview?** The Live Docs only work if you _run_ the notebook. If you are reading this on our course website, then click the button in the top right to run the notebook.
🙋 **Is your screen too small?** Try resizing your window or zooming out.
""" |> hint
# ╔═╡ 24090306-7395-4f2f-af31-34f7486f3945
hint(md"""Check out this page for a refresher on basic Julia syntax:
[Basic Julia Syntax](https://computationalthinking.mit.edu/Fall24/week0/basic_syntax/)""")
# ╔═╡ aa1ff74a-4e78-4ef1-8b8d-3a60a168cf6d
hint(md"""
In [Section 1.1](https://computationalthinking.mit.edu/Fall24/images_abstractions/images/), we drew a red square on top of the image Philip with a simple command...
""")
# ╔═╡ 50e2b0fb-b06d-4ac1-bdfb-eab833466736
md"""
This exercise can be quite difficult if you use a `for` loop or list comprehension.
Instead, you should use the [dot syntax](https://docs.julialang.org/en/v1/manual/functions/#man-vectorized) to apply a function _element-wise_ to an array. For example, this is how you get the square root of `3`:
```
sqrt(3)
```
and this is how you get the square roots of 1, 2 and 3:
```
sqrt.([1, 2, 3])
```
""" |> hint
# ╔═╡ f6ef2c2e-ee07-11ea-13a8-2512e7d94426
hint(md"`rand()` generates a (uniformly) random floating-point number between $0$ and $1$.")
# ╔═╡ 8ce6ad06-819c-4af5-bed7-56ecc08c97be
almost(text) = Markdown.MD(Markdown.Admonition("warning", "Almost there!", [text]))
# ╔═╡ dfa40e89-03fc-4a7a-825e-92d67ee217b2
still_missing(text=md"Replace `missing` with your answer.") = Markdown.MD(Markdown.Admonition("warning", "Here we go!", [text]))
# ╔═╡ 086ec1ff-b62d-4566-9973-5b2cc3353409
keep_working(text=md"The answer is not quite right.") = Markdown.MD(Markdown.Admonition("danger", "Keep working on it!", [text]))
# ╔═╡ 2f6fb3a6-bb5d-4c7a-9297-84dd4b16c7c3
yays = [md"Fantastic!", md"Splendid!", 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 section."]
# ╔═╡ c22f688b-dc04-4a94-b541-fe06266c5446
correct(text=rand(yays)) = Markdown.MD(Markdown.Admonition("correct", "Got it!", [text]))
# ╔═╡ 09102183-f9fb-4d89-b4f9-5d76af7b8e90
let
result = get_red(RGB(0.2, 0.3, 0.4))
if ismissing(result)
still_missing()
elseif isnothing(result)
keep_working(md"Did you forget to write `return`?")
elseif result == 0.2
correct()
else
keep_working()
end
end
# ╔═╡ 63ac142e-6d9d-4109-9286-030a02c900b4
let
test = [RGB(0.2, 0, 0) RGB(0.6, 0, 0)]
result = get_reds(test)
if ismissing(result)
still_missing()
elseif isnothing(result)
keep_working(md"Did you forget to write `return`?")
elseif result == [ 0.2 0.6 ]
correct()
else
keep_working()
end
end
# ╔═╡ 80a4cb23-49c9-4446-a3ec-b2203128dc27
let
result = invert(RGB(1.0, 0.5, 0.25)) # I chose these values because they can be represented exactly by Float64
shouldbe = RGB(0.0, 0.5, 0.75)
if ismissing(result)
still_missing()
elseif isnothing(result)
keep_working(md"Did you forget to write `return`?")
elseif !(result isa AbstractRGB)
keep_working(md"You need to return a _color_, i.e. an object of type `RGB`. Use `RGB(r, g, b)` to create a color with channel values `r`, `g` and `b`.")
elseif !(result == shouldbe)
keep_working()
else
correct()
end
end
# ╔═╡ a6d9635b-85ed-4590-ad09-ca2903ea8f1d
let
result = quantize(RGB(.297, .1, .0))
if ismissing(result)
still_missing()
elseif isnothing(result)
keep_working(md"Did you forget to write `return`?")
elseif !(result isa AbstractRGB)
keep_working(md"You need to return a _color_, i.e. an object of type `RGB`. Use `RGB(r, g, b)` to create a color with channel values `r`, `g` and `b`.")
elseif result != RGB(0.2, .1, .0)
keep_working()
else
correct()
end
end
# ╔═╡ 31ef3710-e4c9-4aa7-bd8f-c69cc9a977ee
let
result = noisify(0.5, 0)
if ismissing(result)
still_missing()
elseif isnothing(result)
keep_working(md"Did you forget to write `return`?")
elseif result == 0.5
results = [noisify(0.9, 0.1) for _ in 1:1000]
if 0.8 ≤ minimum(results) < 0.81 && 0.99 ≤ maximum(results) ≤ 1
result = noisify(5, 3)
if result == 1
correct()
else
keep_working(md"The result should be restricted to the range ``[0,1]``.")
end
else
keep_working()
end
else
keep_working(md"What should `noisify(0.5, 0)` be?")
correct()
end
end
# ╔═╡ ab3d1b70-88e8-4118-8d3e-601a8a68f72d
not_defined(variable_name) = Markdown.MD(Markdown.Admonition("danger", "Oopsie!", [md"Make sure that you define a variable called **$(Markdown.Code(string(variable_name)))**"]))
# ╔═╡ 397941fc-edee-11ea-33f2-5d46c759fbf7
if !@isdefined(random_vect)
not_defined(:random_vect)
elseif ismissing(random_vect)
still_missing()
elseif !(random_vect isa Vector)
keep_working(md"`random_vect` should be a `Vector`.")
elseif eltype(random_vect) != Float64
almost(md"""
You generated a vector of random integers. For the remaining exercises, we want a vector of `Float64` numbers.
The (optional) first argument to `rand` specifies the **type** of elements to generate. For example: `rand(Bool, 10)` generates 10 values that are either `true` or `false`. (Try it!)
""")
elseif length(random_vect) != 10
keep_working(md"`random_vect` does not have the correct size.")
elseif length(Set(random_vect)) != 10
keep_working(md"`random_vect` is not 'random enough'")
else
correct(md"Well done! You can run your code again to generate a new vector!")
end
# ╔═╡ e0bfc973-2808-4f84-b065-fb3d05401e30
if !@isdefined(my_sum)
not_defined(:my_sum)
else
let
result = my_sum([1,2,3])
if ismissing(result)
still_missing()
elseif isnothing(result)
keep_working(md"Did you forget to write `return`?")
elseif result != 6
keep_working()
else
correct()
end
end
end
# ╔═╡ 38dc80a0-edef-11ea-10e9-615255a4588c
if !@isdefined(mean)
not_defined(:mean)
else
let
result = mean([1,2,3])
if ismissing(result)
still_missing()
elseif isnothing(result)
keep_working(md"Did you forget to write `return`?")
elseif result != 2
keep_working()
else
correct()
end
end
end
# ╔═╡ 2b1ccaca-edee-11ea-34b0-c51659f844d0
if !@isdefined(m)
not_defined(:m)
elseif ismissing(m)
still_missing()
elseif !(m isa Number)
keep_working(md"`m` should be a number.")
elseif m != mean(random_vect)
keep_working()
else
correct()
end
# ╔═╡ adf476d8-a334-4b35-81e8-cc3b37de1f28
if !@isdefined(mean)
not_defined(:mean)
else
let
input = Float64[1,2,3]
result = demean(input)
if input === result
almost(md"""
It looks like you **modified** `xs` inside the function.
It is preferable to avoid mutation inside functions, because you might want to use the original data again. For example, applying `demean` to a dataset of sensor readings would **modify** the original data, and the rest of your analysis would be erroneous.
""")
elseif ismissing(result)
still_missing()
elseif isnothing(result)
keep_working(md"Did you forget to write `return`?")
elseif !(result isa AbstractVector) || length(result) != 3
keep_working(md"Return a vector of the same size as `xs`.")
elseif abs(sum(result) / 3) < 1e-10
correct()
else
keep_working()
end
end
end
# ╔═╡ e3394c8a-edf0-11ea-1bb8-619f7abb6881
if !@isdefined(create_bar)
not_defined(:create_bar)
else
let
result = create_bar()
if ismissing(result)
still_missing()
elseif isnothing(result)
keep_working(md"Did you forget to write `return`?")
elseif !(result isa Vector) || length(result) != 100
keep_working(md"The result should be a `Vector` with 100 elements.")
elseif result[[1,50,100]] != [0,1,0]
keep_working()
else
correct()
end
end
end
# ╔═╡ 4d0158d0-ee0d-11ea-17c3-c169d4284acb
if !@isdefined(mean_color)
not_defined(:mean_color)
else
let
input = reshape([RGB(1.0, 1.0, 1.0), RGB(1.0, 1.0, 0.0)], (2, 1))
result = mean_color(input)
shouldbe = RGB(1.0, 1.0, 0.5)
if ismissing(result)
still_missing()
elseif isnothing(result)
keep_working(md"Did you forget to write `return`?")
elseif !(result isa AbstractRGB)
keep_working(md"You need to return a _color_, i.e. an object of type `RGB`. Use `RGB(r, g, b)` to create a color with channel values `r`, `g` and `b`.")
elseif !(result == shouldbe)
keep_working()
else
correct()
end
end
end
# ╔═╡ c905b73e-ee1a-11ea-2e36-23b8e73bfdb6
if !@isdefined(quantize)
not_defined(:quantize)
else
let
result = quantize(.3)
if ismissing(result)
still_missing()
elseif isnothing(result)
keep_working(md"Did you forget to write `return`?")
elseif result != .3
if quantize(0.35) == .3
almost(md"What should quantize(`0.2`) be?")
else
keep_working()
end
else
correct()
end
end
end
# ╔═╡ 8cb0aee8-5774-4490-9b9e-ada93416c089
todo(text) = HTML("""<div
style="background: rgb(220, 200, 255); padding: 2em; border-radius: 1em;"
><h1>TODO</h1>$(repr(MIME"text/html"(), text))</div>""")
# ╔═╡ 115ded8c-ee0a-11ea-3493-89487315feb7
bigbreak = html"<br><br><br><br><br>";
# ╔═╡ 54056a02-ee0a-11ea-101f-47feb6623bec
bigbreak
# ╔═╡ e083b3e8-ed61-11ea-2ec9-217820b0a1b4
md"""
$(bigbreak)
## **Exercise 2** - _Manipulating images_
In this exercise we will get familiar with matrices (2D arrays) in Julia, by manipulating images.
Recall that in Julia images are matrices of `RGB` color objects.
Let's load a picture of Philip again.
"""
# ╔═╡ f6cc03a0-ee07-11ea-17d8-013991514d42
md"""
$(bigbreak)
## Exercise 3 - _More filters_
In the previous exercises, we learned how to use Julia's _dot syntax_ to apply a function _element-wise_ to an array. In this exercise, we will use this to write more image filters, that you can then apply to your own webcam image!
#### Exercise 3.1
👉 Write a function `invert` that inverts a color, i.e. sends $(r, g, b)$ to $(1 - r, 1-g, 1-b)$.
"""
# ╔═╡ 4139ee66-ee0a-11ea-2282-15d63bcca8b8
md"""
$(bigbreak)
### Camera input
"""
# ╔═╡ 87dabfd2-461e-4769-ad0f-132cb2370b88
md"""
$(bigbreak)
### Write your own filter!
"""
# ╔═╡ 91f4778e-ee20-11ea-1b7e-2b0892bd3c0f
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;