图像采样与量化
MATLAB程序:
I = imread('hw1.jpg'); % 读入图像
I1 = rgb2gray(I); % 将RGB图像转换为灰度图像
% 采样:
I2 = I1(1:2:end, 1:2:end); % 图像缩小1/4
I3 = I1(1:4:end, 1:4:end); % 图像缩小1/8
I4 = I1(1:8:end, 1:8:end); % 图像缩小1/16
I5 = I1(1:16:end, 1:16:end); % 图像缩小1/32
figure;
subplot(2, 3, 1);
imshow(I);
title('src image');
subplot(2, 3, 2);
imshow(I1);
title('256*256');
subplot(2, 3, 3);
imshow(I2);
title('128*128');
subplot(2, 3, 4);
imshow(I3);
title('64*64');
subplot(2, 3, 5);
imshow(I4);
title('32*32');
subplot(2, 3, 6);
imshow(I5);
title('16*16');
% 量化:
figure;
subplot(2, 3, 1);
imshow(I1);
title('8bit(256级)');
I2 = round(double(I1)/4)*4; % 灰度级变为4的倍数,即减少1/4
subplot(2, 3, 2);
imshow(uint8(I2));
title('6bit(64级)');
I3 = round(double(I1)/16)*16; % 灰度级减少1/16
subplot(2, 3, 3);
imshow(uint8(I3));
title('4bit(16级)');
I4 = round(double(I1)/32)*32; % 灰度级减少1/32
subplot(2, 3, 4);
imshow(uint8(I4));
title('3bit(8级)');
I5 = round(double(I1)/64)*64; % 灰度级减少1/64
subplot(2, 3, 5);
imshow(uint8(I5));
title('2bit(4级)');
I6 = round(double(I1)/128)*128; % 灰度级减少1/128
subplot(2, 3, 6);
imshow(uint8(I6));
title('1bit(2级)');
采样结果:
量化结果:
python程序
import cv2 as cv
import numpy as np
import matplotlib.pyplot as plt
img = cv.imread('hw1.jpg')
height = img.shape[0]
width = img.shape[1]
img1 = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
b,g,r = cv.split(img)
img = cv.merge([r,g,b])
img2 = img1[0:-1:2, 0:-1:2]
img3 = img1[0:-1:4, 0:-1:4]
img4 = img1[0:-1:8, 0:-1:8]
img5 = img1[0:-1:16, 0:-1:16]
plt.rcParams['font.sans-serif']=['SimHei']
titles = ['(a) img src', '(b) 256*265', '(c) 128*128', '(d) 64*64', '(d) 32*32', '(d) 16*16']
images = [img, img1, img2, img3, img4, img5]
for i in range(6):
plt.subplot(2,3,i+1)
if i == 0:
plt.imshow(images[i])
else:
plt.imshow(images[i], 'gray')
plt.title(titles[i])
plt.xticks([]),plt.yticks([])
plt.show()
img2 = np.zeros((height, width, 3), np.uint(8))
img3 = np.zeros((height, width, 3), np.uint(8))
img4 = np.zeros((height, width, 3), np.uint(8))
img5 = np.zeros((height, width, 3), np.uint(8))
img6 = np.zeros((height, width, 3), np.uint(8))
img2 = np.uint8(img1/4) * 4
img3 = np.uint8(img1/16) * 16
img4 = np.uint8(img1/32) * 32
img5 = np.uint8(img1/64) * 64
img6 = np.uint8(img1>=128) * 128
plt.rcParams['font.sans-serif']=['SimHei']
titles = ['(a) 原始图像', '(b) 量化-L64', '(c) 量化-L16', '(d) 量化-L8', '(d) 量化-L4', '(d) 量化-L2']
images = [img1, img2, img3, img4, img5, img6]
for i in range(6):
plt.subplot(2,3,i+1)
plt.imshow(images[i], 'gray')
plt.title(titles[i])
plt.xticks([]),plt.yticks([])
plt.show()
采样结果:
量化结果: