# @Time : 2023/8/15 16:29
# @Author : zp
# 参考书-----数字图像处理(第三版-冈萨雷斯)
# 图像采样
import numpy as np
from matplotlib import pyplot as plt
from PIL import Image
plt.rcParams['font.sans-serif'] = ['FangSong'] # 设置字体以便正确显示中文
def sampling(img, n):
"""
自己实现图像采样函数
:param img: 待采样的图像
:param n: 采样比率 整数
:return: 已采样的图像
"""
x = img.shape[0]
y = img.shape[1]
z = img.shape[2]
x1 = int(x/n)
y1 = int(y/n)
z1 = int(z)
s_img = np.zeros((x1, y1, z1), dtype='int32')
for i in range(x1):
for j in range(y1):
for k in range(z1):
s_img[i][j][k] = np.mean(img[i*n:(i+1)*n, j*n:(j+1)*n, k]) # 对采样区域取平均
return s_img
img0 = np.asarray(Image.open('lena.jpg')) # PIL库读取图片,并转换为ndarray格式
img1 = sampling(img0, 10)
img2 = sampling(img0, 20)
plt.subplot(131)
plt.title('原图')
plt.imshow(img0)
plt.subplot(132)
plt.title('采样率=10')
plt.imshow(img1)
plt.subplot(133)
plt.title('采样率=20')
plt.imshow(img2)
plt.show()
数字图像处理-采样
于 2023-08-16 13:21:14 首次发布