1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309
| import numpy as np from scipy.fftpack import dct, idct
class TransformCoding: """变换编码实现""" def __init__(self, block_size=8): self.block_size = block_size self.luminance_quant_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] ]) def dct2d(self, block): """二维DCT变换""" return dct(dct(block.T, norm='ortho').T, norm='ortho') def idct2d(self, block): """二维IDCT变换""" return idct(idct(block.T, norm='ortho').T, norm='ortho') def quantize(self, dct_block, quality=50): """量化""" if quality < 50: scale = 5000 / quality else: scale = 200 - 2 * quality quant_table = np.clip((self.luminance_quant_table * scale + 50) / 100, 1, 255) quantized = np.round(dct_block / quant_table) return quantized.astype(np.int32), quant_table def dequantize(self, quantized_block, quant_table): """反量化""" return quantized_block * quant_table def zigzag_scan(self, block): """之字形扫描""" zigzag_order = [ (0,0), (0,1), (1,0), (2,0), (1,1), (0,2), (0,3), (1,2), (2,1), (3,0), (4,0), (3,1), (2,2), (1,3), (0,4), (0,5), (1,4), (2,3), (3,2), (4,1), (5,0), (6,0), (5,1), (4,2), (3,3), (2,4), (1,5), (0,6), (0,7), (1,6), (2,5), (3,4), (4,3), (5,2), (6,1), (7,0), (7,1), (6,2), (5,3), (4,4), (3,5), (2,6), (1,7), (2,7), (3,6), (4,5), (5,4), (6,3), (7,2), (7,3), (6,4), (5,5), (4,6), (3,7), (4,7), (5,6), (6,5), (7,4), (7,5), (6,6), (5,7), (6,7), (7,6), (7,7) ] return [block[i, j] for i, j in zigzag_order] def inverse_zigzag_scan(self, zigzag_data): """逆之字形扫描""" block = np.zeros((8, 8)) zigzag_order = [ (0,0), (0,1), (1,0), (2,0), (1,1), (0,2), (0,3), (1,2), (2,1), (3,0), (4,0), (3,1), (2,2), (1,3), (0,4), (0,5), (1,4), (2,3), (3,2), (4,1), (5,0), (6,0), (5,1), (4,2), (3,3), (2,4), (1,5), (0,6), (0,7), (1,6), (2,5), (3,4), (4,3), (5,2), (6,1), (7,0), (7,1), (6,2), (5,3), (4,4), (3,5), (2,6), (1,7), (2,7), (3,6), (4,5), (5,4), (6,3), (7,2), (7,3), (6,4), (5,5), (4,6), (3,7), (4,7), (5,6), (6,5), (7,4), (7,5), (6,6), (5,7), (6,7), (7,6), (7,7) ] for idx, (i, j) in enumerate(zigzag_order): if idx < len(zigzag_data): block[i, j] = zigzag_data[idx] return block def run_length_encode(self, zigzag_data): """游程编码""" encoded = [] i = 0 while i < len(zigzag_data): if zigzag_data[i] == 0: zero_count = 0 while i < len(zigzag_data) and zigzag_data[i] == 0: zero_count += 1 i += 1 if i < len(zigzag_data): encoded.append((zero_count, zigzag_data[i])) i += 1 else: encoded.append((0, 0)) else: encoded.append((0, zigzag_data[i])) i += 1 return encoded def run_length_decode(self, encoded_data): """游程解码""" decoded = [] for zero_count, value in encoded_data: if zero_count == 0 and value == 0: break decoded.extend([0] * zero_count) if not (zero_count == 0 and value == 0): decoded.append(value) while len(decoded) < 64: decoded.append(0) return decoded[:64] def encode_block(self, block, quality=50): """编码单个块""" dct_block = self.dct2d(block - 128) quantized, quant_table = self.quantize(dct_block, quality) zigzag = self.zigzag_scan(quantized) encoded = self.run_length_encode(zigzag) return encoded, quant_table def decode_block(self, encoded_data, quant_table): """解码单个块""" zigzag = self.run_length_decode(encoded_data) quantized = self.inverse_zigzag_scan(zigzag) dct_block = self.dequantize(quantized, quant_table) reconstructed = self.idct2d(dct_block) + 128 return np.clip(reconstructed, 0, 255) def encode_image(self, image, quality=50): """编码整幅图像""" h, w = image.shape encoded_blocks = [] quant_tables = [] for y in range(0, h, self.block_size): for x in range(0, w, self.block_size): block = image[y:y+self.block_size, x:x+self.block_size] if block.shape != (self.block_size, self.block_size): padded_block = np.zeros((self.block_size, self.block_size)) padded_block[:block.shape[0], :block.shape[1]] = block block = padded_block encoded, quant_table = self.encode_block(block, quality) encoded_blocks.append(encoded) quant_tables.append(quant_table) return encoded_blocks, quant_tables, (h, w) def decode_image(self, encoded_blocks, quant_tables, image_shape): """解码整幅图像""" h, w = image_shape reconstructed = np.zeros((h, w)) block_idx = 0 for y in range(0, h, self.block_size): for x in range(0, w, self.block_size): if block_idx < len(encoded_blocks): decoded_block = self.decode_block(encoded_blocks[block_idx], quant_tables[block_idx]) end_y = min(y + self.block_size, h) end_x = min(x + self.block_size, w) reconstructed[y:end_y, x:end_x] = decoded_block[:end_y-y, :end_x-x] block_idx += 1 return reconstructed.astype(np.uint8) def calculate_compression_ratio(self, original_size, encoded_blocks): """计算压缩比""" total_symbols = sum(len(block) for block in encoded_blocks) compressed_size = total_symbols * 4 / 8 compression_ratio = original_size / compressed_size return compression_ratio, compressed_size
def demo_transform_coding(): test_image = np.zeros((64, 64), dtype=np.uint8) for i in range(64): for j in range(64): test_image[i, j] += 128 + 50 * np.sin(2 * np.pi * i / 32) test_image[i, j] += 20 * np.sin(2 * np.pi * i / 4) * np.sin(2 * np.pi * j / 4) test_image = np.clip(test_image, 0, 255).astype(np.uint8) tc = TransformCoding() qualities = [10, 30, 50, 70, 90] fig, axes = plt.subplots(2, len(qualities) + 1, figsize=(15, 6)) axes[0, 0].imshow(test_image, cmap='gray') axes[0, 0].set_title('原始图像') axes[1, 0].axis('off') original_size = test_image.size for i, quality in enumerate(qualities): print(f"\n质量级别: {quality}") encoded_blocks, quant_tables, shape = tc.encode_image(test_image, quality) reconstructed = tc.decode_image(encoded_blocks, quant_tables, shape) compression_ratio, compressed_size = tc.calculate_compression_ratio(original_size, encoded_blocks) mse = np.mean((test_image.astype(np.float32) - reconstructed.astype(np.float32)) ** 2) psnr = 20 * np.log10(255.0 / np.sqrt(mse)) if mse > 0 else float('inf') print(f"压缩比: {compression_ratio:.2f}:1") print(f"PSNR: {psnr:.2f} dB") print(f"压缩后大小: {compressed_size:.0f} 字节") axes[0, i+1].imshow(reconstructed, cmap='gray') axes[0, i+1].set_title(f'Q={quality}\nPSNR={psnr:.1f}dB') error_image = np.abs(test_image.astype(np.float32) - reconstructed.astype(np.float32)) axes[1, i+1].imshow(error_image, cmap='hot') axes[1, i+1].set_title(f'误差图像\n压缩比={compression_ratio:.1f}:1') plt.tight_layout() plt.show() sample_block = test_image[:8, :8] dct_coeffs = tc.dct2d(sample_block - 128) fig, axes = plt.subplots(1, 3, figsize=(12, 4)) axes[0].imshow(sample_block, cmap='gray') axes[0].set_title('原始块') im1 = axes[1].imshow(dct_coeffs, cmap='RdBu_r') axes[1].set_title('DCT系数') plt.colorbar(im1, ax=axes[1]) quantized, _ = tc.quantize(dct_coeffs, quality=50) im2 = axes[2].imshow(quantized, cmap='RdBu_r') axes[2].set_title('量化后系数') plt.colorbar(im2, ax=axes[2]) plt.tight_layout() plt.show()
demo_transform_coding()
|