【问题标题】:Shifting an image by x pixels to left while maintaining the original shape将图像向左移动 x 个像素,同时保持原始形状
【发布时间】:2019-06-13 21:52:31
【问题描述】:

我想在保持原始形状的同时将图像移动x 像素。我尝试了以下方法:

import cv2

img = cv2.imread("roi.jpg")

shift = img[:,x:size[1]]

但上述方法的问题在于,图像的原始形状丢失了。如何在将图像向左移动x 像素时保留原始形状。

【问题讨论】:

  • 你可以使用Affine Transformation
  • @zindarod 我已经检查过了,但无法真正理解如何使用它。

标签: python opencv image-processing opencv3.0


【解决方案1】:

在图像处理中,这个东西被称为图像的翻译。

原图:

import cv2
import numpy as np

# Read image
img = cv2.imread("roi.jpg") 

# The number of pixels
num_rows, num_cols = img.shape[:2]

# Creating a translation matrix
translation_matrix = np.float32([ [1,0,70], [0,1,110] ])

# Image translation
img_translation = cv2.warpAffine(img, translation_matrix, (num_cols,num_rows))

#cv2.namedWindow('Translation', cv2.WINDOW_NORMAL)
cv2.imshow('Translation', img_translation)
cv2.waitKey(0)
cv2.destroyAllWindows()

这会给你:

但我们想要这样的东西:

平移基本上意味着我们通过添加/减去 X 和 Y 坐标来移动图像。为此,我们需要创建一个变换矩阵,如下所示:

这里的 tx 和 ty 值是 X 和 Y 的平移值,即图像将向右移动 X 个单位,向下移动 Y 个单位。

因此,一旦我们创建了这样的矩阵,我们就可以使用函数 warpAffine 来应用到我们的图像。

warpAffine 中的第三个参数是指生成图像中的行数和列数。由于行数和列数与原始图像相同,因此生成的图像将被裁剪。原因是我们在应用平移矩阵时没有足够的输出空间。为了避免裁剪,我们可以这样做:

img_translation = cv2.warpAffine(img, translation_matrix, (num_cols + 70, num_rows + 110))

cv2.namedWindow('Translation', cv2.WINDOW_NORMAL)
cv2.imshow('Translation', img_translation)
cv2.waitKey(0)
cv2.destroyAllWindows()

这将导致:

记住这张图片在上传到这里时会调整大小,别担心,这是你想要的结果。

此外,如果我们想将图像移动到更大的图像框架的中间;我们可以通过执行以下操作来做这样的事情:

num_rows, num_cols = img.shape[:2]

translation_matrix = np.float32([ [1,0,70], [0,1,110] ])

img_translation = cv2.warpAffine(img, translation_matrix, (num_cols + 70, num_rows + 110))

translation_matrix = np.float32([ [1,0,-30], [0,1,-50] ])

img_translation = cv2.warpAffine(img_translation, translation_matrix, (num_cols + 70 + 30, num_rows + 110 + 50))

cv2.namedWindow('Translation', cv2.WINDOW_NORMAL)
cv2.imshow('Translation', img_translation)
cv2.waitKey(0)
cv2.destroyAllWindows()

这给你的输出为:

【讨论】:

  • 你为什么把 tx 和 ty 作为 70 和 110?
  • 如何将图像向左移动?
  • 嗯,70 和 110 只是用于演示目的,没有什么特别的。关于您向左移动的图像,在下方和右侧用零填充您的 numpy 数组就足够了。我希望你知道填充。
猜你喜欢
  • 2021-11-16
  • 1970-01-01
  • 2018-01-16
  • 1970-01-01
  • 1970-01-01
  • 2013-02-24
  • 1970-01-01
  • 2020-12-11
  • 2018-07-30
相关资源
最近更新 更多