Suh*_*pta 3 python opencv image-processing opencv3.0
我想x在保持原始形状的同时按像素移动图像。我尝试了以下方法:
import cv2
img = cv2.imread("roi.jpg")
shift = img[:,x:size[1]]
Run Code Online (Sandbox Code Playgroud)
但上述方法的问题在于,图像的原始形状丢失了。如何在将图像x向左移动像素的同时保留原始形状。
在图像处理中,这个东西被称为图像的翻译。
原图:
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()
Run Code Online (Sandbox Code Playgroud)
这会给你:
但我们想要这样的东西:
平移基本上意味着我们通过添加/减去 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()
Run Code Online (Sandbox Code Playgroud)
这将导致:
请记住,此图像在此处上传时已调整大小,别担心,这是您想要的结果。
此外,如果我们想在更大的图像帧中间移动图像;我们可以通过执行以下操作来做这样的事情:
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()
Run Code Online (Sandbox Code Playgroud)
这给你的输出为:
| 归档时间: |
|
| 查看次数: |
4516 次 |
| 最近记录: |