Python 将图像向左移动x像素,同时保持原始形状

Python 将图像向左移动x像素,同时保持原始形状,python,opencv,image-processing,opencv3.0,Python,Opencv,Image Processing,Opencv3.0,我想在保持原始形状的同时将图像移动x像素。我尝试了以下方法: import cv2 img = cv2.imread("roi.jpg") shift = img[:,x:size[1]] num_rows, num_cols = img.shape[:2] translation_matrix = np.float32([ [1,0,70], [0,1,110] ]) img_translation = cv2.warpAffine(img, translation_matrix,

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

import cv2

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

shift = img[:,x:size[1]]
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()

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

在图像处理中,这被称为图像平移

原始图像:

这将为您提供:

但我们想要这样的东西:

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()

平移基本上意味着我们通过加/减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()
这将导致:

请记住,此图像在上载到此处时已调整大小,不要担心,这是您想要的结果

此外,如果我们想把图像移到更大的图像帧的中间;我们可以通过执行以下操作来完成类似的操作:

import cv2

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

shift = img[:,x:size[1]]
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()
这将为您提供以下输出:


你可以使用。@zindarod我已经检查了这个,但是在如何使用它的问题上我不能真正理解这个。为什么你要将tx和ty作为70和110?我要如何将图像移到左边?嗯,70和110只是用于演示目的,真的,没有什么特别的。关于将图像向左移动,在下方和右侧用零填充numpy数组就足够了。我希望你了解填充。