三种图像变换方式
- persperctive
- affine
- perspective
findHomography与getPerspectiveTransform类似
findHomography有两个返回值
img = cv2.imread(file_pth)
rows,cols,_ = img.shape
# 1.persperctive
pts1 = np.float32([[56,65],[368,52],[28,387],[389,390]])
pts2 = np.float32([[0,0],[300,0],[0,300],[300,300]])
matrix, _ = cv2.findHomography(pts1, pts2)
output = cv2.warpPerspective(img,matrix,(cols,rows))
print('matrix \n',matrix.shape)
print('matrix \n',matrix)
# 2.affine 只能用三个点
pts1 = np.float32([[56,65],[368,52],[28,387]])
pts2 = np.float32([[0,0],[300,0],[0,300]])
M_affine = cv2.getAffineTransform(pts1,pts2)
img_affine = cv2.warpAffine(img, M_affine, (cols, rows))
cv2.imwrite('aimg_affine.jpg',img_affine)
# 3.perspective
pts1 = np.float32([[56,65],[368,52],[28,387],[389,390]])
pts2 = np.float32([[0,0],[300,0],[0,300],[300,300]])
M_perspective = cv2.getPerspectiveTransform(pts1,pts2)
img_perspective = cv2.warpPerspective(img, M_perspective, (cols, rows))
cv2.imwrite('aimg_perspective.jpg',img_perspective)
将一个点通过透视旋转矩阵映射到新的点
# 1.二维点后补1,转化为三维点,维度(3x1)
# 2.透视矩阵乘以三维点:M(3x3)xP(3x1)=P'(3x1)
# 3.P'=[x',y',k],前个数据除以最后一个数据得到转化后的坐标:P'=[x'/k,y'/k]
pt = np.array([[368,52,1]])
print('point shape:',pt.T.shape)
res = np.dot(M_perspective,pt.T)
pt_ = res[0:2]/res[2]
print('new point:',pt_)
截取图像
从图像上截取目标区域 (x,y,w,h),opencv 图像矩阵的0维是y(上下),1维是x(左右)
def coprImageByRec(img, bbox):
left = bbox[0]
top = bbox[1]
width_ = bbox[2]
high_ = bbox[3]
img_ = img[top:top + high_, left:left + width_]
return img_
图像缩放方式
cv2.resize(frame, (n_w, n_h),interpolation=cv2.INTER_LINEAR)
INTER_NEAREST 最近邻插值
INTER_LINEAR 双线性插值(默认设置)
INTER_AREA 使用像素区域关系进行重采样。
INTER_CUBIC 4x4像素邻域的双三次插值
INTER_LANCZOS4 8x8像素邻域的Lanczos插值