opencv最邻近插值图像缩放

淡淡的烟草味﹌ 2021-11-16 13:20 440阅读 0赞

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,代码实现:

  1. import cv2
  2. import numpy as np
  3. img = cv2.imread('image0.jpg',1)
  4. imgInfo = img.shape
  5. height = imgInfo[0]
  6. width = imgInfo[1]
  7. dstHeight = int(height/2)
  8. dstWidth = int(width/2)
  9. dstImage = np.zeros((dstHeight,dstWidth,3),np.uint8)#0-255
  10. for i in range(0,dstHeight):#行
  11. for j in range(0,dstWidth):#列
  12. iNew = int(i*(height*1.0/dstHeight))
  13. jNew = int(j*(width*1.0/dstWidth))
  14. dstImage[i,j] = img[iNew,jNew]
  15. cv2.imshow('dst',dstImage)
  16. cv2.waitKey(0)

3,图片缩放的另一种具体实现:

  1. #[[A1 A2 B1],[A3 A4 B2]]
  2. # [[A1 A2],[A3 A4]] [[B1],[B2]]
  3. # newX = A1*x + A2*y+B1
  4. # newY = A3*x +A4*y+B2
  5. # x->x*0.5 y->y*0.5
  6. # newX = 0.5*x
  7. import cv2
  8. import numpy as np
  9. img = cv2.imread('image0.jpg',1)
  10. cv2.imshow('src',img)
  11. imgInfo = img.shape
  12. height = imgInfo[0]
  13. width = imgInfo[1]
  14. #A = [0.5,0;0,0.0.5]; b = [0;0]
  15. matScale = np.float32([[0.5,0,0],[0,0.5,0]])
  16. dst = cv2.warpAffine(img,matScale,(int(width/2),int(height/2)))
  17. cv2.imshow('dst',dst)
  18. cv2.waitKey(0)

发表评论

表情:
评论列表 (有 0 条评论,440人围观)

还没有评论,来说两句吧...

相关阅读

    相关 OpenCV 几何变换-图像

    图像的缩放主要用于改变图像的大小,缩放后图像的图像的宽度和高度会发生变化。在图像处理中是一种很基础的几何变换,但是具有很重要的作用,比如:当输入图片尺寸过大时,处理速度会很慢,