-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathSeam_carving_helper.jl
More file actions
2451 lines (2008 loc) · 80 KB
/
Copy pathSeam_carving_helper.jl
File metadata and controls
2451 lines (2008 loc) · 80 KB
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.20.5
#> [frontmatter]
#> chapter = 1
#> video = "https://www.youtube.com/watch?v=KyBXJV1zFlo"
#> image = "https://user-images.githubusercontent.com/6933510/136196584-b3c806a8-aa61-48d9-9e73-30583fcc38bf.gif"
#> section = 8
#> order = 8
#> title = "Seam Carving"
#> layout = "layout.jlhtml"
#> youtube_id = "KyBXJV1zFlo"
#> description = ""
#> tags = ["lecture", "module1", "image", "matrix", "track_julia", "track_climate", "track_data", "optimization", "interactive"]
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)
#! format: off
return 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
#! format: on
end
# ╔═╡ 405a4f82-8116-11eb-1b35-2563b06b02a7
begin
using ImageMagick
using Colors, ColorVectorSpace, ImageShow, FileIO, ImageIO
using ImageFiltering
using Plots, PlutoUI
using BenchmarkTools, OhMyThreads
# Standard libraries
using Statistics, LinearAlgebra
end
# ╔═╡ fb6b8564-8104-11eb-2e10-1f28be9a6ce7
md"""
Scroll through the images in this notebook. The idea of **seam carving** is to shrink an image by removing the "least interesting" parts of the image, but *without* resizing the objects within the image. We want to remove the "dead space" within the image.
We try to find a "seam", i.e. a connected path of pixels from top to bottom of the image, which consists of the "least important" pixels, by some measure.
We then remove the pixels in that seam to give an image that is one pixel narrower.
In order to do this, we need to decide how to measure which pixels are "important".
"""
# ╔═╡ bb44122a-80fb-11eb-0593-8d2a6f1e816e
md"""
### Fall 2020 MIT Class Video from Grant Sanderson
Here is Grant Sanderson (3Blue1Brown) explaining seam carving using this notebook from the Fall 2020 edition of this class.
"""
# ╔═╡ 1e132972-80fc-11eb-387a-9b251ee572f8
html"""
<script src="https://cdn.jsdelivr.net/npm/lite-youtube-embed@0.2.0/src/lite-yt-embed.js" integrity="sha256-wwYlfEzWnCf2nFlIQptfFKdUmBeH5d3G7C2352FdpWE=" crossorigin="anonymous" defer></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/lite-youtube-embed@0.2.0/src/lite-yt-embed.css" integrity="sha256-99PgDZnzzjO63EyMRZfwIIA+i+OS2wDx6k+9Eo7JDKo=" crossorigin="anonymous">
<lite-youtube videoid=rpB6zQNsbQU params="modestbranding=1&rel=0"></lite-youtube>
"""
# ╔═╡ cb335074-eef7-11ea-24e8-c39a325166a1
md"""
## The seam carving algorithm
We need to specify a notion of **importance** of pixels. The seam will then sum up the importance of pixels over the seam and pick the seam which minimizes this total importance.
We will assign importance as "the extent to which a pixel sits inside an edge".
So we need to calculate the "edgeness" of each pixel.
"""
# ╔═╡ 7b0cee56-8106-11eb-0979-e7fead945a6f
md"""
1. We will use convolution with **Sobel filters** for edge detection.
2. Then we will use that to write an algorithm that removes "uninteresting"
bits of an image in order to shrink it.
"""
# ╔═╡ 3721e7f9-83fa-48cd-a1f5-e72e07b0f7a2
image_urls = [
# it will try to get one of these images, top to bottom.
# Comment out lines from the top to get another image
"https://github.com/user-attachments/assets/605b1894-2e18-48a0-b02b-4fb2741ddc02",
"https://www.singulart.com/blog/wp-content/uploads/2023/12/The-Persistence-of-Memory.jpg",
"https://upload.wikimedia.org/wikipedia/en/d/dd/The_Persistence_of_Memory.jpg",
"https://upload.wikimedia.org/wikipedia/commons/thumb/1/17/Gustave_Caillebotte_-_Paris_Street%3B_Rainy_Day_-_Google_Art_Project.jpg/1014px-Gustave_Caillebotte_-_Paris_Street%3B_Rainy_Day_-_Google_Art_Project.jpg",
"https://upload.wikimedia.org/wikipedia/commons/thumb/1/17/Gustave_Caillebotte_-_Paris_Street%3B_Rainy_Day_-_Google_Art_Project.jpg/1014px-Gustave_Caillebotte_-_Paris_Street%3B_Rainy_Day_-_Google_Art_Project.jpg",
"https://upload.wikimedia.org/wikipedia/commons/thumb/c/cc/Grant_Wood_-_American_Gothic_-_Google_Art_Project.jpg/480px-Grant_Wood_-_American_Gothic_-_Google_Art_Project.jpg",
"https://wisetoast.com/wp-content/uploads/2015/10/The-Persistence-of-Memory-salvador-deli-painting.jpg",
"https://upload.wikimedia.org/wikipedia/commons/thumb/7/7d/A_Sunday_on_La_Grande_Jatte%2C_Georges_Seurat%2C_1884.jpg/640px-A_Sunday_on_La_Grande_Jatte%2C_Georges_Seurat%2C_1884.jpg",
"https://upload.wikimedia.org/wikipedia/commons/thumb/e/ea/Van_Gogh_-_Starry_Night_-_Google_Art_Project.jpg/758px-Van_Gogh_-_Starry_Night_-_Google_Art_Project.jpg",
"https://web.mit.edu/facilities/photos/construction/Projects/stata/1_large.jpg",
]
# ╔═╡ d2ae6dd2-eef9-11ea-02df-255ec3b46a36
img = (() -> for u in image_urls
try
return load(download(u))
catch
end
end)()
# ╔═╡ 0b6010a8-eef6-11ea-3ad6-c1f10e30a413
# arbitrarily choose the brightness of a pixel as mean of rgb
# brightness(c::AbstractRGB) = mean((c.r, c.g, c.b))
# Use a weighted sum of rgb giving more weight to colors we perceive as 'brighter'
# Based on https://www.tutorialspoint.com/dip/grayscale_to_rgb_conversion.htm
brightness(c::AbstractRGB) = 0.3 * c.r + 0.59 * c.g + 0.11 * c.b
# ╔═╡ fc1c43cc-eef6-11ea-0fc4-a90ac4336964
Gray.(brightness.(img))
# ╔═╡ 82c0d0c8-efec-11ea-1bb9-83134ecb877e
md"""
# Edge detection filter
(Spoiler alert!) We use the Sobel edge detection filter we created in our Homework.
```math
\begin{align}
G_x &= \begin{bmatrix}
1 & 0 & -1 \\
2 & 0 & -2 \\
1 & 0 & -1 \\
\end{bmatrix} \star A\\[10pt]
G_y &= \begin{bmatrix}
1 & 2 & 1 \\
0 & 0 & 0 \\
-1 & -2 & -1 \\
\end{bmatrix} \star A
\end{align}
```
Here, $\star$ denotes convolution.
Here $A$ is the array corresponding to your image.
We can think of $G_x$ and $G_y$ as calculating (discretized) **derivatives** in the $x$ and $y$ directions.
Then we combine them by finding the magnitude of the (discretized) **gradient**, in the sense of multivariate calculus, by defining
$$G_\text{total} = \sqrt{G_x^2 + G_y^2}.$$
"""
# ╔═╡ ffc9ede2-8106-11eb-2218-79307d6b4515
md"""
Here are the Sobel kernels for the derivatives in each direction:
"""
# ╔═╡ da726954-eff0-11ea-21d4-a7f4ae4a6b09
Sy, Sx = Kernel.sobel()
# ╔═╡ abf6944e-f066-11ea-18e2-0b92606dab85
(collect(Int.(8 .* Sx)), collect(Int.(8 .* Sy)))
# ╔═╡ 42f2105a-810b-11eb-0e47-2dbb5ea2f566
plotly()
# ╔═╡ 406a65c0-810a-11eb-3c57-6d5be524ee3f
surface(brightness.(img))
# ╔═╡ ac8d6902-f069-11ea-0f1d-9b0fa706d769
md"""
- blue shows positive values
- red shows negative values
"""
# ╔═╡ 172c7612-efee-11ea-077a-5d5c6e2505a4
function shrink_image(image, ratio=5)
(height, width) = size(image)
new_height = height ÷ ratio - 1
new_width = width ÷ ratio - 1
list = [
mean(image[
ratio * i:ratio * (i + 1),
ratio * j:ratio * (j + 1),
])
for j in 1:new_width
for i in 1:new_height
]
reshape(list, new_height, new_width)
end
# ╔═╡ fcf46120-efec-11ea-06b9-45f470899cb2
function convolve(M, kernel)
height, width = size(kernel)
half_height = height ÷ 2
half_width = width ÷ 2
new_image = similar(M)
# (i, j) loop over the original image
m, n = size(M)
@inbounds for i in 1:m
for j in 1:n
# (k, l) loop over the neighbouring pixels
accumulator = 0 * M[1, 1]
for k in -half_height:-half_height + height - 1
for l in -half_width:-half_width + width - 1
Mi = i - k
Mj = j - l
# First index into M
if Mi < 1
Mi = 1
elseif Mi > m
Mi = m
end
# Second index into M
if Mj < 1
Mj = 1
elseif Mj > n
Mj = n
end
accumulator += kernel[k, l] * M[Mi, Mj]
end
end
new_image[i, j] = accumulator
end
end
return new_image
end
# ╔═╡ 6f7bd064-eff4-11ea-0260-f71aa7f4f0e5
function edgeness(img)
Sy, Sx = Kernel.sobel()
b = brightness.(img)
∇y = convolve(b, Sy)
∇x = convolve(b, Sx)
sqrt.(∇x.^2 + ∇y.^2)
end
# ╔═╡ dec62538-efee-11ea-1e03-0b801e61e91c
function show_colored_array(array)
pos_color = RGB(0.36, 0.82, 0.8)
neg_color = RGB(0.99, 0.18, 0.13)
to_rgb(x) = max(x, 0) * pos_color + max(-x, 0) * neg_color
to_rgb.(array) / maximum(abs.(array))
end
# ╔═╡ a21a886e-80eb-11eb-35ab-3dd3fb0a8a2c
show_colored_array(Sx), show_colored_array(Sy)
# ╔═╡ ddac52ea-f148-11ea-2860-21cff4c867e6
let
∇y = convolve(brightness.(img), Sy)
∇x = convolve(brightness.(img), Sx)
# clock coordinate
cc = round(Int, size(img, 1) * 0.45)
data = [
md"``G_x``", md"``G_y``",
# zoom in on the clock
img[cc:end, 1:cc], img[cc:end, 1:cc],
show_colored_array.((∇x[cc:end, 1:cc], ∇y[cc:end, 1:cc]))...
]
# avoid collating the images into one big matrix
todisplay = permutedims(reshape(data, (2,3)), (2,1))
@assert length(todisplay) < 10
PlutoUI.ExperimentalLayout.grid(todisplay)
end
# ╔═╡ f8283a0e-eff4-11ea-23d3-9f1ced1bafb4
md"""
## Seam carving idea
The idea of seam carving is to find a path from the top of the image to the bottom of the image where the path minimizes the edgeness.
In other words, this path **minimizes the number of edges in the image that it crosses**.
We will call the edgeness the **energy**.
"""
# ╔═╡ 025e2c94-eefb-11ea-12cb-f56f34886334
md"""
At every step in going down, the path is allowed to go south-west, south or south-east. We want to find a connected path, or **seam**, with the minimum possible sum of "energies" along the path.
We start by writing a `least_edgy` function which takes a matrix of energies and returns
a new matrix. The new matrix has entries $M_{i, j}$ which gives the minimum possible energy when starting from the pixel $(i, j)$ and going from there down to a pixel in the bottom row.
"""
# ╔═╡ d00d3b10-3bf5-41ad-b472-6f37645fddcf
begin
struct Serial end
struct NaiveTasks end
# construct this with TriangleTasks{12}()
# N is the size of the triangles.
struct TriangleTasks{N} end
end
# ╔═╡ acc1ee8c-eef9-11ea-01ac-9b9e9c4167b3
# e[x,y]
# ↙ ↓ ↘ <-- pick the next path which gives the least overall energy
# e[x-1,y+1] e[x,y+1] e[x+1,y+1]
#
# Basic calculation: e[x,y] += min( e[x-1,y+1], e[x,y], e[x+1,y] )
# `dirs` records which direction we take from (-1==SW, 0==S, 1==SE)
function least_edgy!(least_E, dirs, E, ::Serial)
least_E[end, :] .= E[end, :] # the minimum energy on the last row is the energy
# itself
m, n = size(E)
# Go from the last row up, finding the minimum energy
for i in m-1:-1:1
for j in 1:n
j1, j2 = max(1, j-1), min(j+1, n)
e, dir = findmin(least_E[i+1, j1:j2])
least_E[i,j] += e
least_E[i,j] += E[i,j]
dirs[i, j] = (-1, 0, 1)[dir + (j==1)]
end
end
return least_E, dirs
end
# ╔═╡ 08eadb18-7173-43aa-b4fe-19c24f34c8eb
md"""
#### Naive Tasks based parallelism
"""
# ╔═╡ 323932f5-eed4-4263-805b-2577e63640bd
function least_edgy!(least_E, dirs, E, ::NaiveTasks)
least_E[end, :] .= E[end, :] # the minimum energy on the last row is the energy
# itself
m, n = size(E)
# Go from the last row up, finding the minimum energy
# FILL IN THIS BLANK
return least_E, dirs
end
# ╔═╡ c21209b8-9ec6-4647-9e83-555fb17b9ca0
md"""
#### Triangle Based Parallelism
Next we will attempt to parallelize not by row but by larger triangles. The diagram below illustrates the pattern you should use (but **not** the sizes necessarily). Each triangle should be it's own task using OhMyThreads. Note that this means $N$ should be relatively large.
Each of the gray triangles has dependencies only *within* each triangle, and on the row above.
Each of the tan triangles has dependencies only *within* each triangle and on the gray triangles above.
This implies that you should parallelize each strip as follows:
- Divide the gray triangles (upper triangles) amongst your threads and compute all necessary values, relying on the row above if necessary.
- Divide the tan triangles amongst your threads and compute all necessary values, each tan triangle will depend on the values of two of the gray triangles in the previous step.
- Continue to the next strip.
"""
# ╔═╡ f3b5f050-1570-4c0e-8d47-b7530aff32be
html"""
<head>
<style>
img {
background-color: #FFFFFF;
}
</style>
</head>
<body>
<p align="center"><img src="https://shwestrick.github.io/assets/seam-carve/equation.svg" /></p>
</body>
"""
# ╔═╡ 485aae77-a555-4ed4-a0b4-0ffa140abd87
html"""
<head>
<style>
img {
background-color: #FFFFFF;
}
</style>
</head>
<body>
<p align="center"><img src="https://shwestrick.github.io/assets/seam-carve/strips.svg" /></p>
</body>
"""
# ╔═╡ be4a6d76-5f53-4053-87b9-3fd6347bb738
function least_edgy!(least_E, dirs, E, ::TriangleTasks{N}) where N
@assert iseven(N) "Block size must be even (this implies images must have even dimensions)"
# note that we are moving from top to bottom here, this may change the diagrams below by making them upside down.
# You are welcome to fiddle with things and fix this!
least_E[begin, :] .= E[begin, :] # the minimum energy on the first row is the energy
# itself
m, n = size(E)
tri_width = N
tri_height = N ÷ 2
strip_height = tri_height + 1
nblocks = n ÷ tri_width # (the number of upper / lower triangles in each row)
for strip ∈ 1:(m ÷ strip_height)
strip_start = (strip - 1) * strip_height + 1
# @tasks this once you are done debugging
for upper_tri ∈ 1:nblocks # iterate over each upper triangle
# iterate over each row in the upper triangle
for row ∈ strip_start:(strip_start + tri_height - 1) # iterate over each row within the upper triangle part of the strip
local_row = row % strip_height
if row == 1
continue # we already computed the first row
end
# we compute the set of columns in each row of *this* triangle, this decreases in size by 1 from *both* sides of the triangle at each row.
for col ∈ ((upper_tri - 1) * tri_width + local_row):(upper_tri * tri_width - local_row + 1)
# FILL IN THIS BLANK TO COMPUTE THE UPPER TRIANGLE Least Energy and Directions!!!
# REMOVE THE PRINTLN WHEN COMPLETE!
# USE PRINTLN JUDICIOUSLY ON SMALL ARRAYS TO CHECK YOUR WORK!
println("strip $strip, tri $upper_tri, row $row, col $col")
end
end
end
# FILL IN THIS BLANK FOR THE LOWER TRIANGLES!
end
return least_E, dirs
end
# ╔═╡ a4a4d169-e5d3-45a2-b30c-c307f5edf127
# Default to serial execution!
least_edgy!(least_E, dirs, E) = least_edgy!(least_E, dirs, E, Serial())
# ╔═╡ 00377cbc-13fa-416f-a164-d402406bf4d1
function least_edgy(E, parallelism)
# allocate output arrays.
least_E = zeros(size(E))
dirs = zeros(Int, size(E))
least_edgy!(least_E, dirs, E, parallelism)
end
# ╔═╡ a103c976-b144-404a-b60b-53034f9a31b0
# Default to serial execution!
least_edgy(E) = least_edgy(E, Serial())
# ╔═╡ fca4b8c6-9577-4470-8c11-c51c814bac0c
edged_img = edgeness(img);
# ╔═╡ 05e99f66-2f93-4b8d-85a1-0eb4bccc65c5
@benchmark least_edgy(edged_img, Serial())
# ╔═╡ 75cd2249-dbc1-4b29-b580-2a56aa01839d
# @benchmark least_edgy(edged_img, NaiveTasks())
# ╔═╡ 055ad847-8176-4e53-8a0a-4800b9148d9c
# @benchmark least_edgy(edged_img, TriangleTasks{50})
# ╔═╡ 8b204a2a-eff6-11ea-25b0-13f230037ee1
# The bright areas are screaming "AVOID ME!"
least_e, dirs = least_edgy(edgeness(img), Serial())
# ╔═╡ 84d3afe4-eefe-11ea-1e31-bf3b2af4aecd
show_colored_array(least_e)
# ╔═╡ dd71c2a4-8108-11eb-18ce-838c53eac3ef
md"""
Here are the directions that we should take at each step:
"""
# ╔═╡ b507480a-ef01-11ea-21c4-63d19fac19ab
# direction the path should take at every pixel.
reduce( (x, y) -> x*y*"\n",
reduce(*, getindex.(([" ", "↙", "↓", "↘"],), dirs[1:25, 1:60].+3), dims=2, init=""), init="") |> Text
# ╔═╡ 7d8b20a2-ef03-11ea-1c9e-fdf49a397619
md"## Remove seams"
# ╔═╡ f690b06a-ef31-11ea-003b-4f2b2f82a9c3
md"""
We now compress an image horizontally by successively removing a number of seams of lowest energy.
"""
# ╔═╡ 977b6b98-ef03-11ea-0176-551fc29729ab
function get_seam_at(dirs, j)
m = size(dirs, 1)
js = fill(0, m)
js[1] = j
for i=2:m
js[i] = js[i-1] + dirs[i-1, js[i-1]]
end
return tuple.(1:m, js)
end
# ╔═╡ 9abbb158-ef03-11ea-39df-a3e8aa792c50
get_seam_at(dirs, 2)
# ╔═╡ 14f72976-ef05-11ea-2ad5-9f0914f9cf58
function mark_path(img, path)
img′ = copy(img)
m = size(img, 2)
for (i, j) in path
# To make it easier to see, we'll color not just
# the pixels of the seam, but also those adjacent to it
for j′ in j-1:j+1
img′[i, clamp(j′, 1, m)] = RGB(1,0,1)
end
end
return img′
end
# ╔═╡ 22c851c4-8109-11eb-3950-35a75857c3c3
md"""
In the visualization below, the slider specifies which column we start with at the top. The pink seam is the best (least total energy) that will be snipped out.
"""
# ╔═╡ cf9a9124-ef04-11ea-14a4-abf930edc7cc
@bind start_column Slider(1:size(img, 2), show_value=true)
# ╔═╡ 772a4d68-ef04-11ea-366a-f7ae9e1634f6
path = get_seam_at(dirs, start_column)
# ╔═╡ 081a98cc-f06e-11ea-3664-7ba51d4fd153
function pencil(X)
f(x) = RGB(1-x,1-x,1-x)
map(f, X ./ maximum(X))
end
# ╔═╡ 237647e8-f06d-11ea-3c7e-2da57e08bebc
e = edgeness(img);
# ╔═╡ e7eb3490-3248-4d36-98e8-4040d8dae768
md"""
#### Lowest energy path
We can use `findmin` to find the path with the least energy:
"""
# ╔═╡ 4f23bc54-ef0f-11ea-06a9-35ca3ece421e
function rm_path(img, path)
img′ = img[:, 1:end-1] # one less column
for (i, j) in path
img′[i, 1:j-1] .= img[i, 1:j-1]
img′[i, j:end] .= img[i, j+1:end]
end
img′
end
# ╔═╡ b401f398-ef0f-11ea-38fe-012b7bc8a4fa
function shrink_n(img, n)
imgs = []
marked_imgs = []
e = edgeness(img)
for i=1:n
least_E, dirs = least_edgy(e)
_, min_j = findmin(@view least_E[1, :])
seam = get_seam_at(dirs, min_j)
img = rm_path(img, seam)
# Recompute the energy for the new image
# Note, this currently involves rerunning the convolution
# on the whole image, but in principle the only values that
# need recomputation are those adjacent to the seam, so there
# is room for a meanintful speedup here.
# e = edgeness(img)
e = rm_path(e, seam)
push!(imgs, img)
push!(marked_imgs, mark_path(img, seam))
end
imgs, marked_imgs
end
# ╔═╡ b1b6b7fc-f153-11ea-224a-2578e8298775
n_examples = min(200, size(img, 2))
# ╔═╡ 2eb459d4-ef36-11ea-1f74-b53ffec7a1ed
# returns two vectors of n successively smaller images
# The second images have markings where the seam is cut out
carved, marked_carved = shrink_n(img, n_examples);
# ╔═╡ 5d6c1d74-8109-11eb-3529-bf2f23554b02
md"""
### Seam carving in action
"""
# ╔═╡ 48593d7c-8109-11eb-1b8b-6f15155d6ec9
md"""
Here is the algorithm in action. Now the slider tells us on which step of the algorithm we are, having removed each least-energy seam at each step:
"""
# ╔═╡ 7038abe4-ef36-11ea-11a5-75e57ab51032
md"""
Shrink by: $(@bind n Slider(1:length(carved); show_value=true))
"""
# ╔═╡ abcafa92-f426-4653-a65e-149b41dd91bf
# ╔═╡ 1e0322f9-8737-401b-8b10-74f58d8e97ab
md"""
# Appendix
"""
# ╔═╡ fda2f181-e582-4d61-822c-7ee75e214aaa
function downsample(img; maxheight=100)
h,w = size(img)
if h <= maxheight
img
else
img[
floor.(Int,LinRange(1,h,maxheight)),
floor.(Int,LinRange(1,w,floor(Int, maxheight * w / h)))
]
end
end
# ╔═╡ 268c85cf-28c7-46ea-b343-b1214f75de33
downsample(img; maxheight=40)
# ╔═╡ 1fd26a60-f089-11ea-1f56-bb6eba7d9651
# function hbox(x, y, gap=16; sy=size(y), sx=size(x))
# w, h = (max(sx[1], sy[1]),
# gap + sx[2] + sy[2])
# slate = fill(RGB(1,1,1), w,h)
# slate[1:size(x,1), 1:size(x,2)] .= RGB.(x)
# slate[1:size(y,1), size(x,2) + gap .+ (1:size(y,2))] .= RGB.(y)
# slate
# end
# ╔═╡ dbacb273-02dc-4ff0-ac1a-3cc6785d3dac
function hbox(imgs...; maxheight=200)
g(x) = PlutoUI.ExperimentalLayout.Div(
downsample(x; maxheight);
style=Dict("display" => "flex", "flex" => "1 0 auto")
)
PlutoUI.ExperimentalLayout.Div(
collect(map(g, imgs));
style=Dict(
"display" => "flex",
"flex-direction" => "row",
"aspect-ratio" => length(imgs) * size(imgs[1],2) / size(imgs[2],1)
)
)
end
# ╔═╡ 44192a40-eff2-11ea-0ec7-05cdadb0c29a
begin
img_brightness = brightness.(img)
∇x = convolve(img_brightness, Sx)
∇y = convolve(img_brightness, Sy)
hbox(show_colored_array(∇x), show_colored_array(∇y))
end
# ╔═╡ d6a268c0-eff4-11ea-2c9e-bfef19c7f540
begin
edged = edgeness(img)
# hbox(img, pencil(edged))
hbox(img, Gray.(edgeness(img)) / maximum(abs.(edged)))
end
# ╔═╡ 552fb92e-ef05-11ea-0a79-dd7a6760089a
hbox(mark_path(img, path), mark_path(show_colored_array(least_e), path))
# ╔═╡ dfd03c4e-f06c-11ea-1e2a-89233a675138
hbox(
mark_path(img, path),
mark_path(pencil(e), path)
)
# ╔═╡ ca4a87e8-eff8-11ea-3d57-01dfa34ff723
let
# least energy path of them all:
_, k = findmin(least_e[1, :])
path = get_seam_at(dirs, k)
hbox(
mark_path(img, path),
mark_path(show_colored_array(least_e), path)
)
end
# ╔═╡ 8f523ba8-f52c-4269-90ca-1aa87948bdb9
hbox(img, marked_carved[n])
# ╔═╡ 71b16dbe-f08b-11ea-2343-5f1583074029
vbox(x...) = PlutoUI.ExperimentalLayout.vbox(collect(x))
# ╔═╡ 15d1e5dc-ef2f-11ea-093a-417108bcd495
[size(img) size(carved[n])]
# ╔═╡ 00000000-0000-0000-0000-000000000001
PLUTO_PROJECT_TOML_CONTENTS = """
[deps]
BenchmarkTools = "6e4b80f9-dd63-53aa-95a3-0cdb28fa8baf"
ColorVectorSpace = "c3611d14-8923-5661-9e6a-0046d554d3a4"
Colors = "5ae59095-9a9b-59fe-a467-6f913c188581"
FileIO = "5789e2e9-d7fb-5bc7-8068-2c6fae9b9549"
ImageFiltering = "6a3955dd-da59-5b1f-98d4-e7296123deb5"
ImageIO = "82e4d734-157c-48bb-816b-45c225c6df19"
ImageMagick = "6218d12a-5da1-5696-b52f-db25d2ecc6d1"
ImageShow = "4e3cecfd-b093-5904-9786-8bbb286a6a31"
LinearAlgebra = "37e2e46d-f89d-539d-b4ee-838fcccc9c8e"
OhMyThreads = "67456a42-1dca-4109-a031-0a68de7e3ad5"
Plots = "91a5bcdd-55d7-5caf-9e0b-520d859cae80"
PlutoUI = "7f904dfe-b85e-4ff6-b463-dae2292396a8"
Statistics = "10745b16-79ce-11e8-11f9-7d13ad32a3b2"
[compat]
BenchmarkTools = "~1.6.0"
ColorVectorSpace = "~0.9.9"
Colors = "~0.12.8"
FileIO = "~1.16.3"
ImageFiltering = "~0.7.2"
ImageIO = "~0.6.6"
ImageMagick = "~1.3.1"
ImageShow = "~0.3.6"
OhMyThreads = "~0.8.3"
Plots = "~1.40.5"
PlutoUI = "~0.7.48"
"""
# ╔═╡ 00000000-0000-0000-0000-000000000002
PLUTO_MANIFEST_TOML_CONTENTS = """
# This file is machine-generated - editing it directly is not advised
julia_version = "1.11.4"
manifest_format = "2.0"
project_hash = "6cbabf8a0ad6063a177591d3092955dd0c40ca76"
[[deps.AbstractFFTs]]
deps = ["LinearAlgebra"]
git-tree-sha1 = "d92ad398961a3ed262d8bf04a1a2b8340f915fef"
uuid = "621f4979-c628-5d54-868e-fcf4e3e8185c"
version = "1.5.0"
[deps.AbstractFFTs.extensions]
AbstractFFTsChainRulesCoreExt = "ChainRulesCore"
AbstractFFTsTestExt = "Test"
[deps.AbstractFFTs.weakdeps]
ChainRulesCore = "d360d2e6-b24c-11e9-a2a3-2a2ae2dbcce4"
Test = "8dfed614-e22c-5e08-85e1-65c5234f0b40"
[[deps.AbstractPlutoDingetjes]]
deps = ["Pkg"]
git-tree-sha1 = "6e1d2a35f2f90a4bc7c2ed98079b2ba09c35b83a"
uuid = "6e696c72-6542-2067-7265-42206c756150"
version = "1.3.2"
[[deps.Accessors]]
deps = ["CompositionsBase", "ConstructionBase", "Dates", "InverseFunctions", "MacroTools"]
git-tree-sha1 = "3b86719127f50670efe356bc11073d84b4ed7a5d"
uuid = "7d9f7c33-5ae7-4f3b-8dc6-eff91059b697"
version = "0.1.42"
[deps.Accessors.extensions]
AxisKeysExt = "AxisKeys"
IntervalSetsExt = "IntervalSets"
LinearAlgebraExt = "LinearAlgebra"
StaticArraysExt = "StaticArrays"
StructArraysExt = "StructArrays"
TestExt = "Test"
UnitfulExt = "Unitful"
[deps.Accessors.weakdeps]
AxisKeys = "94b1ba4f-4ee9-5380-92f1-94cde586c3c5"
IntervalSets = "8197267c-284f-5f27-9208-e0e47529a953"
LinearAlgebra = "37e2e46d-f89d-539d-b4ee-838fcccc9c8e"
StaticArrays = "90137ffa-7385-5640-81b9-e52037218182"
StructArrays = "09ab397b-f2b6-538f-b94a-2f83cf4a842a"
Test = "8dfed614-e22c-5e08-85e1-65c5234f0b40"
Unitful = "1986cc42-f94f-5a68-af5c-568840ba703d"
[[deps.Adapt]]
deps = ["LinearAlgebra", "Requires"]
git-tree-sha1 = "f7817e2e585aa6d924fd714df1e2a84be7896c60"
uuid = "79e6a3ab-5dfb-504d-930d-738a2a938a0e"
version = "4.3.0"
weakdeps = ["SparseArrays", "StaticArrays"]
[deps.Adapt.extensions]
AdaptSparseArraysExt = "SparseArrays"
AdaptStaticArraysExt = "StaticArrays"
[[deps.AliasTables]]
deps = ["PtrArrays", "Random"]
git-tree-sha1 = "9876e1e164b144ca45e9e3198d0b689cadfed9ff"
uuid = "66dad0bd-aa9a-41b7-9441-69ab47430ed8"
version = "1.1.3"
[[deps.ArgTools]]
uuid = "0dad84c5-d112-42e6-8d28-ef12dabb789f"
version = "1.1.2"
[[deps.ArrayInterface]]
deps = ["Adapt", "LinearAlgebra"]
git-tree-sha1 = "017fcb757f8e921fb44ee063a7aafe5f89b86dd1"
uuid = "4fba245c-0d91-5ea0-9b3e-6abc04ee57a9"
version = "7.18.0"
[deps.ArrayInterface.extensions]
ArrayInterfaceBandedMatricesExt = "BandedMatrices"
ArrayInterfaceBlockBandedMatricesExt = "BlockBandedMatrices"
ArrayInterfaceCUDAExt = "CUDA"
ArrayInterfaceCUDSSExt = "CUDSS"
ArrayInterfaceChainRulesCoreExt = "ChainRulesCore"
ArrayInterfaceChainRulesExt = "ChainRules"
ArrayInterfaceGPUArraysCoreExt = "GPUArraysCore"
ArrayInterfaceReverseDiffExt = "ReverseDiff"
ArrayInterfaceSparseArraysExt = "SparseArrays"
ArrayInterfaceStaticArraysCoreExt = "StaticArraysCore"
ArrayInterfaceTrackerExt = "Tracker"
[deps.ArrayInterface.weakdeps]
BandedMatrices = "aae01518-5342-5314-be14-df237901396f"
BlockBandedMatrices = "ffab5731-97b5-5995-9138-79e8c1846df0"
CUDA = "052768ef-5323-5732-b1bb-66c8b64840ba"
CUDSS = "45b445bb-4962-46a0-9369-b4df9d0f772e"
ChainRules = "082447d4-558c-5d27-93f4-14fc19e9eca2"
ChainRulesCore = "d360d2e6-b24c-11e9-a2a3-2a2ae2dbcce4"
GPUArraysCore = "46192b85-c4d5-4398-a991-12ede77f4527"
ReverseDiff = "37e2e3b7-166d-5795-8a7a-e32c996b4267"
SparseArrays = "2f01184e-e22b-5df5-ae63-d93ebab69eaf"
StaticArraysCore = "1e83bf80-4336-4d27-bf5d-d5a4f845583c"
Tracker = "9f7883ad-71c0-57eb-9f7f-b5c9e6d3789c"
[[deps.Artifacts]]
uuid = "56f22d72-fd6d-98f1-02f0-08ddc0907c33"
version = "1.11.0"
[[deps.AxisArrays]]
deps = ["Dates", "IntervalSets", "IterTools", "RangeArrays"]
git-tree-sha1 = "16351be62963a67ac4083f748fdb3cca58bfd52f"
uuid = "39de3d68-74b9-583c-8d2d-e117c070f3a9"
version = "0.4.7"
[[deps.BangBang]]
deps = ["Accessors", "ConstructionBase", "InitialValues", "LinearAlgebra"]
git-tree-sha1 = "26f41e1df02c330c4fa1e98d4aa2168fdafc9b1f"
uuid = "198e06fe-97b7-11e9-32a5-e1d131e6ad66"
version = "0.4.4"
[deps.BangBang.extensions]
BangBangChainRulesCoreExt = "ChainRulesCore"
BangBangDataFramesExt = "DataFrames"
BangBangStaticArraysExt = "StaticArrays"
BangBangStructArraysExt = "StructArrays"
BangBangTablesExt = "Tables"
BangBangTypedTablesExt = "TypedTables"
[deps.BangBang.weakdeps]
ChainRulesCore = "d360d2e6-b24c-11e9-a2a3-2a2ae2dbcce4"
DataFrames = "a93c6f00-e57d-5684-b7b6-d8193f3e46c0"
StaticArrays = "90137ffa-7385-5640-81b9-e52037218182"
StructArrays = "09ab397b-f2b6-538f-b94a-2f83cf4a842a"
Tables = "bd369af6-aec1-5ad0-b16a-f7cc5008161c"
TypedTables = "9d95f2ec-7b3d-5a63-8d20-e2491e220bb9"
[[deps.Base64]]
uuid = "2a0f44e3-6c83-55bd-87e4-b1978d98bd5f"
version = "1.11.0"
[[deps.BenchmarkTools]]
deps = ["Compat", "JSON", "Logging", "Printf", "Profile", "Statistics", "UUIDs"]
git-tree-sha1 = "e38fbc49a620f5d0b660d7f543db1009fe0f8336"
uuid = "6e4b80f9-dd63-53aa-95a3-0cdb28fa8baf"
version = "1.6.0"
[[deps.BitFlags]]
git-tree-sha1 = "0691e34b3bb8be9307330f88d1a3c3f25466c24d"
uuid = "d1d4a3ce-64b1-5f1a-9ba4-7e7e69966f35"
version = "0.1.9"
[[deps.Bzip2_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl"]
git-tree-sha1 = "1b96ea4a01afe0ea4090c5c8039690672dd13f2e"
uuid = "6e34b625-4abd-537c-b88f-471c36dfa7a0"
version = "1.0.9+0"
[[deps.CEnum]]
git-tree-sha1 = "389ad5c84de1ae7cf0e28e381131c98ea87d54fc"
uuid = "fa961155-64e5-5f13-b03f-caf6b980ea82"
version = "0.5.0"
[[deps.Cairo_jll]]
deps = ["Artifacts", "Bzip2_jll", "CompilerSupportLibraries_jll", "Fontconfig_jll", "FreeType2_jll", "Glib_jll", "JLLWrappers", "LZO_jll", "Libdl", "Pixman_jll", "Xorg_libXext_jll", "Xorg_libXrender_jll", "Zlib_jll", "libpng_jll"]
git-tree-sha1 = "2ac646d71d0d24b44f3f8c84da8c9f4d70fb67df"
uuid = "83423d85-b0ee-5818-9007-b63ccbeb887a"
version = "1.18.4+0"
[[deps.CatIndices]]
deps = ["CustomUnitRanges", "OffsetArrays"]
git-tree-sha1 = "a0f80a09780eed9b1d106a1bf62041c2efc995bc"
uuid = "aafaddc9-749c-510e-ac4f-586e18779b91"
version = "0.2.2"
[[deps.ChunkSplitters]]
git-tree-sha1 = "63a3903063d035260f0f6eab00f517471c5dc784"
uuid = "ae650224-84b6-46f8-82ea-d812ca08434e"
version = "3.1.2"
[[deps.CodecZlib]]
deps = ["TranscodingStreams", "Zlib_jll"]
git-tree-sha1 = "962834c22b66e32aa10f7611c08c8ca4e20749a9"
uuid = "944b1d66-785c-5afd-91f1-9de20f533193"
version = "0.7.8"
[[deps.ColorSchemes]]
deps = ["ColorTypes", "ColorVectorSpace", "Colors", "FixedPointNumbers", "PrecompileTools", "Random"]
git-tree-sha1 = "b5278586822443594ff615963b0c09755771b3e0"
uuid = "35d6a980-a343-548e-a6ea-1d62b119f2f4"
version = "3.26.0"
[[deps.ColorTypes]]
deps = ["FixedPointNumbers", "Random"]
git-tree-sha1 = "b10d0b65641d57b8b4d5e234446582de5047050d"
uuid = "3da002f7-5984-5a60-b8a6-cbb66c0b333f"
version = "0.11.5"
[[deps.ColorVectorSpace]]
deps = ["ColorTypes", "FixedPointNumbers", "LinearAlgebra", "SpecialFunctions", "Statistics", "TensorCore"]
git-tree-sha1 = "600cc5508d66b78aae350f7accdb58763ac18589"
uuid = "c3611d14-8923-5661-9e6a-0046d554d3a4"
version = "0.9.10"
[[deps.Colors]]
deps = ["ColorTypes", "FixedPointNumbers", "Reexport"]
git-tree-sha1 = "362a287c3aa50601b0bc359053d5c2468f0e7ce0"
uuid = "5ae59095-9a9b-59fe-a467-6f913c188581"
version = "0.12.11"
[[deps.CommonWorldInvalidations]]
git-tree-sha1 = "ae52d1c52048455e85a387fbee9be553ec2b68d0"
uuid = "f70d9fcc-98c5-4d4a-abd7-e4cdeebd8ca8"
version = "1.0.0"
[[deps.Compat]]
deps = ["TOML", "UUIDs"]
git-tree-sha1 = "8ae8d32e09f0dcf42a36b90d4e17f5dd2e4c4215"
uuid = "34da2185-b29b-5c13-b0c7-acf172513d20"
version = "4.16.0"
weakdeps = ["Dates", "LinearAlgebra"]
[deps.Compat.extensions]
CompatLinearAlgebraExt = "LinearAlgebra"
[[deps.CompilerSupportLibraries_jll]]
deps = ["Artifacts", "Libdl"]
uuid = "e66e0078-7015-5450-92f7-15fbd957f2ae"
version = "1.1.1+0"
[[deps.CompositionsBase]]
git-tree-sha1 = "802bb88cd69dfd1509f6670416bd4434015693ad"
uuid = "a33af91c-f02d-484b-be07-31d278c5ca2b"
version = "0.1.2"
weakdeps = ["InverseFunctions"]
[deps.CompositionsBase.extensions]
CompositionsBaseInverseFunctionsExt = "InverseFunctions"
[[deps.ComputationalResources]]
git-tree-sha1 = "52cb3ec90e8a8bea0e62e275ba577ad0f74821f7"
uuid = "ed09eef8-17a6-5b46-8889-db040fac31e3"
version = "0.3.2"
[[deps.ConcurrentUtilities]]
deps = ["Serialization", "Sockets"]
git-tree-sha1 = "d9d26935a0bcffc87d2613ce14c527c99fc543fd"
uuid = "f0e56b4a-5159-44fe-b623-3e5288b988bb"
version = "2.5.0"
[[deps.ConstructionBase]]
git-tree-sha1 = "76219f1ed5771adbb096743bff43fb5fdd4c1157"
uuid = "187b0558-2788-49d3-abe0-74a17ed4e7c9"