用opencv的API实现缩放非常的简单
#用API实现图片缩放
import cv2
img = cv2.imread('c.jpg', 1) #后面的1表示彩色,0表示黑白
shape = img.shape #获取图像的宽、高、颜色层数
height = shape[0] #!!!重点,shape[0]表示高,我输错调了一个钟
width = shape[1]
destHeight = int(height * 0.1) #目标大小
destWidth = int(width * 0.1)
img = cv2.resize(img, (destWidth, destHeight)) ##核心API
cv2.imshow('img',img) #显示图片
print('end')
cv2.waitKey(0)
最近邻插值法原理很简单,就是找在原图像中找相应的点相素 : 将变换后的图像中的原像素点最邻近像素的灰度值赋给原像素点的方法。百度很多,可以查一下,以下是python实现,如不懂numpy,建议好好学一下
# 自己的编码实现图片缩放:最近邻插值法
import numpy as np
import cv2
img = cv2.imread('c.jpg', 1)
shape = img.shape
height = shape[0]
width = shape[1]
imgDeep = shape[2]
destWidth = int(width * 0.2)
destHeight = int(height * 0.2)
destImg = np.zeros((destHeight, destWidth, imgDeep), np.uint8)#目标图像矩阵,opencv读入的数据其实也是一个矩阵
for i in range(0, destHeight):
for j in range(0, destWidth):
iNew = int(i * (height*1.0 / destHeight))
jNew = int(j * (width*1.0 / destWidth))
destImg[i,j] = img[iNew, jNew]
print('end')
cv2.imshow('destImg', destImg)
cv2.waitKey(0)