s1093705 作業6

 

Run-Length Based Image Compression 練習

題目說明:

附件中為三張利用將晶片高度以色彩視覺化後的圖片。

請設計一個基於Run-Length 的壓縮法方,對圖檔作無失真壓縮後儲存成新檔案。

部落格上應敘述你的壓縮方法,提供壓縮檔之格式,並計算三張圖的平均壓縮率

(compression ratio)。


開發環境:

  • Windows 11 
  • Visual Studio Code
  • Python 3.11.2 
  • Opencv 4.7.0


實作結果:

Run length format:
[0, 0, 0, 128, 255, 255] -> 0 3 128 1 255 2


程式說明:

1. Import library

from PIL import Image
import numpy as np
import os

2. run-length encoding algorithm

def RLE_encoding(img, bits=8):
    encoded = []
    count = 0
    prev = None
    fimg = img.flatten()
   
    for pixel in fimg:
        if prev==None:
            prev = pixel
            count+=1
        else:
            if prev!=pixel:
                encoded.append((count, prev))
                prev=pixel
                count=1
            else:
                if count<(2**bits)-1:
                    count+=1
                else:
                    encoded.append((count, prev))
                    prev=pixel
                    count=1
    encoded.append((count, prev))
    return np.array(encoded)


3. read image file

    img = Image.open(infile_name[i], 'r')

4. turn image into numpy array

    pixels = np.array(img)

5. split the image into RGB three channels 

    b, g, r = pixels[:, :, 0], pixels[:, :, 1], pixels[:, :, 2]

6. encode three channels

    be, ge, gf = RLE_encoding(b), RLE_encoding(g), RLE_encoding(r)
    cat = np.concatenate((be, ge, gf), axis=0)

7. calculate the compression rate

rate = round(infile_size / outfile_size, 2)

留言

這個網誌中的熱門文章

rzwang Homework #1

s1101438 Homework #1

s1093309 作業6