Hi trying to make a simple jpeg compressor which also decompresses the image. I use the following code to downsample the chrominance of an image for the first step of jpeg compression.
resampler = vision.ChromaResampler;
[Cb, Cr] = resampler(Cb_channel, Cr_channel);
the function is part of the computer vision toolbox for matlab.
for example before downsampling:
Y dimensions = 3024 by 4032; Cb and Cr dimensions = 3024 by 4032
after downsampling:
Y dimensions = 3024 by 4032; Cb and Cr dimensions = 3024 by 2016
to display the original RGB image after decompression, the dimensions of all 3 Y, Cb and Cr components need to be the same so that I can merge the channels and convert the image back to RGB. I'm using the following code to achieve this:
Cb_resized = imresize(Cb, [(size(Cb, 1)) (2*size(Cb, 2))]);
Cr_resized = imresize(Cr, [(size(Cr, 1)) (2*size(Cr, 2))]);
When I then merge the 3 channels and use imshow() to see the image it looks fine. So is the above method the correct way of reversing the downsampled chrominance when decoding a jpeg?
Using
imresizefor up-sampling is "almost correct".Instead of using
imresize, you better usevision.ChromaResamplerfor up-sampling:The module is design such that
Resampling = '4:2:2 to 4:4:4'"reverses" the result ofResampling = '4:4:4 to 4:2:2'.The
'4:4:4 to 4:2:2'ChromaResampler uses a convention that displaces the result 0.5 pixels to the right.(I think shifting by 0.5 pixels supposes to match MPEG-1 codec standard).
The 0.5 displacement is not well documented - I had to build a short test for figuring it out.
As far as I remember, the convention of moving 0.5 a pixel is used by MPEG-1 codec, but not used by MPEG-2 and newer codecs.
I don't think it is used by JPEG, but I am not sure...
Note:
Since the human visual system is not very sensitive to the Chroma resolution, you are probably not going to see the differences if 0.5 displacement is used or not.
For getting the same result as
ChromaResampler, you may use imwarp, with displacement of 1 pixel in the horizontal axis.Understanding
imwarpis a little complicated.I am going to use
imwarpfor demonstrating that 1 pixel displacement, gives the same result asChromaResampler:The following code sample shows the equivalence:
Note: The
imresizeusage is kept in comments.Note:
The default interpolation method of
imresizeis cubic interpolation, and the default interpolation method of ChromaResampler is linear interpolation.Cubic interpolation is considered superior, but linear interpolation is commonly used (the visible difference is negligible).