Skip to content

Instantly share code, notes, and snippets.

@kersulis
Last active June 19, 2020 18:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kersulis/da5b4085e09ace35ce3e94416bf918e3 to your computer and use it in GitHub Desktop.
Save kersulis/da5b4085e09ace35ce3e94416bf918e3 to your computer and use it in GitHub Desktop.
Julia code: shifting and scaling a matrix
using Images
"""
B = shift_lr(A, k)
Shift `A` by `k` columns. If `k` is positive, shift to the
right by inserting `k` columns on the left. If `k` is
negative, shift to the left by inserting `k` columns
on the right.
"""
function shift_lr(A::AbstractMatrix, k::Integer)
k == 0 && return A
m, n = size(A)
if abs(k) > n
@error "Cannot shift matrix with $n columns by $k columns"
end
fill_val = (k > 0 ? A[1] : A[end])
F = fill(fill_val, m, abs(k))
B = (k > 0 ? [F A[:, 1:(n - k)]] : [A[:, (abs(k) + 1):n] F])
return B
end
"""
Shift `A` by `k` rows. If `k` is positive, shift upward by
inserting `k` rows on the bottom. If `k` is
negative, shift downward by inserting `k` rows
on top.
"""
function shift_ud(A::AbstractMatrix, k::Integer)
k == 0 && return A
m, n = size(A)
if abs(k) > m
@error "Cannot shift matrix with $m rows by $k rows."
end
fill_val = (k > 0 ? A[1] : A[end])
F = fill(fill_val, abs(k), n)
B = (k > 0 ? [A[(k + 1):m, :]; F] : [F; A[1:(m - abs(k)), :]])
return B
end
"""
B = scale(A, α)
Use `Images.imresize` to resize `A` by ratio `α`,
preserving its original dimensions.
"""
function scale(A::AbstractMatrix, α::Float64)
α == 1.0 && return A
m, n = size(A)
As = imresize(A; ratio=α)
ms, ns = size(As)
if α < 1.0
fill_rows = m - ms
fill_cols = n - ns
bottom = fill_rows / 2 |> ceil |> Int
left = fill_cols / 2 |> ceil |> Int
fill_value = A[1]
B = fill(fill_value, m, n) .|> Float64
B[(bottom + 1):(bottom + ms), (left + 1):(left + ns)] = As
else
excess_rows = ms - m
excess_cols = ns - n
bottom = excess_rows / 2 |> ceil |> Int
left = excess_cols / 2 |> ceil |> Int
B = As[(bottom + 1):(bottom + m), (left + 1):(left + n)]
end
return B
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment