使用numpy进行图像翻译 [英] Image translation using numpy

查看:226
本文介绍了使用numpy进行图像翻译的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想进行一定程度的图像平移(将图像垂直和水平移动).

I want to perform image translation by a certain amount (shift the image vertically and horizontally).

问题在于,当我将裁切后的图像粘贴回画布上时,我只会得到一个白色的空白框.

The problem is that when I paste the cropped image back on the canvas, I just get back a white blank box.

有人可以在这里发现问题吗?

Can anyone spot the issue here?

非常感谢

img_shape = image.shape

# translate image
# percentage of the dimension of the image to translate
translate_factor_x = random.uniform(*translate)
translate_factor_y = random.uniform(*translate)

# initialize a black image the same size as the image
canvas = np.zeros(img_shape)

# get the top-left corner coordinates of the shifted image
corner_x = int(translate_factor_x*img_shape[1])
corner_y = int(translate_factor_y*img_shape[0])

# determine which part of the image will be pasted
mask = image[max(-corner_y, 0):min(img_shape[0], -corner_y + img_shape[0]),
             max(-corner_x, 0):min(img_shape[1], -corner_x + img_shape[1]),
             :]

# determine which part of the canvas the image will be pasted on
target_coords =  [max(0,corner_y),
                    max(corner_x,0),
                    min(img_shape[0], corner_y + img_shape[0]),
                    min(img_shape[1],corner_x + img_shape[1])]

# paste image on selected part of the canvas
canvas[target_coords[0]:target_coords[2], target_coords[1]:target_coords[3],:] = mask
transformed_img = canvas

plt.imshow(transformed_img)

这就是我得到的:

推荐答案

对于图像翻译,您可以使用有些晦涩的numpy.roll函数.在此示例中,我将使用白色画布,因此更易于可视化.

For image translation, you can make use of the somewhat obscure numpy.roll function. In this example I'm going to use a white canvas so it is easier to visualize.

image = np.full_like(original_image, 255)
height, width = image.shape[:-1]
shift = 100

# shift image
rolled = np.roll(image, shift, axis=[0, 1])
# black out shifted parts
rolled = cv2.rectangle(rolled, (0, 0), (width, shift), 0, -1)
rolled = cv2.rectangle(rolled, (0, 0), (shift, height), 0, -1)

如果要翻转图像,使黑色部分位于另一侧,则可以同时使用np.fliplrnp.flipud.

If you want to flip the image so the black part is on the other side, you can use both np.fliplr and np.flipud.

结果:

这篇关于使用numpy进行图像翻译的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