python 图像插值 最近邻、双线性、双三次实例
最近邻:
importcv2 importnumpyasnp deffunction(img): height,width,channels=img.shape emptyImage=np.zeros((2048,2048,channels),np.uint8) sh=2048/height sw=2048/width foriinrange(2048): forjinrange(2048): x=int(i/sh) y=int(j/sw) emptyImage[i,j]=img[x,y] returnemptyImage img=cv2.imread("e:\\lena.bmp") zoom=function(img) cv2.imshow("nearestneighbor",zoom) cv2.imshow("image",img) cv2.waitKey(0)
双线性:
importcv2 importnumpyasnp importmath deffunction(img,m,n): height,width,channels=img.shape emptyImage=np.zeros((m,n,channels),np.uint8) value=[0,0,0] sh=m/height sw=n/width foriinrange(m): forjinrange(n): x=i/sh y=j/sw p=(i+0.0)/sh-x q=(j+0.0)/sw-y x=int(x)-1 y=int(y)-1 forkinrange(3): ifx+1双三次:
importcv2 importnumpyasnp importmath defS(x): x=np.abs(x) if0<=x<1: return1-2*x*x+x*x*x if1<=x<2: return4-8*x+5*x*x-x*x*x else: return0 deffunction(img,m,n): height,width,channels=img.shape emptyImage=np.zeros((m,n,channels),np.uint8) sh=m/height sw=n/width foriinrange(m): forjinrange(n): x=i/sh y=j/sw p=(i+0.0)/sh-x q=(j+0.0)/sw-y x=int(x)-2 y=int(y)-2 A=np.array([ [S(1+p),S(p),S(1-p),S(2-p)] ]) ifx>=m-3: m-1 ify>=n-3: n-1 ifx>=1andx<=(m-3)andy>=1andy<=(n-3): B=np.array([ [img[x-1,y-1],img[x-1,y], img[x-1,y+1], img[x-1,y+1]], [img[x,y-1],img[x,y], img[x,y+1],img[x,y+2]], [img[x+1,y-1],img[x+1,y], img[x+1,y+1],img[x+1,y+2]], [img[x+2,y-1],img[x+2,y], img[x+2,y+1],img[x+2,y+1]], ]) C=np.array([ [S(1+q)], [S(q)], [S(1-q)], [S(2-q)] ]) blue=np.dot(np.dot(A,B[:,:,0]),C)[0,0] green=np.dot(np.dot(A,B[:,:,1]),C)[0,0] red=np.dot(np.dot(A,B[:,:,2]),C)[0,0] #ajustthevaluetobein[0,255] defadjust(value): ifvalue>255: value=255 elifvalue<0: value=0 returnvalue blue=adjust(blue) green=adjust(green) red=adjust(red) emptyImage[i,j]=np.array([blue,green,red],dtype=np.uint8) returnemptyImage img=cv2.imread("e:\\lena.bmp") zoom=function(img,1024,1024) cv2.imshow("cubic",zoom) cv2.imshow("image",img) cv2.waitKey(0)补充知识:最邻近插值法(Thenearestinterpolation)实现图像缩放
也称零阶插值。它输出的像素灰度值就等于距离它映射到的位置最近的输入像素的灰度值。但当图像中包含像素之间灰度级有变化的细微结构时,最邻近算法会在图像中产生人为加工的痕迹。
具体计算方法:对于一个目的坐标,设为M(x,y),通过向后映射法得到其在原始图像的对应的浮点坐标,设为m(i+u,j+v),其中i,j为正整数,u,v为大于零小于1的小数(下同),则待求象素灰度的值f(m)。利用浮点m相邻的四个像素求f(m)的值。
functionre_im=nearest(im,p,q) %最邻近插值法,输入目标图像和行缩放、纵缩放倍数 %ziheng2016.3.27 [m,n]=size(im); im_R=im(:,:,1); im_G=im(:,:,2); im_B=im(:,:,3); l=round(m*p); h=round(n*q)/3; re_R=uint8(zeros(l,h)); re_G=uint8(zeros(l,h)); re_B=uint8(zeros(l,h)); fordstx=1:l fordsty=1:h srcx=max(1,min(m,round(dstx/p))); srcy=max(1,min(n/3,round(dsty/q))); re_R(dstx,dsty)=im_R(srcx,srcy); re_G(dstx,dsty)=im_G(srcx,srcy); re_B(dstx,dsty)=im_B(srcx,srcy); end end re_im=cat(3,re_R,re_G,re_B); figure,imshow(re_im);以上这篇python图像插值最近邻、双线性、双三次实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持毛票票。