在图像处理中,这个东西被称为图像的翻译。
原图:
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()
这给你的输出为: