改进离散小波变换的卫星图像压缩方法(Python)

复制代码
import pywt
import cv2
import numpy as np
import matplotlib.pyplot as plt
from PIL import Image
import numpy as np
from skimage.metrics import structural_similarity as compare_ssim

Peak Signal-to-Noise Ratio (PSNR)

复制代码
def PSNR(im1_path, im2_path):
    imageA = cv2.imread(im1_path)
    imageB = cv2.imread(im2_path)
    
    imageA = np.clip(np.array(imageA), 0, 255)
    imageB = np.clip(np.array(imageB), 0, 255)


    mse = np.mean((imageA - imageB) ** 2)
    
    if mse == 0:  
        return float('inf')
    
    max_pixel = 255.0 
    psnr_val = 20 * np.log10(max_pixel / np.sqrt(mse))
    
    return psnr_val

Structural Similarity Index (SSIM)

复制代码
def ssim(im1_path, im2_path):
    imageA = cv2.imread(im1_path)
    imageB = cv2.imread(im2_path)


    original_gray = cv2.cvtColor(imageA, cv2.COLOR_BGR2GRAY)
    compressed_gray = cv2.cvtColor(imageB, cv2.COLOR_BGR2GRAY)


    ssim_ = compare_ssim(original_gray, compressed_gray)


    return ssim_

Split image to RGB

复制代码
def split_rgb(path):
    image = cv2.imread(path) 
    b,g,r = cv2.split(image) 
    return b,g,r

Merge Image

复制代码
def save_im(path_sav,rgb):
    merged_image = cv2.merge(rgb)
    cv2.imwrite(path_sav, merged_image)
    return
def labels(im,wav,n):
    coeffs = pywt.wavedec2(im, wavelet=wav, level=n)
    coeff_arr, coeff_slices = pywt.coeffs_to_array(coeffs)
    return coeff_arr, coeff_slices

Discrete Wavelet Transform

复制代码
def DWT_new(image,wav,level,keep,path_coeff,path_binary_im):
    # Perform quantization and select threshold
    coeffs = pywt.wavedec2(image , wavelet=wav, level=level)
    coeff_arr, coeff_slices = pywt.coeffs_to_array(coeffs)


    Csort = np.sort(np.abs(coeff_arr.reshape(-1)))
    thresh = Csort[int(np.floor((1 - keep) * len(Csort)))]
    ind = np.abs(coeff_arr) > thresh
    Cfilt = coeff_arr * ind
    
    coeff_wav = []
    index = []
    matrix = np.zeros((Cfilt.shape[0],Cfilt.shape[1]), dtype=np.uint8)
    count = 0


    # Loop through the quantization coefficients after selecting the threshold and keep only non-zero coefficients 
    for i in range(Cfilt.shape[0]):
        for j in range(Cfilt.shape[1]):
            if Cfilt[i][j] != 0:
                coeff_wav.append(round(Cfilt[i][j],0))
                # Save the index of the non-zero coefficient position
                index.append(count)
            count+=1
            




  


    # Save non-zero coefficients
    coeff_wav = np.array(coeff_wav)
    np.save(path_coeff,coeff_wav)


    # Convert index to label image file in binary image format
    matrix[np.unravel_index(index, (Cfilt.shape[0],Cfilt.shape[1]))] = 1
    image = Image.fromarray(matrix * 255)
    image.save(path_binary_im)
    return

Decompression

复制代码
def de_DWT_new(path_coeff,path_binary_im,Cfilt,coeff_slices,wav):
    # Load file codebook and Label
    coeff_wav_load = np.load(path_coeff)
    image = Image.open(path_binary_im)  
    image_array = np.array(image)


    match_im = np.zeros((Cfilt.shape[0],Cfilt.shape[1]), dtype=float)


    count = 0
    # Loop through the loop to reconstruct the quantized image
    for i in range(image_array.shape[0]):
        for j in range(image_array.shape[1]):
            if image_array[i][j] != 0:
                match_im[i][j] = coeff_wav_load[count]
                count+=1
    coeffs_filt = pywt.array_to_coeffs(match_im, coeff_slices, output_format='wavedec2')
    # Regenerate the original image
    Arecon = pywt.waverec2(coeffs_filt, wavelet=wav)
    Arecon = (Arecon - np.min(Arecon)) / (np.max(Arecon) - np.min(Arecon)) * 255
    return Arecon
