插值方法
四种插值,最近邻域插值 双线性插值 像素关系重采样 立方插值
其中最近邻域插值、双线性插值原理如下:
1) 最近领域插值
两行四列(2, 4)-> (1, 2)
newx = x * (src行/目标行) = 1 * (10 / 5) = 2
newy = y * (src列/目标列) = 2 * (20 / 10) = 4
12.3 = 12
2) 双线性插值(横纵坐标的投影)
A1 = 20% 上 + 80% 下 A2同理
B1 = 30% 左 + 70% 右 B2同理
法一: 最终点 = A1 30% + A2 70%
法二: 最终点 = B1 20% + B2 80%
实现缩放的三种方式
1) opencv api的resize()法
import cv2
import numpy as np
img = cv2.imread('face.jpg', 1)
cv2.imshow('src', img)
imgInfo = img.shape
print('imgInfo: ', imgInfo)
# 高度
height = imgInfo[0]
# 宽度
width = imgInfo[1]
# 颜色组成方式:3, 一个像素由三个基本元素组成
mode = imgInfo[2]
# 放大 缩小 等比例缩放(宽高比相同)
DstHeight = int(height * 0.5)
DstWidth = int(width * 0.5)
dst = cv2.resize(img, (DstWidth, DstHeight))
cv2.imshow('dst', dst)
cv2.waitKey(0)
image.png
2) 双线性插值原理法
# 1 info 2 空白模板 3 xy
import cv2
import numpy as np
img = cv2.imread('face.jpg', 1)
cv2.imshow('src', img)
imgInfo = img.shape
height = imgInfo[0]
width = imgInfo[1]
dstHeight = int(height/ 2)
dstWidth = int(width / 2)
# 三维
dstImage = np.zeros((dstHeight, dstWidth, 3), np.uint8) # 0~255
for i in range(0, dstHeight): # 行
for j in range(0, dstWidth): # 列
iNew = int(i * (height * 1.0 / dstHeight))
jNew = int(j * (width * 1.0 / dstWidth))
dstImage[i, j] = img[iNew, jNew]
cv2.imshow('dst', dstImage)
cv2.waitKey(0)
image.png
3) 仿射变换之缩放矩阵法
# [[A1 A2 B1], [A3 A4 B2]]-> 拆分成 [[A1 A2], [A3 A4]] [[B1], [B2]]
# newx = A1 * x + A2 * y + B1 newx = 0.5 * x
# newY = A3 * x + A4 * Y + B2
import cv2
import numpy as np
img = cv2.imread('face.jpg', 1)
cv2.imshow('src', img)
imgInfo = img.shape
height = imgInfo[0]
width = imgInfo[1]
matScale = np.float32([[0.5, 0, 0], [0, 0.5, 0]])
# 仿射变换
dst = cv2.warpAffine(img, matScale, (int(height / 2), int(width / 2)))
cv2.imshow('dst', dst)
cv2.waitKey(0)
image.png
网友评论