用Python写一个程序,对一个灰度图像进行图像分割8X8,并将各像素值减去128,进行D CT正向变换,再通过量化,最后进行Z字形重排序
时间: 2023-03-29 10:02:22 浏览: 144
您好,我是 CSDN 开发的 C 知道,关于您的问题,我可以回答。以下是 Python 代码实现:
```python
import numpy as np
from scipy.fftpack import dct
# 读取灰度图像
img = cv2.imread('gray_image.jpg', )
# 图像分割8X8
h, w = img.shape
img = img[:h//8*8, :w//8*8]
blocks = img.reshape(h//8, 8, -1, 8).swapaxes(1, 2).reshape(-1, 8, 8)
# 将各像素值减去128
blocks = blocks - 128
# DCT正向变换
dct_blocks = np.zeros_like(blocks)
for i in range(blocks.shape[]):
dct_blocks[i] = dct(dct(blocks[i], axis=, norm='ortho'), axis=1, norm='ortho')
# 量化
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]])
quantized_blocks = np.round(dct_blocks / quantization_table)
# Z字形重排序
zigzag_order = np.array([[, 1, 5, 6, 14, 15, 27, 28],
[2, 4, 7, 13, 16, 26, 29, 42],
[3, 8, 12, 17, 25, 30, 41, 43],
[9, 11, 18, 24, 31, 40, 44, 53],
[10, 19, 23, 32, 39, 45, 52, 54],
[20, 22, 33, 38, 46, 51, 55, 60],
[21, 34, 37, 47, 50, 56, 59, 61],
[35, 36, 48, 49, 57, 58, 62, 63]])
zigzag_blocks = np.zeros_like(quantized_blocks)
for i in range(quantized_blocks.shape[]):
zigzag_blocks[i] = quantized_blocks[i][zigzag_order.flatten()].reshape(8, 8)
# 输出结果
print(zigzag_blocks)
```
希望能对您有所帮助。
阅读全文