Image Quantization

Question:

Write a function that takes a gray image and a target number of gray levels as input, andgenerates the quantized image as output. The function prototype is “quantize(input img,level) → output img”, where “level” is an integer in [1, 256] defining the number of gray levelsof output. You can modify the prototype if necessary.For the report, please load your input image and use your “quantize” function to:

1. Reduce gray level resolution to 128, 32, 8, 4 and 2 levels, then paste your results respectively.Note that, in practice computers always represent “white” via the pixel value of 255, soyou should also follow this rule. For example, when the gray level resolution is reduced to4 levels, the resulting image should contain pixels of 0, 85, 170, 255, instead of 0, 1, 2, 3. 

2. Detailedly discuss how you implement the quantization operation, i.e., the “quantize”function, in less than 2 pages. Again, please focus on the algorithm part. Analyzingand discussing interesting experiment results are also welcomed, but please don’t widelycopy/paste your codes in the report.

Answer:

function quantize( I, GreyNum)
if isstr(I)
    img = imread(I);
end
[row,col] = size(img);
new = zeros(row,col);
r = 256/GreyNum; %确定区间长度
r2 = 255/(GreyNum-1); %确定区间首尾
for j = 1:col 
    for i = 1:row
        for n = 1:GreyNum
            if (img(i,j) < n*r)
                new(i,j) = 0 + (n-1) * r2;
                break;
            end
        end
    end
end
new = uint8(new);
figure
imshow(new);
axis on
title(['量化后的图像(大小: ',num2str(col),'*',num2str(row),'*',...
    ', 灰度分辨率: ',num2str(GreyNum),')']);
end

Algorithm description:

量化算法很简单,就是通过将原图像 256 个灰度值等分区域地映射到要 求下降的灰度分辨率上的某个值上。比如要将灰度分辨率降为 4,那么就将原图 像灰度值为 0—63 范围内的像素点的灰度值映射为 0,在 64—127 范围内的像 素点的灰度值映射为 85,在 128—191 内的映射为 170,在 192—255 范围内的映射为 255。以此类推。

猜你喜欢

转载自blog.csdn.net/qq_34200964/article/details/79517932