import cv2
import numpy as np
img_path = '/home/cody/Pictures/zdy.jpg'
image = cv2.imread(img_path)
image = cv2.resize(image,None,fx=0.5,fy=0.5)
mapping = np.array([[1, 0, 0],
[0, 1, 0]]).astype(np.float)
# mapping = np.array([x_scale, 0, x_shift], # x_shift<0,->left;
# [0, y_scale, y_shift]]).astype(np.float) # y_shift<0,->up;
padding = [ 66.31880208, 111.23558449, 105.38220486]
# mapping 大小2x3, 变换矩阵,一般反映平移或旋转的关系;(w,h)输出大小;boardValue 补值;
crop = cv2.warpAffine(image, mapping, (image.shape[1], image.shape[0]), borderMode=cv2.BORDER_CONSTANT, borderValue=padding)
cv2.imshow('cv2warpAffine', crop)
cv2.waitKey(0)
不做任何变化时:
mapping = np.array([[1, 0, 0],
[0, 1, 0]]).astype(np.float)
x和y各自放大1.5倍 mapping = np.array([[1.5, 0, 0],
[0, 1.5, 0]]).astype(np.float)
x和y向左上角移动100个像素, mapping = np.array([[1.0, 0, -100],
[0, 1.0, -100]]).astype(np.float)
x和y向左上角移动100个像素, mapping = np.array([[1.0, 0, -100],
[0, 1.0, -100]]).astype(np.float)
同时窗口缩小0.5倍:
crop = cv2.warpAffine(image, mapping, (int(image.shape[1]*0.5), int(image.shape[0]*0.5)), borderMode=cv2.BORDER_CONSTANT, borderValue=padding)
结论:
通过控制x_scale,y_scale控制缩放比例,x_shift,y_shift进行移动,通过cv2.warpAffine指定窗口大小,来实现缩放和裁剪
# mapping = np.array([x_scale, 0, x_shift], # x_shift<0,->left; # [0, y_scale, y_shift]]).astype(np.float) # y_shift<0,->up;