JPG編碼的第3步是量化。對於通過離散餘弦變化後的8*8block的數據,咱們要對這8*8的數據進行量化。在JPEG中量化就是對數據V除以某個數Q,獲得round(V/Q)代替原來的數據。而後在JPG解碼的時候再乘以M獲得V。html
須要注意的是,量化會丟失圖片精度,並且是不可逆的。git
M的大小同時也影響壓縮的效果。M越大壓縮效果越好,可是圖片精度損失越大。github
圖片引用自"Compressed Image File Formats JPEG, PNG, GIF, XBM, BMP - John Miano"[1]ide
首先咱們會有一個8*8的量化表,這個表能夠自定義,也能夠用JPEG標準提供的量化表。學習
直接用咱們的8*8的Block數據,除以對應的QuantizationTable的數據便可。ui
const Block QUANTIZATION_TABLE_Y = {16, 11, 10, 16, 24, 40, 51, 61, 12, 12, 14, 19, 26, 58, 60, 55, 14, 13, 16, 24, 40, 57, 69, 56, 14, 17, 22, 29, 51, 87, 80, 62, 18, 22, 37, 56, 68, 109, 103, 77, 24, 35, 55, 64, 81, 104, 113, 92, 49, 64, 78, 87, 103, 121, 120, 101, 72, 92, 95, 98, 112, 100, 103, 99 }; const Block QUANTIZATION_TABLE_CBCR = { 17, 18, 24, 47, 99, 99, 99, 99, 18, 21, 26, 66, 99, 99, 99, 99, 24, 26, 56, 99, 99, 99, 99, 99, 47, 66, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99 };
假設咱們的數據如左下,量化表如右下. 編碼
則round(V / A)就是咱們須要的值了spa
void JPG::quantization() { for (uint i = 0; i < mcuHeight; i++) { for (uint j = 0; j < mcuWidth; j++) { MCU& currentMCU = data[i * mcuWidth + j]; //iterate over 每個component Y, cb cr for (uint componentID = 1; componentID <= 3; componentID++) { //遍歷block for(uint ii = 0; ii < getVerticalSamplingFrequency(componentID); ii++) { for(uint jj = 0; jj < getHorizontalSamplingFrequency(componentID); jj++) { Block& currentBlock = currentMCU[componentID][ii * getHorizontalSamplingFrequency(componentID) + jj]; const Block& quantizationTable = getQuantizationTableByID(componentID); //這一步就是對64個像素進行量化 for(uint index = 0; index < 64; index++) { currentBlock[index] = currentBlock[index] / quantizationTable[index]; } } } } } } }
以上所有的代碼在https://github.com/Cheemion/JPEG_COMPRESS/tree/main/Day4code
Thanks for reading,component
Wish you have a good day.
>>>> JPG學習筆記5(待續)