Created
March 3, 2025 17:35
-
-
Save yoi-hibino/ba0d17921156e0981973f9bcb61f2dbe to your computer and use it in GitHub Desktop.
Shock Wave Imaging - Optical Flow Analysis
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import cv2 | |
import numpy as np | |
import matplotlib.pyplot as plt | |
cap = cv2.VideoCapture('video.mp4') | |
ret, prev_frame = cap.read() | |
if not ret: | |
raise ValueError("Could not read video.") | |
prev_gray = cv2.cvtColor(prev_frame, cv2.COLOR_BGR2GRAY) | |
while True: | |
ret, frame = cap.read() | |
if not ret: | |
break | |
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) | |
# Compute dense optical flow using Farneback's algorithm | |
flow = cv2.calcOpticalFlowFarneback(prev_gray, gray, None, | |
pyr_scale=0.5, levels=3, winsize=15, | |
iterations=3, poly_n=5, poly_sigma=1.2, flags=0) | |
# Prepare grid for visualization | |
h, w = gray.shape | |
step = 16 # grid spacing | |
y, x = np.mgrid[step//2:h:step, step//2:w:step].astype(int) | |
fx, fy = flow[y, x].T | |
plt.figure(figsize=(8, 8)) | |
plt.imshow(gray, cmap='gray') | |
plt.quiver(x, y, fx, fy, color='red', angles='xy', scale_units='xy', scale=1) | |
plt.title('Optical Flow Displacement Field') | |
plt.xlabel('X') | |
plt.ylabel('Y') | |
plt.pause(0.001) | |
plt.clf() | |
prev_gray = gray.copy() | |
cap.release() | |
plt.close() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Concept:
Another approach is to use optical flow, which computes the apparent motion between consecutive frames. Even without a static reference image, methods like the Farneback algorithm can capture the local displacements that might be induced by the shock wave. This approach works well when the shock wave produces subtle, rapid changes between successive frames.
Optical flow is computed between each pair of consecutive frames, capturing any transient shifts.
The resulting vector field may include contributions from overall scene or camera motion. Additional stabilization or filtering might be needed to isolate the shock-induced displacements.