summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorRishi-k-s <rishikrishna.sr@gmail.com>2025-11-06 22:27:14 +0530
committerRishi-k-s <rishikrishna.sr@gmail.com>2025-11-06 22:27:14 +0530
commit9224d9b6435cd18a3ecbba630bf6219690b21732 (patch)
tree13a0eee8e185840d43bdce68fd156ce674000388
parent46e7b3518313689ef2bf8456a2fd880afc2ca4a2 (diff)
Fix heart-rate extraction: robust peak detection and safe returnHEADmaster
-rw-r--r--.gitignore228
-rw-r--r--heartrate.py29
-rw-r--r--main.py34
3 files changed, 271 insertions, 20 deletions
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..a58ad55
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,228 @@
+# Byte-compiled / optimized / DLL files
+__pycache__/
+*.py[codz]
+*$py.class
+
+# C extensions
+*.so
+
+# Distribution / packaging
+.Python
+build/
+develop-eggs/
+dist/
+downloads/
+eggs/
+.eggs/
+lib/
+lib64/
+parts/
+sdist/
+var/
+wheels/
+share/python-wheels/
+*.egg-info/
+.installed.cfg
+*.egg
+MANIFEST
+
+# PyInstaller
+# Usually these files are written by a python script from a template
+# before PyInstaller builds the exe, so as to inject date/other infos into it.
+*.manifest
+*.spec
+
+# Installer logs
+pip-log.txt
+pip-delete-this-directory.txt
+
+# Unit test / coverage reports
+htmlcov/
+.tox/
+.nox/
+.coverage
+.coverage.*
+.cache
+nosetests.xml
+coverage.xml
+*.cover
+*.py.cover
+.hypothesis/
+.pytest_cache/
+cover/
+
+# Translations
+*.mo
+*.pot
+
+# Django stuff:
+*.log
+local_settings.py
+db.sqlite3
+db.sqlite3-journal
+
+# Flask stuff:
+instance/
+.webassets-cache
+
+# Scrapy stuff:
+.scrapy
+
+# Sphinx documentation
+docs/_build/
+
+# PyBuilder
+.pybuilder/
+target/
+
+# Jupyter Notebook
+.ipynb_checkpoints
+
+# IPython
+profile_default/
+ipython_config.py
+
+# pyenv
+# For a library or package, you might want to ignore these files since the code is
+# intended to run in multiple environments; otherwise, check them in:
+# .python-version
+
+# pipenv
+# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
+# However, in case of collaboration, if having platform-specific dependencies or dependencies
+# having no cross-platform support, pipenv may install dependencies that don't work, or not
+# install all needed dependencies.
+# Pipfile.lock
+
+# UV
+# Similar to Pipfile.lock, it is generally recommended to include uv.lock in version control.
+# This is especially recommended for binary packages to ensure reproducibility, and is more
+# commonly ignored for libraries.
+# uv.lock
+
+# poetry
+# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
+# This is especially recommended for binary packages to ensure reproducibility, and is more
+# commonly ignored for libraries.
+# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
+# poetry.lock
+# poetry.toml
+
+# pdm
+# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
+# pdm recommends including project-wide configuration in pdm.toml, but excluding .pdm-python.
+# https://pdm-project.org/en/latest/usage/project/#working-with-version-control
+# pdm.lock
+# pdm.toml
+.pdm-python
+.pdm-build/
+
+# pixi
+# Similar to Pipfile.lock, it is generally recommended to include pixi.lock in version control.
+# pixi.lock
+# Pixi creates a virtual environment in the .pixi directory, just like venv module creates one
+# in the .venv directory. It is recommended not to include this directory in version control.
+.pixi
+
+# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
+__pypackages__/
+
+# Celery stuff
+celerybeat-schedule
+celerybeat.pid
+
+# Redis
+*.rdb
+*.aof
+*.pid
+
+# RabbitMQ
+mnesia/
+rabbitmq/
+rabbitmq-data/
+
+# ActiveMQ
+activemq-data/
+
+# SageMath parsed files
+*.sage.py
+
+# Environments
+.env
+.envrc
+.venv
+env/
+venv/
+ENV/
+env.bak/
+venv.bak/
+
+# Spyder project settings
+.spyderproject
+.spyproject
+
+# Rope project settings
+.ropeproject
+
+# mkdocs documentation
+/site
+
+# mypy
+.mypy_cache/
+.dmypy.json
+dmypy.json
+
+# Pyre type checker
+.pyre/
+
+# pytype static type analyzer
+.pytype/
+
+# Cython debug symbols
+cython_debug/
+
+# PyCharm
+# JetBrains specific template is maintained in a separate JetBrains.gitignore that can
+# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
+# and can be added to the global gitignore or merged into this file. For a more nuclear
+# option (not recommended) you can uncomment the following to ignore the entire idea folder.
+# .idea/
+
+# Abstra
+# Abstra is an AI-powered process automation framework.
+# Ignore directories containing user credentials, local state, and settings.
+# Learn more at https://abstra.io/docs
+.abstra/
+
+# Visual Studio Code
+# Visual Studio Code specific template is maintained in a separate VisualStudioCode.gitignore
+# that can be found at https://github.com/github/gitignore/blob/main/Global/VisualStudioCode.gitignore
+# and can be added to the global gitignore or merged into this file. However, if you prefer,
+# you could uncomment the following to ignore the entire vscode folder
+# .vscode/
+
+# Ruff stuff:
+.ruff_cache/
+
+# PyPI configuration file
+.pypirc
+
+# Marimo
+marimo/_static/
+marimo/_lsp/
+__marimo__/
+
+# Streamlit
+.streamlit/secrets.toml
+20251106_152546.mp4
+
+.vscode/*
+!.vscode/settings.json
+!.vscode/tasks.json
+!.vscode/launch.json
+!.vscode/extensions.json
+!.vscode/*.code-snippets
+!*.code-workspace
+
+# Built Visual Studio Code Extensions
+*.vsix \ No newline at end of file
diff --git a/heartrate.py b/heartrate.py
index 2e9e0c7..0e77df7 100644
--- a/heartrate.py
+++ b/heartrate.py
@@ -2,23 +2,26 @@ from scipy import signal
# Calculate heart rate from FFT peaks
def find_heart_rate(fft, freqs, freq_min, freq_max):
- fft_maximums = []
+ import numpy as np
+ # Build amplitude array for frequency bins within range
+ fft_maximums = np.zeros(fft.shape[0], dtype=np.float32)
for i in range(fft.shape[0]):
if freq_min <= freqs[i] <= freq_max:
- fftMap = abs(fft[i])
- fft_maximums.append(fftMap.max())
- else:
- fft_maximums.append(0)
+ fft_map = np.abs(fft[i])
+ # maximum amplitude across spatial channels
+ fft_maximums[i] = float(fft_map.max())
+ # Find peaks in the amplitude spectrum
peaks, properties = signal.find_peaks(fft_maximums)
- max_peak = -1
- max_freq = 0
- # Find frequency with max amplitude in peaks
- for peak in peaks:
- if fft_maximums[peak] > max_freq:
- max_freq = fft_maximums[peak]
- max_peak = peak
+ if len(peaks) == 0:
+ # No clear peak found
+ return None
- return freqs[max_peak] * 60
+ # Select peak with maximum amplitude
+ peak_amplitudes = fft_maximums[peaks]
+ best_idx = peaks[np.argmax(peak_amplitudes)]
+
+ # Convert frequency (Hz) to beats per minute
+ return float(freqs[best_idx]) * 60.0
diff --git a/main.py b/main.py
index 623e5af..5a626be 100644
--- a/main.py
+++ b/main.py
@@ -12,9 +12,9 @@ freq_min = 1
freq_max = 1.8
# Mode: 'heartrate' or 'deepfake'
-MODE = 'deepfake' # Change to 'heartrate' for original functionality
+MODE = 'heartrate' # Change to 'heartrate' for original functionality
-video_path = '/Users/aloshdenny/Downloads/videoplayback.mp4'
+video_path = '/home/rishi/devmt/deepfake-eulerian-video-magnification/20251106_152546.mp4'
# Preprocessing phase - optimized to reduce memory
print("Reading + preprocessing video...")
@@ -55,11 +55,22 @@ for i, video in enumerate(lap_video):
result, fft, frequencies = eulerian.fft_filter(video, freq_min, freq_max, fps)
lap_video[i] += result
+ # Compute heart rate from middle pyramid level when in heartrate mode
+ if MODE == 'heartrate' and i == 1:
+ try:
+ heart_rate = heartrate.find_heart_rate(fft, frequencies, freq_min, freq_max)
+ if heart_rate is None:
+ print(f"Warning: could not estimate heart rate from level {i}")
+ else:
+ print(f"Estimated heart rate (from level {i}): {heart_rate:.2f} bpm")
+ except Exception as e:
+ print("Warning: failed to compute heart rate:", e)
+
# Store FFT data for deepfake detection (only for middle level to save memory)
if i == 1 and MODE == 'deepfake':
all_fft.append(fft)
all_frequencies.append(frequencies)
-
+
# Free intermediate results
del result, fft, frequencies
gc.collect()
@@ -72,14 +83,19 @@ if MODE == 'deepfake' and len(all_fft) > 0:
freq_max=freq_max,
confidence_threshold=0.6
)
+ # Keep a reference to the FFT/frequencies used for visualization
+ saved_fft = all_fft[0]
+ saved_frequencies = all_frequencies[0]
+
detection_result = detector.detect(
- all_fft[0],
- all_frequencies[0],
+ saved_fft,
+ saved_frequencies,
freq_min,
freq_max,
video_frames=None, # Don't pass video_frames to save memory
detailed=True
)
+ # Free large arrays after creating saved references
del all_fft, all_frequencies
gc.collect()
@@ -97,8 +113,12 @@ elif MODE == 'deepfake':
try:
import matplotlib
matplotlib.use('TkAgg') # or 'Qt5Agg' depending on your system
- detector.visualize_detection(fft, frequencies, detection_result,
- save_path='deepfake_analysis.png')
+ # Use saved FFT/frequencies from detection if available
+ if 'saved_fft' in locals() and 'saved_frequencies' in locals():
+ detector.visualize_detection(saved_fft, saved_frequencies, detection_result,
+ save_path='deepfake_analysis.png')
+ else:
+ print("No FFT data available for visualization")
except ImportError:
print("Matplotlib not available for visualization")