【问题标题】:Image translation using numpy使用 numpy 进行图像翻译
【发布时间】:2020-08-11 23:02:10
【问题描述】:

我想执行一定量的图像平移(垂直和水平移动图像)。

问题是当我将裁剪后的图像粘贴回画布上时,我只得到一个白色的空白框。

谁能在这里发现问题?

非常感谢

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 切片来裁剪图像的某些部分 (x2,y2,w,h),然后使用 numpy 将其插入到 (x1,y1) 的黑色背景图像中,w,h)? canvas[y1:y1+h, x1:x1+w] = image[y2:y2+h, x2:x2+w]翻译量为(x1-x2)和(y1-y2)。
  • 能否提供原图给我们?谢谢你。我怀疑这很可能是数据类型问题。但除非您向我们提供可重现的代码,否则很难找到问题所在。
  • 使用numpy.pad

标签: python numpy opencv image-processing


【解决方案1】:

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

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 语句,就像我所做的那样:# black out the shifted parts if h_shift < 0: new_img[:, h_shift:] = 0 else: new_img[:, :h_shift] = 0 if v_shift < 0: new_img[v_shift:, :] = 0 else: new_img[:v_shift, :] = 0
  • 我不认为我跟随;你想把移动的部分涂黑吗?
  • 所以基本上原始帖子中的图像是我想要的,白色部分应该是移位的图像。
猜你喜欢
  • 2020-04-16
  • 2020-01-30
  • 1970-01-01
  • 2014-07-14
  • 2023-04-09
  • 2021-06-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多