a_silve
a_silve

Reputation: 3

Copy a numpy array into part of another array if the borders exceed

I have a larger image and a smaller one. I want to paste the smaller one into a particular position of the larger one. The problem arises if the coordinates where I want to paste the image are such that the smaller image exceeds the borders of the larger one. I know I can do:

    larger_image[center_x - smaller_image.shape[0]/2 : center_x + smaller_image.shape[0]/2, center_y - smaller_image.shape[1]/2 : center_y + smaller_image.shape[1]/2] = smaller_image

Let's suppose center_x = center_y = 2, with for example smaller_image.shape = (10, 10) and larger_image.shape = (20, 20) the problem arises because the smaller_image cannot be pasted entirely on the larger one. Is there a way to avoid numpy errors and just paste the part of the smaller_image that is inside the larger_one?

Upvotes: 0

Views: 242

Answers (2)

busybear
busybear

Reputation: 10580

I don't think there's an easy function to handle this. But you can force index of your larger values to min and max of 0 and the dimensions of your image, respectively, and adjust your smaller image index similarly:

dy_l, dx_l = larger_image.shape
dy_s, dx_s = smaller_image.shape

# Coordinates within larger image
ymin = int(max(0, center_y - dy_s/2))
ymax = int(min(dy_l, center_y + dy_s/2))
xmin = int(max(0, center_x - dx_s/2))
xmax = int(min(dx_l, center_x + dx_s/2))

# Coordinates within smaller image    
yoff0 = int(max(0, dy_s/2 - center_y))
yoff1 = int(dy_s + min(0, dy_l - (center_y + dy_s/2)))
xoff0 = int(max(0, dx_s/2 - center_x))
xoff1 = int(dx_s + min(0, dx_l - (center_x + dx_s/2)))

# Paste image
larger_image[ymin:ymax, xmin:xmax] = smaller_image[yoff0:yoff1, xoff0:xoff1]

Upvotes: 2

Jan Christoph Terasa
Jan Christoph Terasa

Reputation: 5935

You could pad the larger image first, and remove the padding afterwards:

x, y = smaller_image.shape

larger_image_pad = np.pad(larger_image, (x, y), mode='constant')
center_x += x
center_y += y
larger_image_pad[center_x - x//2 : center_x + x//2, center_y - y//2 : center_y + y//2] = smaller_image
larger_image = larger_image_pad[x:-x,y:-y]

Upvotes: 0

Related Questions