Skip to content

Instantly share code, notes, and snippets.

@curegit
Created July 29, 2024 09:40
Show Gist options
  • Save curegit/4e9cfeaa8d003c3f66a02ea7319290dd to your computer and use it in GitHub Desktop.
Save curegit/4e9cfeaa8d003c3f66a02ea7319290dd to your computer and use it in GitHub Desktop.
OpenCV で Non-local Means フィルタ(動画)
import itertools
from collections import deque
from rich.progress import track
import cv2
n = 5
process_frames = 60 * 3
cap = cv2.VideoCapture("SSX.avi")
width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
fps = float(cap.get(cv2.CAP_PROP_FPS))
def iframes(cap, max_frames=None):
i = 0
while cap.isOpened():
ret, frame = cap.read()
if not ret or max_frames is not None and i > max_frames:
break
yield frame
i += 1
def window(cap, n=5, max_frames=None):
pad = n // 2
queue = deque(maxlen=n)
for frame in itertools.chain([None] * pad, iframes(cap, max_frames=max_frames), [None] * pad):
queue.append(frame)
if len(queue) == n:
yield list(queue)
fourcc = cv2.VideoWriter_fourcc(*"mp4v")
writer = cv2.VideoWriter("OUTPUT.mp4", fourcc, fps, (width, height), isColor=True)
for frames in track(window(cap, n=n, max_frames=process_frames)):
while frames[0] is None or frames[-1] is None:
frames = frames[1:-1]
result = cv2.fastNlMeansDenoisingColoredMulti(frames, imgToDenoiseIndex=(len(frames) // 2), temporalWindowSize=len(frames), dst=None, h=4, hColor=4, templateWindowSize=5, searchWindowSize=17)
writer.write(result)
cap.release()
writer.release()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment