Offset image in numpy

I have an image in a 2d numpy array. I want to move the image using X and Y offsets and want the rest of the frame to be padded with zeros. I've seen discussions about the "roll" function, but this only works on one axis. (if someone can't point me to the 2d version with addon). I tried slicing, but I ran into a problem where the offsets are in all possible directions. I don't want to move through all the XY +/- offsets. Is there a simple general solution? I have below code which works great for X-offset = + 100. But it falls for X-offset = -100.

Thanks Gert

import matplotlib.pyplot as plt
import scipy.misc        as msc
import numpy             as np

lena = msc.lena()
lena.dtype
(imx,imy)= lena.shape
ox= 100
oy= 20
shift_lena = np.zeros((imx,imy))
shift_lena[0:imy-oy,0:imx-ox] = lena[oy:,ox:]
shift_lena_m = shift_lena.astype(np.int64)
shift_lena_m.dtype
plt.figure(figsize=(10, 3.6))
plt.subplot(131)
plt.imshow(lena, cmap=plt.cm.gray)
plt.subplot(132)
plt.imshow(shift_lena_m, cmap=plt.cm.gray)
plt.subplots_adjust(wspace=0, hspace=0., top=0.99, bottom=0.01, left=0.05, right=0.99)
plt.show()

      

+4


source to share


2 answers


There is no other way to handle negative and positive shifts accordingly:



non = lambda s: s if s<0 else None
mom = lambda s: max(0,s)

ox, oy = 100, 20

shift_lena = numpy.zeros_like(lena)
shift_lena[mom(oy):non(oy), mom(ox):non(ox)] = lena[mom(-oy):non(-oy), mom(-ox):non(-ox)]

      

+6


source


You can use the scroll function to circularly shift x and y and then zero the offset



def shift_image(X, dx, dy):
    X = np.roll(X, dy, axis=0)
    X = np.roll(X, dx, axis=1)
    if dy>0:
        X[:dy, :] = 0
    elif dy<0:
        X[dy:, :] = 0
    if dx>0:
        X[:, :dx] = 0
    elif dx<0:
        X[:, dx:] = 0
    return X

      

0


source







All Articles