s1081440 作業六
主題
附件中為三張利用將晶片高度以色彩視覺化後的圖片。
請設計一個基於 Run-Length 的壓縮法方,對圖檔作無失真壓縮後儲存成新檔案。
部落格上應敘述你的壓縮方法,提供壓縮檔之格式,並計算三張圖的平均壓縮率(compression ratio)。
開發環境
Windows 11+ Visual Studio Code Python 3.10.4
程式說明
之後進行run_length_compression
將資料壓縮儲存到txt檔
確認壓縮後的資料根據重複次數(run_count)可以還原回png檔(也是利用PIL)
from PIL import Image
img1 = Image.open('img1.bmp')
img2 = Image.open('img2.bmp')
img3 = Image.open('img3.bmp')
def run_length_compression(img):
pixel = list(img.getdata())
run_count = 1
run_compress_img = []
for i in range(1, len(pixel)):
if pixel[i] == pixel[i-1]:
run_count += 1
else:
run_compress_img.append((pixel[i-1], run_count))
run_count = 1
run_compress_img.append((pixel[-1], run_count))
return run_compress_img
def output_txt(lst, path):
f = open(path, 'w')
f.writelines('%s %s\n' % tu for tu in lst)
f.close()
def decode_pixels(img, lst):
width, length = img.size
new_image = Image.new('RGB', (width, length))
decode_lst = []
for i in range(0, len(lst)):
for j in range(0, lst[i][1]):
decode_lst.append(lst[i][0])
new_image.putdata(decode_lst)
return new_image
c_img1 = run_length_compression(img1) # 1061987
c_img2 = run_length_compression(img2) # 1767862
c_img3 = run_length_compression(img3) # 1012413
output_txt(c_img1, 'c_img1.txt')
output_txt(c_img2, 'c_img2.txt')
output_txt(c_img3, 'c_img3.txt')
new_img1 = decode_pixels(img1, c_img1)
new_img2 = decode_pixels(img2, c_img2)
new_img3 = decode_pixels(img3, c_img3)
new_img1.save('new_img1.png')
new_img2.save('new_img2.png')
new_img3.save('new_img3.png')
img1 = 16585/14322*100 = 116%
img2 = 28383/14322*100 = 198%
img3 = 15984/14322*100 = 112%
還原結果:
留言
張貼留言