目录
一、下采样
对图像进行下采样,可以得到尺寸较小的图像,最简单直接的就是直接按照一定间隔选取原始图像的像素点,即直接下采样,但是这样做的效果并不好。可以采用高斯预滤波平滑图像,再进行下采样,这样会得到相对比较好的结果。
import cv2 as cv
import numpy as np
def simple_downsampling(image, scale_factor):
height, width = image.shape[:2]
new_height = int(height * scale_factor)
new_width = int(width * scale_factor)
new_image = np.zeros((new_height, new_width, 3), dtype=np.uint8)
for i in range(new_height):
for j in range(new_width):
new_image[i, j] = image[int(i / scale_factor), int(j / scale_factor)]
return new_image
img = cv.imread('./img.png')
height, width = img.shape[: 2]
print(height, width)
simple_downsampled_img = simple_downsampling(img,0.25)
new_height, new_width = simple_downsampled_img.shape[:2]
cv.imwrite('./simple_downsampling.jpg', simple_downsampled_img)
print(new_height, new_width)
# 高斯滤波
out_path2 = './gs_blurred.jpg'
kernel_size2 = (5, 5) # 滤波器大小
sigma_x = 0 # X方向的高斯核标准差,若为0,根据kernel_size自动计算
gs_blurred_image = cv.GaussianBlur(img, kernel_size2, sigma_x)
cv.imwrite(out_path2, gs_blurred_image)
gs_downsampling_img = simple_downsampling(gs_blurred_image,0.25)
new_height2, new_width2 = simple_downsampled_img.shape[:2]
cv.imwrite('./gs_downsampling_img.jpg', gs_downsampling_img)
print(new_height2, new_width2)
二、上采样
对图像上采样并进行插值可得到更大尺寸的图像。插值的方法有很多中,只需修改resize的参数即可以实现不同插值效果。
import cv2 as cv
# 读取图像
img = cv.imread('bee.png') # 替换成你的图像路径
height, width = img.shape[:2] # 获取图像的高度和宽度
print(height, width)
# 设置新的宽度和高度
new_width, new_height = 350,350 # 设置新的宽度和高度
# 最近邻插值
resized_image_INTER_NEAREST = cv.resize(img, (new_width, new_height), interpolation=cv.INTER_NEAREST)
cv.imwrite('./resized_image_INTER_NEAREST.png', resized_image_INTER_NEAREST)
# 调整图像大小并使用双线性插值
resized_image_INTER_LINEAR = cv.resize(img, (new_width, new_height), interpolation=cv.INTER_LINEAR)
cv.imwrite('./resized_image_INTER_LINEAR.png', resized_image_INTER_LINEAR)
# 双三次插值
resized_image_INTER_CUBIC = cv.resize(img, (new_width, new_height), interpolation=cv.INTER_CUBIC)
cv.imwrite('./resized_image_INTER_CUBIC.png', resized_image_INTER_CUBIC)