Skip to content

Instantly share code, notes, and snippets.

@ricebunnyNL
Last active November 3, 2021 00:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save ricebunnyNL/d913288a18e71cd7fe172301b525a4fd to your computer and use it in GitHub Desktop.
Save ricebunnyNL/d913288a18e71cd7fe172301b525a4fd to your computer and use it in GitHub Desktop.
Optimized seam carving for Julia
function find_min_energy_map2(energy)
energy = transpose(energy)
row,col = size(energy)
dir_arr = [-1,0,1]
energy_map = zeros(row,col)
energy_map[:, end] = energy[:, end]
dirs= zeros(Int, row,col)
@inbounds for c = col-1:-1:1
local_energy, next_element = min2(energy_map[1,c+1], energy_map[2,c+1])
energy_map[1,c] = local_energy + energy[1,c]
dirs[1,c] = dir_arr[next_element + 1]
@inbounds for r=2:row-1
top = max(1, r-1)
bottom = min(row,r+1)
local_energy, next_element = min3(energy_map[r-1, c+1], energy_map[r, c+1], energy_map[r+1, c+1])
energy_map[r,c] += local_energy + energy[r,c]
dirs[r,c] = dir_arr[next_element]
end
local_energy, next_element = min2(energy_map[row-1,c+1], energy_map[row,c+1])
energy_map[row,c] = local_energy + energy[row,c]
dirs[row,c] = dir_arr[next_element]
end
return transpose(energy_map), transpose(dirs)
end
function min2(a,b)
return (a<b) ? (a,1) : (b,2)
end
function min3(a,b,c)
if (a<b)
if (a<c)
return a,1
else
return c,3
end
else
if (b<c)
return b,2
else
return c,3
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment