视频实时去雾:可用代码,python
·
- 效果

- 性能
在虚拟机上,处理一帧1280*720,需要约50ms。
画面有点暗,可以考虑加亮。
- 代码
从代码来看,还是暗通道算法。
import cv2
import numpy as np
import time
class SimpleFastDehazer:
"""超快速视频去雾(牺牲一些质量换取速度)"""
def __init__(self, w=0.8):
self.w = w
self.A = np.array([200, 200, 200], dtype=np.float32) # 初始大气光
def dehaze_frame_fast(self, img):
"""
极速去雾版本
处理640x480图像约3-5ms
"""
# 1. 快速估计大气光(取图像最亮的0.1%像素)
img_flat = img.reshape(-1, 3)
bright_thresh = np.percentile(img_flat, 99.9, axis=0)
bright_pixels = img_flat[np.all(img_flat >= bright_thresh * 0.9, axis=1)]
if len(bright_pixels) > 0:
A_est = np.mean(bright_pixels, axis=0)
# 平滑更新
self.A = 0.7 * self.A + 0.3 * A_est
# 2. 简单暗通道(使用下采样加速)
small = cv2.resize(img, (160, 120))
dark = np.min(small, axis=2)
dark = cv2.medianBlur(dark.astype(np.uint8), 5)
# 3. 简单透射率估计
transmission = 1 - self.w * (dark / 255.0)
transmission = cv2.resize(transmission, (img.shape[1], img.shape[0]))
transmission = np.clip(transmission, 0.1, 1.0)
# 4. 快速恢复
transmission = transmission[:, :, np.newaxis]
result = (img.astype(np.float32) - self.A) / transmission + self.A
return np.clip(result, 0, 255).astype(np.uint8)
# 使用示例
def real_time_dehazing(input_file, output_file):
dehazer = SimpleFastDehazer()
cap = cv2.VideoCapture(input_file)
fps = int(cap.get(cv2.CAP_PROP_FPS))
width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
# 初始化视频写入器
merge = True
write_w= width
if (merge): write_w += width
fourcc = cv2.VideoWriter_fourcc(*'mp4v')
out = cv2.VideoWriter(output_file, fourcc, fps, (write_w, height))
counter= 0
cost = 0
while True:
ret, frame = cap.read()
if not ret:
break
counter += 1
# 超快速去雾
start_time = time.time()
result = dehazer.dehaze_frame_fast(frame)
time_ms = (time.time() - start_time)*1000
cost += time_ms
# 显示
cv2.putText(result, f"{time_ms:.1f}ms", (30, 100),
cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 255, 0), 2)
if (merge):
result = cv2.hconcat([frame, result]);
out.write(result)
print(cost, '/', counter, '=', (cost/counter))
out.release()
cap.release()
if __name__ == "__main__":
input_file = '../fog5.mp4'
output_file = 'defog.mp4'
real_time_dehazing(input_file, output_file)
更多推荐



所有评论(0)