opencv最邻近插值图像缩放
1,最近邻插值算法的思想:
设原始图像src的高为h,宽为w,图像上像素值为(x,y)。
设目标图像dst的高H,宽为W,图像上的像素值为(X,Y)。
那么根据比例缩放的思想有x/X=w/W
同理,纵向上的像素对应比值为y/Y=h/H
那么在考虑目标图像dst上面的像素点(X,Y)对应到原始图像src上面像素点的位置为
(x,y)=(w/W*X,h/H*Y)
这里要对w/W*X与h/H*Y两个数值进行取整,在OpenCV源码当中,是用cvFloor函数取整,即舍去小数部分。
2,代码实现:
import cv2
import numpy as np
img = cv2.imread('image0.jpg',1)
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)
3,图片缩放的另一种具体实现:
#[[A1 A2 B1],[A3 A4 B2]]
# [[A1 A2],[A3 A4]] [[B1],[B2]]
# newX = A1*x + A2*y+B1
# newY = A3*x +A4*y+B2
# x->x*0.5 y->y*0.5
# newX = 0.5*x
import cv2
import numpy as np
img = cv2.imread('image0.jpg',1)
cv2.imshow('src',img)
imgInfo = img.shape
height = imgInfo[0]
width = imgInfo[1]
#A = [0.5,0;0,0.0.5]; b = [0;0]
matScale = np.float32([[0.5,0,0],[0,0.5,0]])
dst = cv2.warpAffine(img,matScale,(int(width/2),int(height/2)))
cv2.imshow('dst',dst)
cv2.waitKey(0)
还没有评论,来说两句吧...