path = "satellite_image.png"
rgb = ['Red','Green','Blue']


RGB_image = split_rgb(path)


plt.figure(figsize=(15,9))


for i in range(len(RGB_image)):
    plt.subplot(1, 3, i+1)
    plt.axis('off')
    plt.title(rgb[i])
    plt.imshow(RGB_image[i],'gray')
复制代码
wav = 'db4'
keep = 0.05
lev = 3
for i in range(len(RGB_image)):
    path_coeff = f'coeff_{rgb[i]}.npy'
    path_binary_im = f'binary_im_{rgb[i]}.png'
    DWT_new(RGB_image[i],wav,lev,keep,path_coeff,path_binary_im)
rgb_decompression = []
for i in range(len(RGB_image)):
    path_coeff = f'coeff_{rgb[i]}.npy'
    path_binary_im = f'binary_im_{rgb[i]}.png'
    
    Cfilt,coeff_slices = labels(RGB_image[i],wav,lev)


    rgb_decompression.append(de_DWT_new(path_coeff,path_binary_im,Cfilt,coeff_slices,wav))


save_im('decompression_image.png',rgb_decompression)
plt.figure(figsize=(15,9))


for i in range(len(RGB_image)):
    plt.subplot(1, 3, i+1)
    plt.axis('off')
    plt.title(f'{rgb[i]}-compressed')
    plt.imshow(rgb_decompression[i],'gray')
复制代码
psnr = PSNR('decompression_image.png',"satellite_image.png")
ssim_ = ssim('decompression_image.png',"satellite_image.png")


print(f"PSNR : {psnr}")
print(f"SSIM : {ssim_}")
PSNR : 29.574974444821635
SSIM : 0.7271495852092889

 
擅长领域:现代信号处理,机器学习,深度学习,数字孪生,时间序列分析,设备缺陷检测、设备异常检测、设备智能故障诊断与健康管理PHM等。
知乎学术咨询:https://www.zhihu.com/consult/people/792359672131756032?isMe=1
擅长领域:现代信号处理,机器学习,深度学习,数字孪生,时间序列分析,设备缺陷检测、设备异常检测、设备智能故障诊断与健康管理PHM等。

知乎学术咨询:擅长领域:现代信号处理,机器学习,深度学习,数字孪生,时间序列分析,设备缺陷检测、设备异常检测、设备智能故障诊断与健康管理PHM等。

相关推荐
扬帆起航136 分钟前
亚马逊新品推广破局指南:从手动试错到智能闭环的系统化路径
大数据·数据库·人工智能
小王爱学人工智能7 分钟前
利用OpenCV进行指纹识别的案例
人工智能·opencv·计算机视觉
代码AI弗森8 分钟前
DPO 深度解析:从公式到工程,从偏好数据到可复用训练管线
人工智能
Q_Q196328847513 分钟前
python+springboot+uniapp微信小程序题库系统 在线答题 题目分类 错题本管理 学习记录查询系统
spring boot·python·django·uni-app·node.js·php
Elastic 中国社区官方博客14 分钟前
使用 LangExtract 和 Elasticsearch
大数据·人工智能·elasticsearch·搜索引擎·ai·信息可视化·全文检索
共享家952723 分钟前
经典动态规划题解
算法·leetcode·动态规划
Pluchon23 分钟前
硅基计划3.0 Map类&Set类
java·开发语言·数据结构·算法·哈希算法·散列表
lifallen28 分钟前
淘宝RecGPT:通过LLM增强推荐
人工智能·深度学习·ai·推荐算法
Rhys..30 分钟前
.gitignore文件的作用及用法
python·github
42fourtytoo1 小时前
天津大学智算2026预推免机试第二批题目及代码c++
开发语言·c++·面试