写一个在JupyterLab上对一张灰度图像进行JPEG图像压缩的代码
时间: 2024-02-21 18:58:13 浏览: 74
以下是一个在JupyterLab上对一张灰度图像进行JPEG图像压缩的Python代码示例:
```python
import numpy as np
import matplotlib.pyplot as plt
import imageio
from scipy.fftpack import dct, idct
# 读取灰度图像
img = imageio.imread('image.jpg', as_gray=True)
# 设置JPEG压缩参数
quality = 50 # 压缩质量(0-100)
# 对图像进行分块并进行DCT变换
block_size = 8
height, width = img.shape
dct_img = np.zeros((height, width))
for i in range(0, height, block_size):
for j in range(0, width, block_size):
dct_img[i:i+block_size, j:j+block_size] = dct(img[i:i+block_size, j:j+block_size])
# 对DCT系数进行量化
quantization_table = np.array([[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]])
quantization_table = quantization_table * quality / 100
quantization_table = np.round(quantization_table)
dct_img_quantized = np.round(dct_img / quantization_table)
# 对量化后的DCT系数进行反量化
dct_img_dequantized = dct_img_quantized * quantization_table
# 对反量化后的DCT系数进行IDCT变换
img_reconstructed = np.zeros((height, width))
for i in range(0, height, block_size):
for j in range(0, width, block_size):
img_reconstructed[i:i+block_size, j:j+block_size] = idct(dct_img_dequantized[i:i+block_size, j:j+block_size])
# 显示压缩前后的图像
fig, axes = plt.subplots(1, 2, figsize=(10, 5))
axes[0].imshow(img, cmap='gray')
axes[0].set_title('Original Image')
axes[1].imshow(img_reconstructed, cmap='gray')
axes[1].set_title('JPEG Compressed Image (Quality = {})'.format(quality))
plt.show()
```
在代码中,首先使用`imageio.imread`读取灰度图像。然后设置JPEG压缩参数`quality`,并使用`scipy.fftpack.dct`对图像进行分块并进行DCT变换。接着使用自定义的量化表对DCT系数进行量化,并对量化后的DCT系数进行反量化、IDCT变换,得到压缩后的图像。最后使用`matplotlib.pyplot`显示压缩前后的图像。
阅读全文