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 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390
| import numpy as np from typing import Tuple, List, Dict, Optional from dataclasses import dataclass from enum import Enum import cv2 from scipy.optimize import minimize_scalar
class BlockSize(Enum): """块大小枚举""" SIZE_4x4 = (4, 4) SIZE_8x8 = (8, 8) SIZE_16x16 = (16, 16) SIZE_32x32 = (32, 32)
class PredictionMode(Enum): """预测模式枚举""" INTRA = "intra" INTER = "inter" SKIP = "skip" MERGE = "merge"
@dataclass class MotionVector: """运动矢量""" x: int y: int cost: float
@dataclass class CodingUnit: """编码单元""" x: int y: int width: int height: int mode: PredictionMode motion_vector: Optional[MotionVector] quantization_parameter: int rate: float distortion: float rd_cost: float
class VideoEncoder: """视频编码器""" def __init__(self, lambda_factor: float = 1.0): self.lambda_factor = lambda_factor self.search_range = 16 self.block_sizes = [BlockSize.SIZE_16x16, BlockSize.SIZE_8x8, BlockSize.SIZE_4x4] def motion_estimation_full_search(self, current_block: np.ndarray, reference_frame: np.ndarray, block_x: int, block_y: int) -> MotionVector: """全搜索运动估计""" block_height, block_width = current_block.shape ref_height, ref_width = reference_frame.shape best_mv = MotionVector(0, 0, float('inf')) for dy in range(-self.search_range, self.search_range + 1): for dx in range(-self.search_range, self.search_range + 1): ref_x = block_x + dx ref_y = block_y + dy if (ref_x >= 0 and ref_y >= 0 and ref_x + block_width <= ref_width and ref_y + block_height <= ref_height): ref_block = reference_frame[ref_y:ref_y + block_height, ref_x:ref_x + block_width] sad = np.sum(np.abs(current_block.astype(np.float32) - ref_block.astype(np.float32))) if sad < best_mv.cost: best_mv = MotionVector(dx, dy, sad) return best_mv def motion_estimation_diamond_search(self, current_block: np.ndarray, reference_frame: np.ndarray, block_x: int, block_y: int) -> MotionVector: """菱形搜索运动估计""" block_height, block_width = current_block.shape ref_height, ref_width = reference_frame.shape large_diamond = [(-2, 0), (0, -2), (2, 0), (0, 2)] small_diamond = [(-1, 0), (0, -1), (1, 0), (0, 1)] center_x, center_y = 0, 0 best_cost = self._calculate_block_cost(current_block, reference_frame, block_x + center_x, block_y + center_y) step_size = 2 while step_size >= 1: improved = False pattern = large_diamond if step_size == 2 else small_diamond for dx, dy in pattern: test_x = center_x + dx test_y = center_y + dy ref_x = block_x + test_x ref_y = block_y + test_y if (ref_x >= 0 and ref_y >= 0 and ref_x + block_width <= ref_width and ref_y + block_height <= ref_height): cost = self._calculate_block_cost(current_block, reference_frame, ref_x, ref_y) if cost < best_cost: best_cost = cost center_x, center_y = test_x, test_y improved = True if not improved: step_size //= 2 return MotionVector(center_x, center_y, best_cost) def _calculate_block_cost(self, current_block: np.ndarray, reference_frame: np.ndarray, ref_x: int, ref_y: int) -> float: """计算块匹配代价""" block_height, block_width = current_block.shape ref_block = reference_frame[ref_y:ref_y + block_height, ref_x:ref_x + block_width] sad = np.sum(np.abs(current_block.astype(np.float32) - ref_block.astype(np.float32))) return sad def rate_distortion_optimization(self, current_block: np.ndarray, reference_frame: np.ndarray, block_x: int, block_y: int, block_size: BlockSize) -> CodingUnit: """率失真优化""" width, height = block_size.value best_cu = None best_rd_cost = float('inf') intra_cu = self._test_intra_mode(current_block, block_x, block_y, width, height) if intra_cu.rd_cost < best_rd_cost: best_cu = intra_cu best_rd_cost = intra_cu.rd_cost inter_cu = self._test_inter_mode(current_block, reference_frame, block_x, block_y, width, height) if inter_cu.rd_cost < best_rd_cost: best_cu = inter_cu best_rd_cost = inter_cu.rd_cost skip_cu = self._test_skip_mode(current_block, reference_frame, block_x, block_y, width, height) if skip_cu.rd_cost < best_rd_cost: best_cu = skip_cu best_rd_cost = skip_cu.rd_cost return best_cu def _test_intra_mode(self, current_block: np.ndarray, block_x: int, block_y: int, width: int, height: int) -> CodingUnit: """测试帧内预测模式""" dc_value = np.mean(current_block) predicted_block = np.full_like(current_block, dc_value) residual = current_block.astype(np.float32) - predicted_block distortion = np.mean(residual ** 2) rate = self._estimate_intra_rate(residual) rd_cost = distortion + self.lambda_factor * rate return CodingUnit( x=block_x, y=block_y, width=width, height=height, mode=PredictionMode.INTRA, motion_vector=None, quantization_parameter=22, rate=rate, distortion=distortion, rd_cost=rd_cost ) def _test_inter_mode(self, current_block: np.ndarray, reference_frame: np.ndarray, block_x: int, block_y: int, width: int, height: int) -> CodingUnit: """测试帧间预测模式""" mv = self.motion_estimation_diamond_search(current_block, reference_frame, block_x, block_y) ref_x = block_x + mv.x ref_y = block_y + mv.y predicted_block = reference_frame[ref_y:ref_y + height, ref_x:ref_x + width] residual = current_block.astype(np.float32) - predicted_block.astype(np.float32) distortion = np.mean(residual ** 2) rate = self._estimate_inter_rate(residual, mv) rd_cost = distortion + self.lambda_factor * rate return CodingUnit( x=block_x, y=block_y, width=width, height=height, mode=PredictionMode.INTER, motion_vector=mv, quantization_parameter=22, rate=rate, distortion=distortion, rd_cost=rd_cost ) def _test_skip_mode(self, current_block: np.ndarray, reference_frame: np.ndarray, block_x: int, block_y: int, width: int, height: int) -> CodingUnit: """测试跳过模式""" predicted_block = reference_frame[block_y:block_y + height, block_x:block_x + width] distortion = np.mean((current_block.astype(np.float32) - predicted_block.astype(np.float32)) ** 2) rate = 1.0 rd_cost = distortion + self.lambda_factor * rate return CodingUnit( x=block_x, y=block_y, width=width, height=height, mode=PredictionMode.SKIP, motion_vector=MotionVector(0, 0, 0), quantization_parameter=22, rate=rate, distortion=distortion, rd_cost=rd_cost ) def _estimate_intra_rate(self, residual: np.ndarray) -> float: """估算帧内预测的码率""" variance = np.var(residual) rate = 0.5 * np.log2(2 * np.pi * np.e * variance + 1e-10) return max(rate, 0.1) def _estimate_inter_rate(self, residual: np.ndarray, mv: MotionVector) -> float: """估算帧间预测的码率""" residual_rate = self._estimate_intra_rate(residual) mv_rate = 2 + abs(mv.x) * 0.1 + abs(mv.y) * 0.1 return residual_rate + mv_rate def adaptive_quantization(self, frame: np.ndarray, target_bitrate: float) -> np.ndarray: """自适应量化""" complexity = self._calculate_frame_complexity(frame) base_qp = 22 complexity_factor = complexity / np.mean(complexity) adaptive_qp = np.zeros_like(complexity) for i in range(complexity.shape[0]): for j in range(complexity.shape[1]): if complexity_factor[i, j] > 1.5: adaptive_qp[i, j] = base_qp + 3 elif complexity_factor[i, j] < 0.5: adaptive_qp[i, j] = base_qp - 3 else: adaptive_qp[i, j] = base_qp return adaptive_qp def _calculate_frame_complexity(self, frame: np.ndarray) -> np.ndarray: """计算帧复杂度""" grad_x = cv2.Sobel(frame, cv2.CV_64F, 1, 0, ksize=3) grad_y = cv2.Sobel(frame, cv2.CV_64F, 0, 1, ksize=3) complexity = np.sqrt(grad_x**2 + grad_y**2) block_size = 16 height, width = frame.shape block_complexity = np.zeros((height // block_size, width // block_size)) for i in range(0, height - block_size, block_size): for j in range(0, width - block_size, block_size): block = complexity[i:i + block_size, j:j + block_size] block_complexity[i // block_size, j // block_size] = np.mean(block) return block_complexity
def demo_video_encoding_optimization(): print("Video Encoding Optimization Demo") print("================================") frame_size = (128, 128) current_frame = np.random.randint(0, 256, frame_size, dtype=np.uint8) reference_frame = np.random.randint(0, 256, frame_size, dtype=np.uint8) cv2.rectangle(current_frame, (20, 20), (60, 60), 200, -1) cv2.rectangle(reference_frame, (25, 25), (65, 65), 200, -1) encoder = VideoEncoder(lambda_factor=1.0) print("\n1. Motion Estimation Comparison") block_size = 16 test_block = current_frame[20:36, 20:36] mv_full = encoder.motion_estimation_full_search(test_block, reference_frame, 20, 20) print(f"Full search MV: ({mv_full.x}, {mv_full.y}), cost: {mv_full.cost:.2f}") mv_diamond = encoder.motion_estimation_diamond_search(test_block, reference_frame, 20, 20) print(f"Diamond search MV: ({mv_diamond.x}, {mv_diamond.y}), cost: {mv_diamond.cost:.2f}") print("\n2. Rate-Distortion Optimization") for block_size in encoder.block_sizes: width, height = block_size.value test_block = current_frame[20:20+height, 20:20+width] cu = encoder.rate_distortion_optimization(test_block, reference_frame, 20, 20, block_size) print(f"Block size {width}x{height}:") print(f" Best mode: {cu.mode.value}") print(f" Rate: {cu.rate:.2f}") print(f" Distortion: {cu.distortion:.2f}") print(f" RD cost: {cu.rd_cost:.2f}") if cu.motion_vector: print(f" Motion vector: ({cu.motion_vector.x}, {cu.motion_vector.y})") print("\n3. Adaptive Quantization") adaptive_qp = encoder.adaptive_quantization(current_frame, target_bitrate=1000) print(f"Adaptive QP map shape: {adaptive_qp.shape}") print(f"QP range: {np.min(adaptive_qp):.0f} - {np.max(adaptive_qp):.0f}") print(f"Average QP: {np.mean(adaptive_qp):.2f}") complexity = encoder._calculate_frame_complexity(current_frame) print(f"\nFrame complexity analysis:") print(f" Complexity range: {np.min(complexity):.2f} - {np.max(complexity):.2f}") print(f" Average complexity: {np.mean(complexity):.2f}") print("\nVideo encoding optimization demo completed")
if __name__ == "__main__": demo_video_encoding_optimization()
|