Skip to content

Free Motion Capture for Everyone πŸ’€βœ¨

TypeScript

DELETE ALL THE THINGS

Endurance Idehen726163a75086
diff --git a/CITATION.cff b/CITATION.cff
index 86748800..5a28c7d5 100644
--- a/CITATION.cff
+++ b/CITATION.cff
@@ -9,4 +9,4 @@ authors:
title: "FreeMoCap: A free, open source markerless motion capture system"
-version: 0.0.52
+version: 0.0.54
diff --git a/Dockerfile b/Dockerfile
deleted file mode 100644
index 71de937b..00000000
--- a/Dockerfile
+++ /dev/null
@@ -1,46 +0,0 @@
-# syntax=docker/dockerfile:1.2
-
-# Good base image to start from for most development
-FROM python:3.8-slim
-
-# Please remember, the base image we use /must be as small as possible/ for the best
-# production deployments. This is not optional.
-
-WORKDIR /workspace
-
-# Allows python to stream logs rather than buffer them for output.
-ENV PYTHONUNBUFFERED=1
-
-# The official Debian/Ubuntu Docker Image automatically removes the cache by default!
-# Removing the docker-clean file manages that issue.
-RUN rm -rf /etc/apt/apt.conf.d/docker-clean
-
-COPY ./bin/builds/ .
-
-# Apt-get install packages here since we're using Debian as a root OS for this particular Dockerfile.
-RUN --mount=type=cache,target=/var/cache/apt ./install_packages \
- dumb-init \
- tk \
- libgl1-mesa-glx \
- libglib2.0-0 \
- imagemagick
-
-
-# Install pip packages
-ENV PATH=/root/.local/bin:$PATH
-COPY requirements.txt .
-RUN --mount=type=cache,target=/root/.cache pip install --upgrade pip \
- && pip install -r requirements.txt
-
-# Switch to non-root user
-RUN useradd -m appuser && chown -R appuser /workspace
-USER appuser
-
-# Copy project files
-COPY src/api ./api
-COPY freemocap ./freemocap
-COPY ./bin ./bin
-COPY ./src ./src
-
-ENTRYPOINT ["/usr/bin/dumb-init", "--"]
-CMD ["./bin/run_web_server.sh"]
diff --git a/README.rst b/README.rst
deleted file mode 100644
index 04fd79c3..00000000
--- a/README.rst
+++ /dev/null
@@ -1,20 +0,0 @@
-=================
-Your Project Name
-=================
-
-.. image:: https://img.shields.io/travis//your-project-name.svg
- :target: https://travis-ci.org//your-project-name
-
-.. image:: https://img.shields.io/pypi/v/your-project-name.svg
- :target: https://pypi.python.org/pypi/your-project-name
-
-
-Python package for doing science.
-
-* Free software: Affero GNU Public Licence (AGPLv3)
-* Documentation: (COMING SOON!) https://.github.io/your-project-name.
-
-Features
---------
-
-* TODO
diff --git a/charuco_board_image.png b/assets/charuco/charuco_board_image.png
similarity index 100%
rename from charuco_board_image.png
rename to assets/charuco/charuco_board_image.png
diff --git a/charuco_board_image_highRes.png b/assets/charuco/charuco_board_image_highRes.png
similarity index 100%
rename from charuco_board_image_highRes.png
rename to assets/charuco/charuco_board_image_highRes.png
diff --git a/docker-compose.yml b/docker-compose.yml
deleted file mode 100644
index 81e5f95a..00000000
--- a/docker-compose.yml
+++ /dev/null
@@ -1,21 +0,0 @@
-version: "3.8"
-
-services:
- app:
- build:
- context: .
- dockerfile: Dockerfile
- ports:
- - "57000:8080"
- command:
- - "./bin/run_uvicorn_server.sh"
- volumes:
- - .:/workspace
-
- db:
- image: postgres:14-alpine
- ports:
- - "5432:5432"
- environment:
- POSTGRES_USER: postgres
- POSTGRES_PASSWORD: password
diff --git a/freemocap/__init__.py b/freemocap/__init__.py
deleted file mode 100644
index 55932fa6..00000000
--- a/freemocap/__init__.py
+++ /dev/null
@@ -1,45 +0,0 @@
-# from ._version import get_versions
-
-# __version__ = get_versions()["version"]
-# del get_versions
-
-from freemocap.fmc_runme import RunMe
-from freemocap import fmc_demo, fmc_runme
-
-# from freemocap import fmc_runme, fmc_demo #JSM NOTE - there's gotta be a better way to do this lol
-
-# def RunMe(sessionID=None,
-# stage=1,
-# useOpenPose=True,
-# openPoseDummyRun=False,
-# useMediaPipe=False,
-# useDLC=False,
-# dlcConfigPath=None,
-# debug=False,
-# setDataPath=False,
-# userDataPath = None,
-# recordVid=False,
-# reconstructionConfidenceThreshold = .8,
-# charucoSquareSize = 36,
-# ):
-# """
-# Passes user-set values from the freemocap_runme_script to the fmc_runme.Run function (and allows the user to run the pipeline with just an fmc.RunMe command)
-# """
-# fmc_runme.Run(sessionID,
-# stage,
-# useOpenPose,
-# openPoseDummyRun,
-# useMediaPipe,
-# useDLC,
-# dlcConfigPath,
-# debug,
-# setDataPath,
-# userDataPath,
-# recordVid)
-
-def RunDemo():
- """
- Will (eventually) download sample data from Figshare, and run the animation for it
- """
- sample_data_location, sample_data_name = fmc_demo.DemoSetup() #run a bunch of GUIs, get the location of the directory where the data folder with the sample data is
- #fmc_runme.RunMe(sessionID = sample_data_name,stage = 5,useOpenPose = False, useMediaPipe = True,useDLC = True, userDataPath = sample_data_location)
\ No newline at end of file
diff --git a/freemocap/_version.py b/freemocap/_version.py
deleted file mode 100644
index 3398cacf..00000000
--- a/freemocap/_version.py
+++ /dev/null
@@ -1,556 +0,0 @@
-# This file helps to compute a version number in source trees obtained from
-# git-archive tarball (such as those provided by githubs download-from-tag
-# feature). Distribution tarballs (built by setup.py sdist) and build
-# directories (produced by setup.py build) will contain a much shorter file
-# that just contains the computed version number.
-
-# This file is released into the public domain. Generated by
-# versioneer-0.18 (https://github.com/warner/python-versioneer)
-
-"""Git implementation of _version.py."""
-
-import errno
-import os
-import re
-import subprocess
-import sys
-
-
-def get_keywords():
- """Get the keywords needed to look up the version information."""
- # these strings will be replaced by git during git-archive.
- # setup.py/versioneer.py will grep for the variable names, so they must
- # each be defined on a line of their own. _version.py will just call
- # get_keywords().
- git_refnames = "$Format:%d$"
- git_full = "$Format:%H$"
- git_date = "$Format:%ci$"
- keywords = {"refnames": git_refnames, "full": git_full, "date": git_date}
- return keywords
-
-
-class VersioneerConfig:
- """Container for Versioneer configuration parameters."""
-
-
-def get_config():
- """Create, populate and return the VersioneerConfig() object."""
- # these strings are filled in when 'setup.py versioneer' creates
- # _version.py
- cfg = VersioneerConfig()
- cfg.VCS = "git"
- cfg.style = "pep440-post"
- cfg.tag_prefix = "v"
- cfg.parentdir_prefix = "None"
- cfg.versionfile_source = "freemocap/_version.py"
- cfg.verbose = False
- return cfg
-
-
-class NotThisMethod(Exception):
- """Exception raised if a method is not valid for the current scenario."""
-
-
-LONG_VERSION_PY = {}
-HANDLERS = {}
-
-
-def register_vcs_handler(vcs, method): # decorator
- """Decorator to mark a method as the handler for a particular VCS."""
-
- def decorate(f):
- """Store f in HANDLERS[vcs][method]."""
- if vcs not in HANDLERS:
- HANDLERS[vcs] = {}
- HANDLERS[vcs][method] = f
- return f
-
- return decorate
-
-
-def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False, env=None):
- """Call the given command(s)."""
- assert isinstance(commands, list)
- p = None
- for c in commands:
- try:
- dispcmd = str([c] + args)
- # remember shell=False, so use git.cmd on windows, not just git
- p = subprocess.Popen(
- [c] + args,
- cwd=cwd,
- env=env,
- stdout=subprocess.PIPE,
- stderr=(subprocess.PIPE if hide_stderr else None),
- )
- break
- except EnvironmentError:
- e = sys.exc_info()[1]
- if e.errno == errno.ENOENT:
- continue
- if verbose:
- print("unable to run %s" % dispcmd)
- print(e)
- return None, None
- else:
- if verbose:
- print("unable to find command, tried %s" % (commands,))
- return None, None
- stdout = p.communicate()[0].strip()
- if sys.version_info[0] >= 3:
- stdout = stdout.decode()
- if p.returncode != 0:
- if verbose:
- print("unable to run %s (error)" % dispcmd)
- print("stdout was %s" % stdout)
- return None, p.returncode
- return stdout, p.returncode
-
-
-def versions_from_parentdir(parentdir_prefix, root, verbose):
- """Try to determine the version from the parent directory name.
-
- Source tarballs conventionally unpack into a directory that includes both
- the project name and a version string. We will also support searching up
- two directory levels for an appropriately named parent directory
- """
- rootdirs = []
-
- for i in range(3):
- dirname = os.path.basename(root)
- if dirname.startswith(parentdir_prefix):
- return {
- "version": dirname[len(parentdir_prefix) :],
- "full-revisionid": None,
- "dirty": False,
- "error": None,
- "date": None,
- }
- else:
- rootdirs.append(root)
- root = os.path.dirname(root) # up a level
-
- if verbose:
- print(
- "Tried directories %s but none started with prefix %s"
- % (str(rootdirs), parentdir_prefix)
- )
- raise NotThisMethod("rootdir doesn't start with parentdir_prefix")
-
-
-@register_vcs_handler("git", "get_keywords")
-def git_get_keywords(versionfile_abs):
- """Extract version information from the given file."""
- # the code embedded in _version.py can just fetch the value of these
- # keywords. When used from setup.py, we don't want to import _version.py,
- # so we do it with a regexp instead. This function is not used from
- # _version.py.
- keywords = {}
- try:
- f = open(versionfile_abs, "r")
- for line in f.readlines():
- if line.strip().startswith("git_refnames ="):
- mo = re.search(r'=\s*"(.*)"', line)
- if mo:
- keywords["refnames"] = mo.group(1)
- if line.strip().startswith("git_full ="):
- mo = re.search(r'=\s*"(.*)"', line)
- if mo:
- keywords["full"] = mo.group(1)
- if line.strip().startswith("git_date ="):
- mo = re.search(r'=\s*"(.*)"', line)
- if mo:
- keywords["date"] = mo.group(1)
- f.close()
- except EnvironmentError:
- pass
- return keywords
-
-
-@register_vcs_handler("git", "keywords")
-def git_versions_from_keywords(keywords, tag_prefix, verbose):
- """Get version information from git keywords."""
- if not keywords:
- raise NotThisMethod("no keywords at all, weird")
- date = keywords.get("date")
- if date is not None:
- # git-2.2.0 added "%cI", which expands to an ISO-8601 -compliant
- # datestamp. However we prefer "%ci" (which expands to an "ISO-8601
- # -like" string, which we must then edit to make compliant), because
- # it's been around since git-1.5.3, and it's too difficult to
- # discover which version we're using, or to work around using an
- # older one.
- date = date.strip().replace(" ", "T", 1).replace(" ", "", 1)
- refnames = keywords["refnames"].strip()
- if refnames.startswith("$Format"):
- if verbose:
- print("keywords are unexpanded, not using")
- raise NotThisMethod("unexpanded keywords, not a git-archive tarball")
- refs = set([r.strip() for r in refnames.strip("()").split(",")])
- # starting in git-1.8.3, tags are listed as "tag: foo-1.0" instead of
- # just "foo-1.0". If we see a "tag: " prefix, prefer those.
- TAG = "tag: "
- tags = set([r[len(TAG) :] for r in refs if r.startswith(TAG)])
- if not tags:
- # Either we're using git < 1.8.3, or there really are no tags. We use
- # a heuristic: assume all version tags have a digit. The old git %d
- # expansion behaves like git log --decorate=short and strips out the
- # refs/heads/ and refs/tags/ prefixes that would let us distinguish
- # between branches and tags. By ignoring refnames without digits, we
- # filter out many common branch names like "release" and
- # "stabilization", as well as "HEAD" and "master".
- tags = set([r for r in refs if re.search(r"\d", r)])
- if verbose:
- print("discarding '%s', no digits" % ",".join(refs - tags))
- if verbose:
- print("likely tags: %s" % ",".join(sorted(tags)))
- for ref in sorted(tags):
- # sorting will prefer e.g. "2.0" over "2.0rc1"
- if ref.startswith(tag_prefix):
- r = ref[len(tag_prefix) :]
- if verbose:
- print("picking %s" % r)
- return {
- "version": r,
- "full-revisionid": keywords["full"].strip(),
- "dirty": False,
- "error": None,
- "date": date,
- }
- # no suitable tags, so version is "0+unknown", but full hex is still there
- if verbose:
- print("no suitable tags, using unknown + full revision id")
- return {
- "version": "0+unknown",
- "full-revisionid": keywords["full"].strip(),
- "dirty": False,
- "error": "no suitable tags",
- "date": None,
- }
-
-
-@register_vcs_handler("git", "pieces_from_vcs")
-def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command):
- """Get version from 'git describe' in the root of the source tree.
-
- This only gets called if the git-archive 'subst' keywords were *not*
- expanded, and _version.py hasn't already been rewritten with a short
- version string, meaning we're inside a checked out source tree.
- """
- GITS = ["git"]
- if sys.platform == "win32":
- GITS = ["git.cmd", "git.exe"]
-
- out, rc = run_command(GITS, ["rev-parse", "--git-dir"], cwd=root, hide_stderr=True)
- if rc != 0:
- if verbose:
- print("Directory %s not under git control" % root)
- raise NotThisMethod("'git rev-parse --git-dir' returned error")
-
- # if there is a tag matching tag_prefix, this yields TAG-NUM-gHEX[-dirty]
- # if there isn't one, this yields HEX[-dirty] (no NUM)
- describe_out, rc = run_command(
- GITS,
- [
- "describe",
- "--tags",
- "--dirty",
- "--always",
- "--long",
- "--match",
- "%s*" % tag_prefix,
- ],
- cwd=root,
- )
- # --long was added in git-1.5.5
- if describe_out is None:
- raise NotThisMethod("'git describe' failed")
- describe_out = describe_out.strip()
- full_out, rc = run_command(GITS, ["rev-parse", "HEAD"], cwd=root)
- if full_out is None:
- raise NotThisMethod("'git rev-parse' failed")
- full_out = full_out.strip()
-
- pieces = {}
- pieces["long"] = full_out
- pieces["short"] = full_out[:7] # maybe improved later
- pieces["error"] = None
-
- # parse describe_out. It will be like TAG-NUM-gHEX[-dirty] or HEX[-dirty]
- # TAG might have hyphens.
- git_describe = describe_out
-
- # look for -dirty suffix
- dirty = git_describe.endswith("-dirty")
- pieces["dirty"] = dirty
- if dirty:
- git_describe = git_describe[: git_describe.rindex("-dirty")]
-
- # now we have TAG-NUM-gHEX or HEX
-
- if "-" in git_describe:
- # TAG-NUM-gHEX
- mo = re.search(r"^(.+)-(\d+)-g([0-9a-f]+)$", git_describe)
- if not mo:
- # unparseable. Maybe git-describe is misbehaving?
- pieces["error"] = "unable to parse git-describe output: '%s'" % describe_out
- return pieces
-
- # tag
- full_tag = mo.group(1)
- if not full_tag.startswith(tag_prefix):
- if verbose:
- fmt = "tag '%s' doesn't start with prefix '%s'"
- print(fmt % (full_tag, tag_prefix))
- pieces["error"] = "tag '%s' doesn't start with prefix '%s'" % (
- full_tag,
- tag_prefix,
- )
- return pieces
- pieces["closest-tag"] = full_tag[len(tag_prefix) :]
-
- # distance: number of commits since tag
- pieces["distance"] = int(mo.group(2))
-
- # commit: short hex revision ID
- pieces["short"] = mo.group(3)
-
- else:
- # HEX: no tags
- pieces["closest-tag"] = None
- count_out, rc = run_command(GITS, ["rev-list", "HEAD", "--count"], cwd=root)
- pieces["distance"] = int(count_out) # total number of commits
-
- # commit date: see ISO-8601 comment in git_versions_from_keywords()
- date = run_command(GITS, ["show", "-s", "--format=%ci", "HEAD"], cwd=root)[
- 0
- ].strip()
- pieces["date"] = date.strip().replace(" ", "T", 1).replace(" ", "", 1)
-
- return pieces
-
-
-def plus_or_dot(pieces):
- """Return a + if we don't already have one, else return a ."""
- if "+" in pieces.get("closest-tag", ""):
- return "."
- return "+"
-
-
-def render_pep440(pieces):
- """Build up version string, with post-release "local version identifier".
-
- Our goal: TAG[+DISTANCE.gHEX[.dirty]] . Note that if you
- get a tagged build and then dirty it, you'll get TAG+0.gHEX.dirty
-
- Exceptions:
- 1: no tags. git_describe was just HEX. 0+untagged.DISTANCE.gHEX[.dirty]
- """
- if pieces["closest-tag"]:
- rendered = pieces["closest-tag"]
- if pieces["distance"] or pieces["dirty"]:
- rendered += plus_or_dot(pieces)
- rendered += "%d.g%s" % (pieces["distance"], pieces["short"])
- if pieces["dirty"]:
- rendered += ".dirty"
- else:
- # exception #1
- rendered = "0+untagged.%d.g%s" % (pieces["distance"], pieces["short"])
- if pieces["dirty"]:
- rendered += ".dirty"
- return rendered
-
-
-def render_pep440_pre(pieces):
- """TAG[.post.devDISTANCE] -- No -dirty.
-
- Exceptions:
- 1: no tags. 0.post.devDISTANCE
- """
- if pieces["closest-tag"]:
- rendered = pieces["closest-tag"]
- if pieces["distance"]:
- rendered += ".post.dev%d" % pieces["distance"]
- else:
- # exception #1
- rendered = "0.post.dev%d" % pieces["distance"]
- return rendered
-
-
-def render_pep440_post(pieces):
- """TAG[.postDISTANCE[.dev0]+gHEX] .
-
- The ".dev0" means dirty. Note that .dev0 sorts backwards
- (a dirty tree will appear "older" than the corresponding clean one),
- but you shouldn't be releasing software with -dirty anyways.
-
- Exceptions:
- 1: no tags. 0.postDISTANCE[.dev0]
- """
- if pieces["closest-tag"]:
- rendered = pieces["closest-tag"]
- if pieces["distance"] or pieces["dirty"]:
- rendered += ".post%d" % pieces["distance"]
- if pieces["dirty"]:
- rendered += ".dev0"
- rendered += plus_or_dot(pieces)
- rendered += "g%s" % pieces["short"]
- else:
- # exception #1
- rendered = "0.post%d" % pieces["distance"]
- if pieces["dirty"]:
- rendered += ".dev0"
- rendered += "+g%s" % pieces["short"]
- return rendered
-
-
-def render_pep440_old(pieces):
- """TAG[.postDISTANCE[.dev0]] .
-
- The ".dev0" means dirty.
-
- Eexceptions:
- 1: no tags. 0.postDISTANCE[.dev0]
- """
- if pieces["closest-tag"]:
- rendered = pieces["closest-tag"]
- if pieces["distance"] or pieces["dirty"]:
- rendered += ".post%d" % pieces["distance"]
- if pieces["dirty"]:
- rendered += ".dev0"
- else:
- # exception #1
- rendered = "0.post%d" % pieces["distance"]
- if pieces["dirty"]:
- rendered += ".dev0"
- return rendered
-
-
-def render_git_describe(pieces):
- """TAG[-DISTANCE-gHEX][-dirty].
-
- Like 'git describe --tags --dirty --always'.
-
- Exceptions:
- 1: no tags. HEX[-dirty] (note: no 'g' prefix)
- """
- if pieces["closest-tag"]:
- rendered = pieces["closest-tag"]
- if pieces["distance"]:
- rendered += "-%d-g%s" % (pieces["distance"], pieces["short"])
- else:
- # exception #1
- rendered = pieces["short"]
- if pieces["dirty"]:
- rendered += "-dirty"
- return rendered
-
-
-def render_git_describe_long(pieces):
- """TAG-DISTANCE-gHEX[-dirty].
-
- Like 'git describe --tags --dirty --always -long'.
- The distance/hash is unconditional.
-
- Exceptions:
- 1: no tags. HEX[-dirty] (note: no 'g' prefix)
- """
- if pieces["closest-tag"]:
- rendered = pieces["closest-tag"]
- rendered += "-%d-g%s" % (pieces["distance"], pieces["short"])
- else:
- # exception #1
- rendered = pieces["short"]
- if pieces["dirty"]:
- rendered += "-dirty"
- return rendered
-
-
-def render(pieces, style):
- """Render the given version pieces into the requested style."""
- if pieces["error"]:
- return {
- "version": "unknown",
- "full-revisionid": pieces.get("long"),
- "dirty": None,
- "error": pieces["error"],
- "date": None,
- }
-
- if not style or style == "default":
- style = "pep440" # the default
-
- if style == "pep440":
- rendered = render_pep440(pieces)
- elif style == "pep440-pre":
- rendered = render_pep440_pre(pieces)
- elif style == "pep440-post":
- rendered = render_pep440_post(pieces)
- elif style == "pep440-old":
- rendered = render_pep440_old(pieces)
- elif style == "git-describe":
- rendered = render_git_describe(pieces)
- elif style == "git-describe-long":
- rendered = render_git_describe_long(pieces)
- else:
- raise ValueError("unknown style '%s'" % style)
-
- return {
- "version": rendered,
- "full-revisionid": pieces["long"],
- "dirty": pieces["dirty"],
- "error": None,
- "date": pieces.get("date"),
- }
-
-
-def get_versions():
- """Get version information or return default if unable to do so."""
- # I am in _version.py, which lives at ROOT/VERSIONFILE_SOURCE. If we have
- # __file__, we can work backwards from there to the root. Some
- # py2exe/bbfreeze/non-CPython implementations don't do __file__, in which
- # case we can only use expanded keywords.
-
- cfg = get_config()
- verbose = cfg.verbose
-
- try:
- return git_versions_from_keywords(get_keywords(), cfg.tag_prefix, verbose)
- except NotThisMethod:
- pass
-
- try:
- root = os.path.realpath(__file__)
- # versionfile_source is the relative path from the top of the source
- # tree (where the .git directory might live) to this file. Invert
- # this to find the root from __file__.
- for i in cfg.versionfile_source.split("/"):
- root = os.path.dirname(root)
- except NameError:
- return {
- "version": "0+unknown",
- "full-revisionid": None,
- "dirty": None,
- "error": "unable to find root of source tree",
- "date": None,
- }
-
- try:
- pieces = git_pieces_from_vcs(cfg.tag_prefix, root, verbose)
- return render(pieces, cfg.style)
- except NotThisMethod:
- pass
-
- try:
- if cfg.parentdir_prefix:
- return versions_from_parentdir(cfg.parentdir_prefix, root, verbose)
- except NotThisMethod:
- pass
-
- return {
- "version": "0+unknown",
- "full-revisionid": None,
- "dirty": None,
- "error": "unable to compute version",
- "date": None,
- }
diff --git a/freemocap/analysis/balls_scratchpad.py b/freemocap/analysis/balls_scratchpad.py
deleted file mode 100644
index 54b75f83..00000000
--- a/freemocap/analysis/balls_scratchpad.py
+++ /dev/null
@@ -1,108 +0,0 @@
-#%% lol
-import numpy as np
-
-import matplotlib.pyplot as plt
-import mpl_toolkits.mplot3d.axes3d as p3
-import matplotlib.animation as animation
-from matplotlib.widgets import Slider
-import cv2
-
-import copy
-from pathlib import Path
-
-#RICH CONSOLE STUFF
-from rich import pretty
-pretty.install() #makes all print statement output pretty
-from rich import inspect
-from rich.console import Console
-console = Console()
-from rich.traceback import install as rich_traceback_install
-from rich.markdown import Markdown
-
-# %% load dlc data
-
-dlcDataPath = Path(r"C:\Users\jonma\Dropbox\GitKrakenRepos\freemocap - Copy\Data\sesh_21-07-20_165209\DataArrays\deepLabCut_3d.npy")
-openPoseDataPath = Path(r"C:\Users\jonma\Dropbox\GitKrakenRepos\freemocap - Copy\Data\sesh_21-07-20_165209\DataArrays\openPoseSkel_3d.npy")
-
-dlc_fr_mar_xyz = np.load(dlcDataPath)
-dlc_trajectories = [dlc_fr_mar_xyz[:,markerNum,:] for markerNum in range(dlc_fr_mar_xyz.shape[1])]
-
-skel_fr_mar_xyz = np.load(openPoseDataPath)
-skel_trajectories = [skel_fr_mar_xyz[:,markerNum,:] for markerNum in range(skel_fr_mar_xyz.shape[1])]
-
-# %% hand/ball vs time
-fig1 = plt.figure()
-axX = fig1.add_subplot(2,1,1)
-# axX.plot(dlc_trajectories[0][:,0], 'purple',linewidth=2)
-axX.plot(dlc_trajectories[1][:,0], 'orange',linewidth=2)
-
-axX.plot(skel_trajectories[4][:,0], 'red',linewidth=2)
-axX.plot(skel_trajectories[7][:,0], 'blue',linewidth=2)
-axX.set_title('X')
-xlim = [300, 500]
-
-axX.set_xlim(xlim)
-axX.set_ylim([-300, 300])
-
-axY = fig1.add_subplot(2,1,2)
-# axY.plot(-dlc_trajectories[0][:,1], 'purple',linewidth=2)
-axY.plot(-dlc_trajectories[1][:,1], 'orange',linewidth=2)
-
-axY.plot(-skel_trajectories[4][:,1], 'red',linewidth=2)
-axY.plot(-skel_trajectories[7][:,1], 'blue',linewidth=2)
-axY.set_title('Y')
-axY.set_xlim(xlim)
-axY.set_ylim([-200, 500])
-
-# axY = fig1.add_subplot(3,1,3)
-# axY.plot(dlc_trajectories[0][:,2], 'purple',linewidth=2)
-# axY.plot(skel_trajectories[4][:,2], 'red',linewidth=2)
-# axY.set_title('Z')
-# %% hand ball planar projections
-
-fig2 = plt.figure()
-axPlanar = fig2.add_subplot( )
-frRange = np.arange(xlim[0], xlim[1], 1)
-
-ballX = -dlc_trajectories[0][frRange,0]
-ballY = -dlc_trajectories[0][frRange,1]
-
-rHandX = -skel_trajectories[4][frRange,0]
-rHandY = -skel_trajectories[4][frRange,1]
-
-lHandX = -skel_trajectories[7][frRange,0]
-lHandY = -skel_trajectories[7][frRange,1]
-
-axPlanar.plot(ballX, ballY, 'purple',linewidth=2)
-axPlanar.plot(rHandX, rHandY, 'red',linewidth=2)
-axPlanar.plot(lHandX, lHandY, 'blue',linewidth=2)
-
-#%% hand vs ball?
-
-fig3 = plt.figure()
-axPhase = fig3.add_subplot( )
-frRange = np.arange(xlim[0], xlim[0]+300, 1)
-ballX = -dlc_trajectories[0][frRange,0]
-ballY = -dlc_trajectories[0][frRange,1]
-
-rHandX = -skel_trajectories[4][frRange,0]
-rHandY = -skel_trajectories[4][frRange,1]
-
-lHandX = -skel_trajectories[7][frRange,0]
-lHandY = -skel_trajectories[7][frRange,1]
-
-
-rHandXvBallX = rHandX - ballX
-rHandYvBallY = rHandY - ballY
-
-lHandXvBallX = lHandX - ballX
-lHandYvBallY = lHandY - ballY
-
-# axPhase.plot(ballX, rHandX, 'purple',linewidth=2)
-# axPhase.plot(ballY, rHandY, 'red',linewidth=2)
-axPhase.plot(rHandXvBallX, rHandYvBallY, 'red',linewidth=2)
-axPhase.plot(lHandXvBallX, lHandYvBallY, 'blue',linewidth=2)
-# axPhase.plot(ballY, lHandY, 'forestgreen',linewidth=2)
-
-#%%
-# %%
diff --git a/freemocap/analysis/convert_npy_datafiles_to_pandas_dataframe.py b/freemocap/analysis/convert_npy_datafiles_to_pandas_dataframe.py
deleted file mode 100644
index 9e37b4eb..00000000
--- a/freemocap/analysis/convert_npy_datafiles_to_pandas_dataframe.py
+++ /dev/null
@@ -1,9 +0,0 @@
-#%%
-import numpy as np
-import pandas as pd
-from pathlib import Path
-from ruamel.yaml import YAML
-yaml = YAML()
-#%%
-path_to_session_congfig = Path("C:\Users\jonma\Dropbox\FreeMoCapProject\FreeMocap_Data\sesh_2021-09-14_10_22_15\sesh_2021-09-14_10_22_15_config.yaml")
-configList = yaml.load(configFile, Loader=yaml.FullLoader)
\ No newline at end of file
diff --git a/freemocap/analysis/skel_analisys.ipynb b/freemocap/analysis/skel_analisys.ipynb
deleted file mode 100644
index de77733d..00000000
--- a/freemocap/analysis/skel_analisys.ipynb
+++ /dev/null
@@ -1 +0,0 @@
-{"cells":[{"cell_type":"code","execution_count":1,"source":["%matplotlib WX\r\n"],"outputs":[{"output_type":"error","ename":"ValueError","evalue":"Key backend: Unrecognized backend string 'gtkagg': valid strings are ['GTK3Agg', 'GTK3Cairo', 'MacOSX', 'nbAgg', 'Qt4Agg', 'Qt4Cairo', 'Qt5Agg', 'Qt5Cairo', 'TkAgg', 'TkCairo', 'WebAgg', 'WX', 'WXAgg', 'WXCairo', 'agg', 'cairo', 'pdf', 'pgf', 'ps', 'svg', 'template']","traceback":["\u001b[1;31m---------------------------------------------------------------------------\u001b[0m","\u001b[1;31mValueError\u001b[0m Traceback (most recent call last)","\u001b[1;32m~\\anaconda3\\envs\\freemocap-env\\lib\\site-packages\\matplotlib\\__init__.py\u001b[0m in \u001b[0;36m__setitem__\u001b[1;34m(self, key, val)\u001b[0m\n\u001b[0;32m 801\u001b[0m \u001b[1;32mtry\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m--> 802\u001b[1;33m \u001b[0mcval\u001b[0m \u001b[1;33m=\u001b[0m \u001b[0mself\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mvalidate\u001b[0m\u001b[1;33m[\u001b[0m\u001b[0mkey\u001b[0m\u001b[1;33m]\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mval\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m\u001b[0;32m 803\u001b[0m \u001b[1;32mexcept\u001b[0m \u001b[0mValueError\u001b[0m \u001b[1;32mas\u001b[0m \u001b[0mve\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n","\u001b[1;32m~\\anaconda3\\envs\\freemocap-env\\lib\\site-packages\\matplotlib\\rcsetup.py\u001b[0m in \u001b[0;36mvalidate_backend\u001b[1;34m(s)\u001b[0m\n\u001b[0;32m 265\u001b[0m \u001b[0ms\u001b[0m \u001b[1;32mif\u001b[0m \u001b[0ms\u001b[0m \u001b[1;32mis\u001b[0m \u001b[0m_auto_backend_sentinel\u001b[0m \u001b[1;32mor\u001b[0m \u001b[0ms\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mstartswith\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;34m\"module://\"\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m--> 266\u001b[1;33m else _validate_standard_backends(s))\n\u001b[0m\u001b[0;32m 267\u001b[0m \u001b[1;32mreturn\u001b[0m \u001b[0mbackend\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n","\u001b[1;32m~\\anaconda3\\envs\\freemocap-env\\lib\\site-packages\\matplotlib\\rcsetup.py\u001b[0m in \u001b[0;36m__call__\u001b[1;34m(self, s)\u001b[0m\n\u001b[0;32m 63\u001b[0m raise ValueError('Unrecognized %s string %r: valid strings are %s'\n\u001b[1;32m---> 64\u001b[1;33m % (self.key, s, list(self.valid.values())))\n\u001b[0m\u001b[0;32m 65\u001b[0m \u001b[1;33m\u001b[0m\u001b[0m\n","\u001b[1;31mValueError\u001b[0m: Unrecognized backend string 'gtkagg': valid strings are ['GTK3Agg', 'GTK3Cairo', 'MacOSX', 'nbAgg', 'Qt4Agg', 'Qt4Cairo', 'Qt5Agg', 'Qt5Cairo', 'TkAgg', 'TkCairo', 'WebAgg', 'WX', 'WXAgg', 'WXCairo', 'agg', 'cairo', 'pdf', 'pgf', 'ps', 'svg', 'template']","\nDuring handling of the above exception, another exception occurred:\n","\u001b[1;31mValueError\u001b[0m Traceback (most recent call last)","\u001b[1;32m~\\AppData\\Local\\Temp/ipykernel_2252/2305839510.py\u001b[0m in \u001b[0;36m<module>\u001b[1;34m\u001b[0m\n\u001b[1;32m----> 1\u001b[1;33m \u001b[0mget_ipython\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mrun_line_magic\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;34m'matplotlib'\u001b[0m\u001b[1;33m,\u001b[0m \u001b[1;34m'gtk'\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m","\u001b[1;32m~\\anaconda3\\envs\\freemocap-env\\lib\\site-packages\\IPython\\core\\interactiveshell.py\u001b[0m in \u001b[0;36mrun_line_magic\u001b[1;34m(self, magic_name, line, _stack_depth)\u001b[0m\n\u001b[0;32m 2346\u001b[0m \u001b[0mkwargs\u001b[0m\u001b[1;33m[\u001b[0m\u001b[1;34m'local_ns'\u001b[0m\u001b[1;33m]\u001b[0m \u001b[1;33m=\u001b[0m \u001b[0mself\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mget_local_scope\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mstack_depth\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m 2347\u001b[0m \u001b[1;32mwith\u001b[0m \u001b[0mself\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mbuiltin_trap\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m-> 2348\u001b[1;33m \u001b[0mresult\u001b[0m \u001b[1;33m=\u001b[0m \u001b[0mfn\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;33m*\u001b[0m\u001b[0margs\u001b[0m\u001b[1;33m,\u001b[0m \u001b[1;33m**\u001b[0m\u001b[0mkwargs\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m\u001b[0;32m 2349\u001b[0m \u001b[1;32mreturn\u001b[0m \u001b[0mresult\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m 2350\u001b[0m \u001b[1;33m\u001b[0m\u001b[0m\n","\u001b[1;32m~\\anaconda3\\envs\\freemocap-env\\lib\\site-packages\\decorator.py\u001b[0m in \u001b[0;36mfun\u001b[1;34m(*args, **kw)\u001b[0m\n\u001b[0;32m 230\u001b[0m \u001b[1;32mif\u001b[0m \u001b[1;32mnot\u001b[0m \u001b[0mkwsyntax\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m 231\u001b[0m \u001b[0margs\u001b[0m\u001b[1;33m,\u001b[0m \u001b[0mkw\u001b[0m \u001b[1;33m=\u001b[0m \u001b[0mfix\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0margs\u001b[0m\u001b[1;33m,\u001b[0m \u001b[0mkw\u001b[0m\u001b[1;33m,\u001b[0m \u001b[0msig\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m--> 232\u001b[1;33m \u001b[1;32mreturn\u001b[0m \u001b[0mcaller\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mfunc\u001b[0m\u001b[1;33m,\u001b[0m \u001b[1;33m*\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mextras\u001b[0m \u001b[1;33m+\u001b[0m \u001b[0margs\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m,\u001b[0m \u001b[1;33m**\u001b[0m\u001b[0mkw\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m\u001b[0;32m 233\u001b[0m \u001b[0mfun\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0m__name__\u001b[0m \u001b[1;33m=\u001b[0m \u001b[0mfunc\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0m__name__\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m 234\u001b[0m \u001b[0mfun\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0m__doc__\u001b[0m \u001b[1;33m=\u001b[0m \u001b[0mfunc\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0m__doc__\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n","\u001b[1;32m~\\anaconda3\\envs\\freemocap-env\\lib\\site-packages\\IPython\\core\\magic.py\u001b[0m in \u001b[0;36m<lambda>\u001b[1;34m(f, *a, **k)\u001b[0m\n\u001b[0;32m 185\u001b[0m \u001b[1;31m# but it's overkill for just that one bit of state.\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m 186\u001b[0m \u001b[1;32mdef\u001b[0m \u001b[0mmagic_deco\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0marg\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m--> 187\u001b[1;33m \u001b[0mcall\u001b[0m \u001b[1;33m=\u001b[0m \u001b[1;32mlambda\u001b[0m \u001b[0mf\u001b[0m\u001b[1;33m,\u001b[0m \u001b[1;33m*\u001b[0m\u001b[0ma\u001b[0m\u001b[1;33m,\u001b[0m \u001b[1;33m**\u001b[0m\u001b[0mk\u001b[0m\u001b[1;33m:\u001b[0m \u001b[0mf\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;33m*\u001b[0m\u001b[0ma\u001b[0m\u001b[1;33m,\u001b[0m \u001b[1;33m**\u001b[0m\u001b[0mk\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m\u001b[0;32m 188\u001b[0m \u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m 189\u001b[0m \u001b[1;32mif\u001b[0m \u001b[0mcallable\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0marg\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n","\u001b[1;32m~\\anaconda3\\envs\\freemocap-env\\lib\\site-packages\\IPython\\core\\magics\\pylab.py\u001b[0m in \u001b[0;36mmatplotlib\u001b[1;34m(self, line)\u001b[0m\n\u001b[0;32m 97\u001b[0m \u001b[0mprint\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;34m\"Available matplotlib backends: %s\"\u001b[0m \u001b[1;33m%\u001b[0m \u001b[0mbackends_list\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m 98\u001b[0m \u001b[1;32melse\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m---> 99\u001b[1;33m \u001b[0mgui\u001b[0m\u001b[1;33m,\u001b[0m \u001b[0mbackend\u001b[0m \u001b[1;33m=\u001b[0m \u001b[0mself\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mshell\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0menable_matplotlib\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0margs\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mgui\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mlower\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;33m)\u001b[0m \u001b[1;32mif\u001b[0m \u001b[0misinstance\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0margs\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mgui\u001b[0m\u001b[1;33m,\u001b[0m \u001b[0mstr\u001b[0m\u001b[1;33m)\u001b[0m \u001b[1;32melse\u001b[0m \u001b[0margs\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mgui\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m\u001b[0;32m 100\u001b[0m \u001b[0mself\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0m_show_matplotlib_backend\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0margs\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mgui\u001b[0m\u001b[1;33m,\u001b[0m \u001b[0mbackend\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m 101\u001b[0m \u001b[1;33m\u001b[0m\u001b[0m\n","\u001b[1;32m~\\anaconda3\\envs\\freemocap-env\\lib\\site-packages\\IPython\\core\\interactiveshell.py\u001b[0m in \u001b[0;36menable_matplotlib\u001b[1;34m(self, gui)\u001b[0m\n\u001b[0;32m 3528\u001b[0m \u001b[0mgui\u001b[0m\u001b[1;33m,\u001b[0m \u001b[0mbackend\u001b[0m \u001b[1;33m=\u001b[0m \u001b[0mpt\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mfind_gui_and_backend\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mself\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mpylab_gui_select\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m 3529\u001b[0m \u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m-> 3530\u001b[1;33m \u001b[0mpt\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mactivate_matplotlib\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mbackend\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m\u001b[0;32m 3531\u001b[0m \u001b[0mconfigure_inline_support\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mself\u001b[0m\u001b[1;33m,\u001b[0m \u001b[0mbackend\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m 3532\u001b[0m \u001b[1;33m\u001b[0m\u001b[0m\n","\u001b[1;32m~\\anaconda3\\envs\\freemocap-env\\lib\\site-packages\\IPython\\core\\pylabtools.py\u001b[0m in \u001b[0;36mactivate_matplotlib\u001b[1;34m(backend)\u001b[0m\n\u001b[0;32m 315\u001b[0m \u001b[1;31m# the rcParam to update. This needs to be set *before* the module\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m 316\u001b[0m \u001b[1;31m# magic of switch_backend().\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m--> 317\u001b[1;33m \u001b[0mmatplotlib\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mrcParams\u001b[0m\u001b[1;33m[\u001b[0m\u001b[1;34m'backend'\u001b[0m\u001b[1;33m]\u001b[0m \u001b[1;33m=\u001b[0m \u001b[0mbackend\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m\u001b[0;32m 318\u001b[0m \u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m 319\u001b[0m \u001b[1;31m# Due to circular imports, pyplot may be only partially initialised\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n","\u001b[1;32m~\\anaconda3\\envs\\freemocap-env\\lib\\site-packages\\matplotlib\\__init__.py\u001b[0m in \u001b[0;36m__setitem__\u001b[1;34m(self, key, val)\u001b[0m\n\u001b[0;32m 802\u001b[0m \u001b[0mcval\u001b[0m \u001b[1;33m=\u001b[0m \u001b[0mself\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mvalidate\u001b[0m\u001b[1;33m[\u001b[0m\u001b[0mkey\u001b[0m\u001b[1;33m]\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mval\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m 803\u001b[0m \u001b[1;32mexcept\u001b[0m \u001b[0mValueError\u001b[0m \u001b[1;32mas\u001b[0m \u001b[0mve\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m--> 804\u001b[1;33m \u001b[1;32mraise\u001b[0m \u001b[0mValueError\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;34m\"Key %s: %s\"\u001b[0m \u001b[1;33m%\u001b[0m \u001b[1;33m(\u001b[0m\u001b[0mkey\u001b[0m\u001b[1;33m,\u001b[0m \u001b[0mstr\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mve\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m\u001b[0;32m 805\u001b[0m \u001b[0mdict\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0m__setitem__\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mself\u001b[0m\u001b[1;33m,\u001b[0m \u001b[0mkey\u001b[0m\u001b[1;33m,\u001b[0m \u001b[0mcval\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m 806\u001b[0m \u001b[1;32mexcept\u001b[0m \u001b[0mKeyError\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n","\u001b[1;31mValueError\u001b[0m: Key backend: Unrecognized backend string 'gtkagg': valid strings are ['GTK3Agg', 'GTK3Cairo', 'MacOSX', 'nbAgg', 'Qt4Agg', 'Qt4Cairo', 'Qt5Agg', 'Qt5Cairo', 'TkAgg', 'TkCairo', 'WebAgg', 'WX', 'WXAgg', 'WXCairo', 'agg', 'cairo', 'pdf', 'pgf', 'ps', 'svg', 'template']"]}],"metadata":{}},{"cell_type":"code","execution_count":null,"source":["\r\n","\r\n","import numpy as np\r\n","\r\n","import matplotlib.pyplot as plt\r\n","import mpl_toolkits.mplot3d.axes3d as p3\r\n","import matplotlib.animation as animation\r\n","from matplotlib.widgets import Slider\r\n","import cv2 \r\n","\r\n","import copy\r\n","from pathlib import Path\r\n","\r\n","#RICH CONSOLE STUFF\r\n","from rich import pretty\r\n","pretty.install() #makes all print statement output pretty\r\n","from rich import inspect\r\n","from rich.console import Console\r\n","console = Console() \r\n","from rich.traceback import install as rich_traceback_install\r\n","from rich.markdown import Markdown\r\n"],"outputs":[],"metadata":{}},{"cell_type":"code","execution_count":null,"source":["\r\n","openPose3dDataPath = Path(r\"C:\\Users\\jonma\\Dropbox\\FreeMoCapProject\\FreeMocap_Data\\sesh_2021-09-07_09_09_56\\DataArrays\\openPoseSkel_3d.npy\")\r\n","openPose3dReprojPath = Path(r\"C:\\Users\\jonma\\Dropbox\\FreeMoCapProject\\FreeMocap_Data\\sesh_2021-09-07_09_09_56\\DataArrays\\openPoseSkel_reprojErr.npy\")\r\n","\r\n","mediaPipe3dDataPath = Path(r\"C:\\Users\\jonma\\Dropbox\\FreeMoCapProject\\FreeMocap_Data\\sesh_2021-09-07_09_09_56\\DataArrays\\mediaPipeSkel_3d.npy\")\r\n","mediaPipe3dReprojPath = Path(r\"C:\\Users\\jonma\\Dropbox\\FreeMoCapProject\\FreeMocap_Data\\sesh_2021-09-07_09_09_56\\DataArrays\\mediaPipeSkel_reprojErr.npy\")\r\n","\r\n","openPose2dDataPath = Path(r\"C:\\Users\\jonma\\Dropbox\\FreeMoCapProject\\FreeMocap_Data\\sesh_2021-09-07_09_09_56\\DataArrays\\openPoseData_2d.npy\")\r\n","\r\n","mediaPipe2dDataPath = Path(r\"C:\\Users\\jonma\\Dropbox\\FreeMoCapProject\\FreeMocap_Data\\sesh_2021-09-07_09_09_56\\DataArrays\\mediaPipe_2d.npy\")\r\n"],"outputs":[],"metadata":{}},{"cell_type":"code","execution_count":null,"source":["mediaPipe_nCams_nFrames_nImgPts_XYC = np.load(mediaPipe2dDataPath)\r\n","\r\n","mp_rToe_conf = mediaPipe_nCams_nFrames_nImgPts_XYC[:,:,32,2].transpose()\r\n","mp_nose_conf = mediaPipe_nCams_nFrames_nImgPts_XYC[:,:,0,2].transpose()\r\n","mediaPipe_ReProjErr= np.load(mediaPipe3dReprojPath)\r\n","\r\n","mediaPipe_meanReproj_fr = np.nanmean(mediaPipe_ReProjErr,0)"],"outputs":[],"metadata":{}},{"cell_type":"code","execution_count":null,"source":["openPose_nCams_nFrames_nImgPts_XYC = np.load(openPose2dDataPath)\r\n","\r\n","openPose_rToe_conf = openPose_nCams_nFrames_nImgPts_XYC[:,:,32,2].transpose()\r\n","openPose_nose_conf = openPose_nCams_nFrames_nImgPts_XYC[:,:,0,2].transpose()\r\n","\r\n","openPose_ReProjErr= np.load(openPose3dReprojPath)\r\n","openPose_meanReproj_fr = np.nanmean(openPose_ReProjErr,0)\r\n"],"outputs":[],"metadata":{}},{"cell_type":"code","execution_count":null,"source":["\r\n","camLabels = [\"Cam#{}\".format(str(camNum)) for camNum in range(mediaPipe_nCams_nFrames_nImgPts_XYC.shape[0])]\r\n","\r\n","fig1 = plt.figure()\r\n","axToe = fig1.add_subplot(1,3,1)\r\n","\r\n","axToe.plot(mp_rToe_conf, label='rToe')\r\n","axToe.set_xlabel('Time (frames)')\r\n","axToe.set_ylabel('Nose Confidence')\r\n","axToe.legend()\r\n","\r\n","axNose = fig1.add_subplot(1,3,2)\r\n","\r\n","axNose.plot(mp_nose_conf, label='Nose')\r\n","axNose.set_xlabel('Time (frames)')\r\n","axNose.set_ylabel('Nose Confidence')\r\n","axNose.legend()\r\n","\r\n","axSkelReProj = fig1.add_subplot(1,3,3)\r\n","\r\n","axSkelReProj.plot(mediaPipe_meanReproj_fr, label='ReprojErr')\r\n","axSkelReProj.set_xlabel('Time (frames)')\r\n","axSkelReProj.set_ylabel('Mean ReprojErr')\r\n","axSkelReProj.legend()\r\n","\r\n","plt.show()\r\n","plt.pause(.1)\r\n"],"outputs":[],"metadata":{}},{"cell_type":"code","execution_count":null,"source":["\r\n","\r\n","fig2 = plt.figure()\r\n","axToe = fig2.add_subplot(1,3,1)\r\n","\r\n","axToe.plot(openPose_rToe_conf, label='rToe')\r\n","axToe.set_xlabel('Time (frames)')\r\n","axToe.set_ylabel('Nose Confidence')\r\n","axToe.legend()\r\n","\r\n","axNose = fig2.add_subplot(1,3,2)\r\n","\r\n","axNose.plot(openPose_nose_conf, label='Nose')\r\n","axNose.set_xlabel('Time (frames)')\r\n","axNose.set_ylabel('Nose Confidence')\r\n","axNose.legend()\r\n","\r\n","axSkelReProj = fig2.add_subplot(1,3,3)\r\n","\r\n","axSkelReProj.plot(openPose_meanReproj_fr, label='ReprojErr')\r\n","axSkelReProj.set_xlabel('Time (frames)')\r\n","axSkelReProj.set_ylabel('Mean ReprojErr')\r\n","axSkelReProj.legend()\r\n","\r\n","plt.show()\r\n","plt.pause(.1)\r\n"],"outputs":[],"metadata":{}},{"cell_type":"code","execution_count":null,"source":[],"outputs":[],"metadata":{}},{"cell_type":"code","execution_count":null,"source":[],"outputs":[],"metadata":{}}],"nbformat":4,"nbformat_minor":2,"metadata":{"language_info":{"codemirror_mode":{"name":"ipython","version":3},"file_extension":".py","mimetype":"text/x-python","name":"python","nbconvert_exporter":"python","pygments_lexer":"ipython3","version":"3.7.10"},"orig_nbformat":4,"kernelspec":{"name":"python3","display_name":"Python 3.7.10 64-bit ('freemocap-env': conda)"},"interpreter":{"hash":"14003e192b7068b5c6f3e01a75a7e2fbf9024b2608b3367651f2fa04e27b22a0"}}}
\ No newline at end of file
diff --git a/freemocap/analysis/skel_analisys.py b/freemocap/analysis/skel_analisys.py
deleted file mode 100644
index a55bac7d..00000000
--- a/freemocap/analysis/skel_analisys.py
+++ /dev/null
@@ -1,75 +0,0 @@
-#%%
-%matplotlib
-
-import numpy as np
-
-import matplotlib.pyplot as plt
-import mpl_toolkits.mplot3d.axes3d as p3
-import matplotlib.animation as animation
-from matplotlib.widgets import Slider
-import cv2
-
-import copy
-from pathlib import Path
-
-#RICH CONSOLE STUFF
-from rich import pretty
-pretty.install() #makes all print statement output pretty
-from rich import inspect
-from rich.console import Console
-console = Console()
-from rich.traceback import install as rich_traceback_install
-from rich.markdown import Markdown
-
-# %% load dlc data
-
-openPose3dDataPath = Path(r"C:\Users\jonma\Dropbox\FreeMoCapProject\FreeMocap_Data\sesh_2021-09-07_09_09_56\DataArrays\openPoseSkel_3d.npy")
-
-mediaPipe3dDataPath = Path(r"C:\Users\jonma\Dropbox\FreeMoCapProject\FreeMocap_Data\sesh_2021-09-07_09_09_56\DataArrays\mediaPipeSkel_3d.npy")
-mediaPipe3dReprojPath = Path(r"C:\Users\jonma\Dropbox\FreeMoCapProject\FreeMocap_Data\sesh_2021-09-07_09_09_56\DataArrays\mediaPipeSkel_reprojErr.npy")
-
-openPose2dDataPath = Path(r"C:\Users\jonma\Dropbox\FreeMoCapProject\FreeMocap_Data\sesh_2021-09-07_09_09_56\DataArrays\openPoseData_2d.npy")
-
-mediaPipe2dDataPath = Path(r"C:\Users\jonma\Dropbox\FreeMoCapProject\FreeMocap_Data\sesh_2021-09-07_09_09_56\DataArrays\mediaPipe_2d.npy")
-
-#%% pull out 2d data
-mediaPipe_nCams_nFrames_nImgPts_XYC = np.load(mediaPipe2dDataPath)
-
-mp_rToe_conf = mediaPipe_nCams_nFrames_nImgPts_XYC[:,:,32,2].transpose()
-mp_nose_conf = mediaPipe_nCams_nFrames_nImgPts_XYC[:,:,0,2].transpose()
-
-#%% pull out 3d reproj error
-
-mediaPipe_ReProjErr= np.load(mediaPipe3dReprojPath)
-
-mediaPipe_meanReproj_fr = np.nanmean(mediaPipe_ReProjErr,0)
-
-
-# %% hand/ball vs time
-
-camLabels = ["Cam#{}".format(str(camNum)) for camNum in range(mediaPipe_nCams_nFrames_nImgPts_XYC.shape[0])]
-
-fig1 = plt.figure()
-axToe = fig1.add_subplot(1,3,1)
-
-axToe.plot(mp_rToe_conf, label='rToe')
-axToe.set_xlabel('Time (frames)')
-axToe.set_ylabel('Nose Confidence')
-axToe.legend()
-
-axNose = fig1.add_subplot(1,3,2)
-
-axNose.plot(mp_nose_conf, label='Nose')
-axNose.set_xlabel('Time (frames)')
-axNose.set_ylabel('Nose Confidence')
-axNose.legend()
-
-axSkelReProj = fig1.add_subplot(1,3,3)
-
-axSkelReProj.plot(mediaPipe_meanReproj_fr, label='ReprojErr')
-axSkelReProj.set_xlabel('Time (frames)')
-axSkelReProj.set_ylabel('Mean ReprojErr')
-axSkelReProj.legend()
-
-
-# %%
diff --git a/freemocap/build_data.npy b/freemocap/build_data.npy
deleted file mode 100644
index 5b00b0b3..00000000
Binary files a/freemocap/build_data.npy and /dev/null differ
diff --git a/freemocap/calibrate.py b/freemocap/calibrate.py
deleted file mode 100644
index d2607a38..00000000
--- a/freemocap/calibrate.py
+++ /dev/null
@@ -1,280 +0,0 @@
-import os
-import copy
-import json
-import pickle
-import glob
-from pathlib import Path
-
-from aniposelib.cameras import CameraGroup
-from aniposelib.utils import load_pose2d_fnames
-from numba.core.types.misc import StringLiteral
-import numpy as np
-import cv2
-
-import matplotlib.pyplot as plt
-from mpl_toolkits.mplot3d import Axes3D
-from freemocap import reconstruct3D, fmc_anipose
-from rich.progress import track
-from rich import print
-from rich.console import Console
-
-from scipy.spatial.transform import Rotation
-
-console = Console()
-
-def pin_camera_zero_to_origin(_anipose_camera_group_object):
- original_translation_vectors = _anipose_camera_group_object.get_translations()
- camera_0_translation = original_translation_vectors[0, :]
- altered_translation_vectors = np.zeros(original_translation_vectors.shape)
- for this_camera_number in range(original_translation_vectors.shape[0]):
- altered_translation_vectors[this_camera_number, :] = original_translation_vectors[this_camera_number,
- :] - camera_0_translation
-
- _anipose_camera_group_object.set_translations(altered_translation_vectors)
- print(f"original translation vectors: {original_translation_vectors}")
- print(f"altered translation vectors: {_anipose_camera_group_object.get_translations()}")
- return _anipose_camera_group_object
-
-def rotate_cameras_so_camera_zero_aligns_with_XYZ(_anipose_camera_group_object):
- original_rotations_euler = _anipose_camera_group_object.get_rotations()
- original_translation_vectors = _anipose_camera_group_object.get_translations()
- camera_rotation_matrix_list = [Rotation.from_euler('xyz',original_rotations_euler[this_cam_num,:]).as_matrix() for this_cam_num in range(original_rotations_euler.shape[0])]
-
- rotated_translation_vectors = [camera_rotation_matrix_list[0] @ this_tx for this_tx in original_translation_vectors]
- _anipose_camera_group_object.set_rotations(rotated_translation_vectors)
- return _anipose_camera_group_object
-
-def CalibrateCaptureVolume(session,board, calVideoFrameLength = 1):
- """
- Check if a previous calibration yaml exists, and if not, create a set of shortened calibration videos and run Anipose functions
- to create a calibration yaml. Takes the 2D charuco board points and reconstructs them into 3D points that are saved out
- into the DataArrays folder
-
- note `debugAniposeIter` spoofs a failed anipose calibration to make it easier to test the thing where we iterate through with different frame windows to try to find one that works
- """
-
- session.calVidPath.mkdir(exist_ok = True)
- session.dataArrayPath.mkdir(exist_ok = True)
- calibrationVideoPath = session.calVidPath
-
-
-
- if session.use_saved_calibration:
- saved_calibration_folder = session.freemocap_module_path/'fmc_calibration'
- #saved_calibration_file_name = os.listdir(saved_calibration_folder)[0]
- #saved_calibration_file_path = os.path.join(saved_calibration_folder, saved_calibration_file_name)
- #saved_calibration_file_path = list(Path(saved_calibration_folder).glob('*.toml'))
- saved_calibration_file_path = saved_calibration_folder/'previous_calibration.toml'
-
-
- cam_names = [i+1 for i in range(session.numCams)]
- cgroup = fmc_anipose.CameraGroup.from_names( cam_names, fisheye=True)
-
-
- cgroup = CameraGroup.load(saved_calibration_file_path)
- charuco_nCams_nFrames_nImgPts_XY = np.load(saved_calibration_folder/'charuco_2d_points.npy')
-
- session.cameraCalFilePath = session.sessionPath /"{}_calibration.toml".format(session.sessionID)
- cgroup.dump(session.cameraCalFilePath)
-
- session.cgroup = cgroup
-
- camera_calibration_info_dict = cgroup.get_dicts()
- camera_calibration_pickle_path = session.sessionPath / "{}_calibration.pickle".format(session.sessionID)
-
- with open(str(camera_calibration_pickle_path), 'wb') as pickle_file:
- pickle.dump(camera_calibration_info_dict, pickle_file)
-
- else:
-
- if type(calVideoFrameLength)==int or type(calVideoFrameLength)==float:
- if calVideoFrameLength < 0: # if '-1' use the whole video
- cal_vid_frame_range = [0, session.numFrames]
- calibrationVideoPath = session.calVidPath
- else:
- if calVideoFrameLength>0 and calVideoFrameLength<=1: #if between 0 and 1, use as a percentage of the total video length
- cal_vid_frame_range = [0, round(calVideoFrameLength * session.numFrames)]
- else: #otherwise, just use the input value as the number of frames to use
- cal_vid_frame_range = [0, calVideoFrameLength]
- elif type(calVideoFrameLength)==list:
- if len(calVideoFrameLength) ==2:
- cal_vid_frame_range = calVideoFrameLength
-
-
- createCalibrationVideos(session, cal_vid_frame_range)
-
- vidnames = []
- cam_names = []
-
- for count, thisVidPath in enumerate(calibrationVideoPath.glob("*.mp4"), start=1):
- vidnames.append([str(thisVidPath)])
- cam_names.append(str(count))
- session.numCams = count
-
-
- cgroup = fmc_anipose.CameraGroup.from_names( cam_names, fisheye=True) # Looking through their code... it looks lke the 'fisheye=True' doesn't do much (see 2020-03-29 obsidian note)
-
- calibrationFile = "{}_calibration.toml".format(session.sessionID)
-
- session.cameraCalFilePath = session.sessionPath / calibrationFile
-
- error,charuco_data, charuco_frames = cgroup.calibrate_videos(vidnames, board)
-
- cgroup = pin_camera_zero_to_origin(cgroup)
- # cgroup = rotate_cameras_so_camera_zero_aligns_with_XYZ(cgroup)
-
-
- cgroup.dump(session.cameraCalFilePath)
-
- camera_calibration_info_dict = cgroup.get_dicts()
- camera_calibration_pickle_path = session.sessionPath / "{}_calibration.pickle".format(session.sessionID)
-
-
- with open(str(camera_calibration_pickle_path), 'wb') as pickle_file:
- pickle.dump(camera_calibration_info_dict, pickle_file)
-
-
-
- session.cgroup = cgroup
- n_frames = cal_vid_frame_range[1]-cal_vid_frame_range[0]
- startframe = 0
- n_trackedPoints = 24
-
- charuco_nCams_nFrames_nImgPts_XY = np.empty([session.numCams, n_frames, n_trackedPoints, 2])
- charuco_nCams_nFrames_nImgPts_XY[:] = np.nan
-
- for cam in range(session.numCams):
- for charCount, thisCharFrame in enumerate(charuco_frames):
- try:
- charuco_nCams_nFrames_nImgPts_XY[cam, thisCharFrame, :,:] = np.squeeze(charuco_data[charCount][cam]["filled"])
- except:
- # print("failed frame:", frame)
- continue
-
- saved_calibration_folder = session.freemocap_module_path/'fmc_calibration'
- saved_calibration_folder.mkdir(exist_ok=True, parents=True)
- calibration_toml_path = saved_calibration_folder/'previous_calibration.toml'
- calibration_charuco2d_npy_path = saved_calibration_folder/'charuco_2d_points.npy'
- cgroup.dump(calibration_toml_path)
- np.save(calibration_charuco2d_npy_path,charuco_nCams_nFrames_nImgPts_XY)
-
-
- charuco2d_filename = session.dataArrayPath/'charuco_2d_points.npy'
- np.save(charuco2d_filename,charuco_nCams_nFrames_nImgPts_XY)
-
-
-
-
-
-
- session.charuco_nCams_nFrames_nImgPts_XY = charuco_nCams_nFrames_nImgPts_XY
-
- charuco_fr_mar_xyz, charuco_reprojErr= reconstruct3D.reconstruct3D(
- session, charuco_nCams_nFrames_nImgPts_XY
- )
-
- mean_charuco_fr_mar_xyz = np.nanmean(charuco_fr_mar_xyz, axis=0)
-
- # charry_reshaped = charucoarray.reshape(session.numCams, -1, 2)
-
- # char_flat = cgroup.triangulate(charry_reshaped, progress=True)
- # charReprojerr_flat = cgroup.reprojection_error(char_flat, charry_reshaped, mean=True)
-
- # char_fr_mar_xyz = char_flat.reshape(n_frames, n_trackedPoints, 3)
- # charReprojErr_fr_mar_err = charReprojerr_flat.reshape(n_frames, n_trackedPoints)
-
- if session.debug:
- fig = plt.figure()
- # mean charuco position
- ax1 = fig.add_subplot(111, projection="3d")
- ax1.cla()
- x = mean_charuco_fr_mar_xyz[:][:, 0]
- y = mean_charuco_fr_mar_xyz[:][:, 1]
- z = mean_charuco_fr_mar_xyz[:][:, 2]
- mx = np.nanmean(x)
- my = np.nanmean(y)
- mz = np.nanmean(z)
-
- ax1.scatter(x, y, z, marker="o")
- ax1.set_title("Mean Charuco Point Positions")
-
- ax1.set_xlabel("x")
- ax1.set_ylabel("y")
- ax1.set_zlabel("z")
-
- for camNum in range(len(cgroup.cameras)):
- np.append(mx, cgroup.cameras[camNum].tvec[0])
- np.append(my, cgroup.cameras[camNum].tvec[1])
- np.append(mz, cgroup.cameras[camNum].tvec[2])
-
- ax1.scatter(
- cgroup.cameras[camNum].tvec[0],
- cgroup.cameras[camNum].tvec[1],
- cgroup.cameras[camNum].tvec[2],
- marker="p",
- )
-
- axRange = board.square_length * 5
-
- ax1.set_xlim(mx - axRange, mx + axRange)
- ax1.set_ylim(my - axRange, my + axRange)
- ax1.set_zlim(mz - axRange, mz + axRange)
-
- # #charuco points over time
- # ax2 = fig.add_subplot(122)
- # ax2.cla()
- # numPts = charuco_fr_mar_xyz.shape[1]
- # for pp in range(numPts):
- # ax2.plot(charuco_fr_mar_xyz[:,pp,:])
- # ax2.set_title('Charuco Point positions over time')
- plt.show()
-
- np.save(session.dataArrayPath/'charuco_3d_points.npy', charuco_fr_mar_xyz)
- np.save(session.dataArrayPath/'charuco_3d_reprojErr.npy', charuco_reprojErr)
-
- return cgroup, charuco_fr_mar_xyz
-
-
-def createCalibrationVideos(session, calVideoFrameLength):
- """
- Based on the desired length of the calibration videos (for the anipose functions), create new videos trimmed
- to that specific length
- """
- vidList = glob.glob(str(session.syncedVidPath) + "/*.mp4")
- if len(calVideoFrameLength)==1:
- framelist = list(range(calVideoFrameLength))
- elif len(calVideoFrameLength)==2:
- framelist = list(range(calVideoFrameLength[0], calVideoFrameLength[1]))
- else:
- Exception('calVideoFrameLength must be either 1 or 2 elements long')
-
- codec = "DIVX"
- for count, vid in enumerate(vidList, start=1):
- cam_name = "Cam{}".format(count)
- cap = cv2.VideoCapture(vid)
- fourcc = cv2.VideoWriter_fourcc(*codec)
-
- # grab resolution parameters from the videos
- resWidth = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
- resHeight = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
- framerate = int(cap.get(cv2.CAP_PROP_FPS))
-
- saveName = (
- session.sessionID + "_trimmed_" + cam_name + ".mp4"
- ) # create a name for the trimmed video
- saveCalVidPath = str(
- session.calVidPath / saveName
- ) # create an output path for the function
-
- success, image = cap.read() # start reading frames
-
- out = cv2.VideoWriter(saveCalVidPath, fourcc, framerate, (resWidth, resHeight))
- print("Trimming " + cam_name + " to frames {}-{} for Anipose Calibration".format(framelist[0], framelist[-1]))
- for frame in track(framelist):
- cap.set(
- cv2.CAP_PROP_POS_FRAMES, frame
- ) # set the video to the frame that we need
- success, image = cap.read()
- out.write(image)
- cap.release()
- out.release()
diff --git a/freemocap/createvideo.py b/freemocap/createvideo.py
deleted file mode 100644
index 96b161c1..00000000
--- a/freemocap/createvideo.py
+++ /dev/null
@@ -1,62 +0,0 @@
-import glob
-import cv2
-from pathlib import Path
-import os
-
-
-def createVideo(session):
-
- vidSavePath = str(session.sessionPath / "{}_outVid.mp4".format(session.sessionID))
- fps = 30
- shape = 1078, 647
- frame_array = []
-
- for filename in session.imOutPath.glob("*.png"):
- filename = str(filename)
-
- # reading each files
- img = cv2.imread(filename)
- # resized = cv2.resize(img,shape)
- # shape = img.shape[:2]
- resized = cv2.resize(img, shape)
- # inserting the frames into an image array
- frame_array.append(resized)
- out = cv2.VideoWriter(vidSavePath, cv2.VideoWriter_fourcc(*"DIVX"), fps, shape)
- for i in range(len(frame_array)):
- # writing to a image array
- out.write(frame_array[i])
- out.release()
-
-
-def createBodyTrackingVideos(session):
-
- vidSavePath = str(session.sessionPath / "{}_outVid.mp4".format(session.sessionID))
- fps = 30
- shape = 1078, 647
- # frame_array = []
-
- if session.useOpenPose:
-
- for count,videoPath in enumerate(session.session_settings['openPose_imgPathList']):
- frame_array = []
- vidSavePath = str(
- session.openPoseDataPath / "openPoseVideo_cam{}.mp4".format(count)
- )
- videoPath = Path(videoPath)
- for filename in videoPath.glob("*.png"):
-
- filename = str(filename)
- # reading each files
- img = cv2.imread(filename)
- # resized = cv2.resize(img,shape)
- # shape = img.shape[:2]
- resized = cv2.resize(img, shape)
- # inserting the frames into an image array
- frame_array.append(resized)
- out = cv2.VideoWriter(
- vidSavePath, cv2.VideoWriter_fourcc(*"DIVX"), fps, shape
- )
- for i in range(len(frame_array)):
- # writing to a image array
- out.write(frame_array[i])
- out.release()
diff --git a/freemocap/dev_scratchpad/__init__.py b/freemocap/dev_scratchpad/__init__.py
deleted file mode 100644
index eb6e819d..00000000
--- a/freemocap/dev_scratchpad/__init__.py
+++ /dev/null
@@ -1 +0,0 @@
-from play_skeleton_animation.py import PlaySkeletonAnimation
\ No newline at end of file
diff --git a/freemocap/dev_scratchpad/batch_process.py b/freemocap/dev_scratchpad/batch_process.py
deleted file mode 100644
index 88fbd194..00000000
--- a/freemocap/dev_scratchpad/batch_process.py
+++ /dev/null
@@ -1,93 +0,0 @@
-#%%
-from pathlib import Path
-import freemocap as fmc
-import datetime
-import logging
-from rich import inspect
-from rich import print
-from rich.console import Console
-console = Console()
-import shutil
-import pandas as pd
-#%%
-
-
-
-import socket
-this_computer_name = socket.gethostname()
-
-freemocap_data_path=None
-
-if this_computer_name=='jon-hallway-XPS-8930':
- freemocap_data_path = Path('/home/jon/Dropbox/FreeMoCapProject/FreeMocap_Data')
-
-elif this_computer_name == 'DESKTOP-DCG6K4F':
- freemocap_data_path = Path(r'C:\Users\jonma\Dropbox\FreeMoCapProject\FreeMocap_Data')
-elif this_computer_name == 'DESKTOP-V3D343U':
- freemocap_data_path = Path(r'C:\Users\WindowsPC_Hallway\Dropbox\FreeMoCapProject\FreeMocap_Data')
-elif this_computer_name == 'Jons-MacBook-Pro.local':
- freemocap_data_path = Path('/Users/jon/Dropbox/FreeMoCapProject\FreeMocap_Data')
-
-#%%
-
-batch_process_ID = datetime.datetime.now().strftime("batch_process_%Y-%m-%d_%H_%M_%S")
-path_to_log_file = freemocap_data_path / (batch_process_ID+'_log.txt')
-
-logging.basicConfig(filename=str(path_to_log_file), filemode='w', format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO)
-logging.info('Log file create :D')
-
-#%%
-out_vid_path = freemocap_data_path / 'output_animation_videos'
-out_vid_path.mkdir(exist_ok=True)
-
-csv_path = out_vid_path / 'viable_folders_status.csv'
-
-detect_folders_to_process_bool = True
-if detect_folders_to_process_bool:
- dataframe_init_dict = {'viable_folder_paths':[],
- 'outVid_exists_bool':[]}
- viable_folders_dataframe = pd.DataFrame(dataframe_init_dict)
-
- with console.status('Looking for viable folders (that contain synced vids)'):
- for this_folder in freemocap_data_path.glob('**/*'):
- if this_folder.is_dir():
- #check if there is a synced video folder in here
- for this_sub_folder in this_folder.iterdir():
- if this_sub_folder.is_dir():
- if this_sub_folder.name.lower()[0:4]=='sync':
- logging.info('Viable Folder found at {}'.format(str(this_folder)))
- out_vid_exists = False
- for this_mp4 in this_folder.glob('*.mp4'):
- out_vid_exists = True
- # shutil.copy(this_mp4, str(out_vid_path))
- # logging.info('OutVid - {} - Copied to - {}'.format(str(this_mp4), str(out_vid_path)))
- viable_folders_dataframe.loc[len(viable_folders_dataframe.index)] = [str(this_folder), out_vid_exists]
- viable_folders_dataframe.to_csv(csv_path, index=False)
- logging.info('List of all viable session folders saved to {}'.format(str(csv_path)))
-else:
- try:
- viable_folders_dataframe = pd.read_csv(csv_path)
- logging.info('Loaded csv with list viable session folders from {}'.format(str(csv_path)))
- except Exception:
- console.print_exception()
- logging.error('Failed to load csv with list viable session folders from {}'.format(str(csv_path)))
-
-
-# %%
-
-
-# %%
-reprocess_bool = False
-if reprocess_bool:
- folders_to_process = viable_folders_dataframe[viable_folders_dataframe["outVid_exists_bool"]==False]
- for this_item in folders_to_process['viable_folder_paths']:
- this_session_id = Path(this_item).name
- print('Starting to process SessionID: {}'.format(this_session_id))
- logging.info('Starting to process SessionID: {}'.format(this_session_id))
- try:
- fmc.RunMe(sessionID = this_session_id, stage=3, useBlender=True, showAnimation=False)
- logging.info('SessionID: {} processed successfully!'.format(this_session_id))
- except Exception:
- console.print_exception(Exception)
- logging.info('SessionID: {} failed to process'.format(this_session_id))
-
diff --git a/freemocap/dev_scratchpad/blender_test_script.py b/freemocap/dev_scratchpad/blender_test_script.py
deleted file mode 100644
index 2412ceac..00000000
--- a/freemocap/dev_scratchpad/blender_test_script.py
+++ /dev/null
@@ -1,8 +0,0 @@
-import bpy
-
-bpy.ops.mesh.primitive_monkey_add(enter_editmode=False, align='WORLD', location=(0, 0, 0), scale=(1, 1, 1))
-
-this_monke = bpy.context.active_object
-
-bpy.ops.mesh.primitive_monkey_add(enter_editmode=False, align='WORLD', location=(0, 2, 0), scale=(1, 1, 1))
-
diff --git a/freemocap/dev_scratchpad/dev_alpha_old/FMC_Camera.py b/freemocap/dev_scratchpad/dev_alpha_old/FMC_Camera.py
deleted file mode 100644
index d05a49c3..00000000
--- a/freemocap/dev_scratchpad/dev_alpha_old/FMC_Camera.py
+++ /dev/null
@@ -1,374 +0,0 @@
-##
-##
-## β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆ
-## β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ
-## β–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ
-## β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ
-## β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ
-##
-##
-#Font - ANSI Regular - https://patorjk.com/software/taag/#p=display&f=ANSI%20Regular&t=Play%20Skeleton%20Animation
-
-
-
-import platform
-from pathlib import Path
-import time
-
-import cv2
-import numpy as np
-
-#python rich stuff - https://rich.readthedocs.io/
-from rich import print
-from rich.console import Console
-
-
-
-cap_default_parameters_dict = {
- 'exposure': -5,
- 'cap_resolution_width': 1280,
- 'cap_resolution_height': 720,
- }
-
-class FMC_Camera:
- """ Class to open a cv2.VideoCapture object, with parts to connect to a `FMC_MutliCam` object as part of a FMC_Session.
- Note, this class was made in service of the needs of the FreeMoCap project, at some point I'd love to develop this into a fully generic and useful 'camera' object, right now it's designed with that application (and only that application) in mind
- """
- ##
- ##
- ## β–ˆβ–ˆ β–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ
- ## β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ
- ## β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ
- ## β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ
- ## β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ
- ##
- ##
- ##
-
- def __init__(
- self,
- cam_num=0,
- rotation_code=None,
- frame_queue = None,
- barrier = None,
- exit_event = None,
- show_cam_stream = False,
- rich_console = None,
- show_console = False,
- cap_parameters_dict = cap_default_parameters_dict,
- vid_save_path=None,
- ):
- """Open a camera stream using `cv2.VideoCapture()`.
- If `Windows`, use `cv2.VideoCapture(camNum, cv2.CAP_DSHOW)` to make video initialize much faster. Otherwise, use `cv2.VideoCapture(camNum, cv2.CAP_ANY)
-
- Args:
- camNum (int, optional): The ID of the camera to open. Defaults to 0 (i.e. the first camera it finds)
- vid_save_path (pathlib Path, optional): Where to save the video. Defaults to None.
- barrier (threading.Barrier, optional): Barrier for syncronized multicam recording. Defaults to None.
- frame_queue (queue.Queue, optional): [description]. Queue to send out images when we're recording in a thread.
- """
-
- self._cam_num = cam_num
- self._cam_name = 'Camera_{}'.format(str(self._cam_num).zfill(2))
- self._cam_short_name = 'cam{}'.format(self._cam_name)
-
- self._vid_cap_start_time_unix = None
-
- self._cap_parameters_dict = cap_parameters_dict
-
- self._rotation_code = rotation_code
-
- self._frame_queue = frame_queue
- self._barrier = barrier
- self._exit_event = exit_event
- self._vid_save_path = vid_save_path
- self._show_console = show_console
- self.rich_console = rich_console # a console object from the Rich python package
-
-
- if vid_save_path:
- self._vid_save_path = Path(vid_save_path)
-
-
- if not self.rich_console:
- self.rich_console = Console()
-
- self.open() #open VideoCapture Object
-
- self._show_cam_stream = show_cam_stream
- if self._show_cam_stream:
- self.show()#display camera stream
-
- if self._frame_queue:
- self.run_in_thread() #launch in thread (or process?) mode
- ##
- ## β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ
- ## β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ
- ## β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ
- ## β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ
- ## β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ
- ##
- ##
- @property
- def cam_num(self):
- return self._cam_num
-
- @property
- def cam_name(self):
- return self._cam_name
-
- @property
- def cam_short_name(self):
- return self._cam_short_name
-
- @property
- def vid_save_path(self):
- return self._vid_save_path
-
- @property
- def show_cam_stream(self):
- return self._show_cam_stream
-
- @show_cam_stream.setter
- def show_cam_stream(self, input_bool):
- self._show_cam_stream = input_bool
-
- @property
- def vid_cap_start_time_unix(self):
- return self._vid_cap_start_time_unix
-
- @property
- def vid_cap_timestamps_unix_ns(self): #not really a property though?
- return self._vid_cap_timestamps_unix_ns
-
- @property
- def show_console(self):
- return self._show_console
-
- @show_console.setter
- def show_console(self, input_bool):
- self._show_console = input_bool
-
- ###
- ###
- ### β–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆ β–ˆβ–ˆ
- ### β–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ
- ### β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ
- ### β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ
- ### β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆ
- ###
- ###
- ###
-
- def show_cam_stream(self, show_cam_stream_bool=True):
- """whether to open a window showing camera stream
-
- calls `self.show()` when set to `True`
- and calls `self.close()` when set to `False` (b/c I'm too lazy to figure out how to make ti close th the display without closing the capture right now, sorry lol)
-
- Args:
- show_cam_stream_bool (Bool): whether to show stream (default)
-
- Returns:
- self
- """
- assert type(show_cam_stream_bool) == type(True), 'Input to `show_cam_stream` must be a bool'
- self._show_cam_stream = show_cam_stream_bool
-
- if self._show_cam_stream:
- self.show()
- else:
- self.close()
-
- return self._show_cam_stream
- ###
- ### β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ
- ### β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ
- ### β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ
- ### β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ
- ### β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ
- ###
- ###
- def open(self):
- """
- Open Video Capture Object and dispaly in little video
- """
-
- if platform.system() == 'Windows':
- self.cv2_cap = cv2.VideoCapture(self._cam_num, cv2.CAP_DSHOW)
- else:
- self.cv2_cap = cv2.VideoCapture(self._cam_num, cv2.CAP_ANY)
-
- self.cv2_cap.set(cv2.CAP_PROP_EXPOSURE, self._cap_parameters_dict['exposure'])
- self.cv2_cap.set(cv2.CAP_PROP_FRAME_WIDTH, self._cap_parameters_dict['cap_resolution_width'])
- self.cv2_cap.set(cv2.CAP_PROP_FRAME_HEIGHT, self._cap_parameters_dict['cap_resolution_height'])
-
- self.cv2_cap.set(cv2.CAP_PROP_FOURCC, cv2.VideoWriter_fourcc('M', 'J', 'P', 'G'))
-
-
- self.video_exposure = self.cv2_cap.get(cv2.CAP_PROP_EXPOSURE)
- self.video_resolution_width = self.cv2_cap.get(cv2.CAP_PROP_FRAME_WIDTH)
- self.video_resolution_height = self.cv2_cap.get(cv2.CAP_PROP_FRAME_HEIGHT)
-
- if not self.cv2_cap.isOpened():
- self.rich_console.log("Camera# "+str(self._cam_num)+" failed to open :(")
-
- else:
- self.rich_console.log("Camera# "+str(self._cam_num)+" started - Exposure:({}) - Resolution(width, height):({},{}) ".format(self.video_exposure, self.video_resolution_width, self.video_resolution_height))
- self._vid_cap_start_time_unix = time.time_ns() #the precision is aspirational, lol
- self._vid_cap_timestamps_unix_ns = np.empty(0)
-
- ###
- ### β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ
- ### β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ
- ### β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ
- ### β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ
- ### β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ
- ###
-
- def show(self):
- """
- display the camera stream, press ESC to close (and release the `cv2_cap`)
- """
- success, image, timestamp = self.read_next_frame()
-
- while success:
- cv2.imshow(self._cam_name, image)
-
- success, image, timestamp = self.read_next_frame()
-
- console_msg = self.cam_name + " read an image at {:.4f}".format(timestamp)
- self.update_console(console_msg)
- self._vid_cap_timestamps_unix_ns = np.append(self.vid_cap_timestamps_unix_ns, timestamp)
-
- if self.wait_key() == 27: # exit on ESC
- self.close()
-
- if cv2.getWindowProperty(self._cam_name, cv2.WND_PROP_VISIBLE) < 1: #break loop if window closed
- break
- cv2.destroyAllWindows()
-
- ###
- ### β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ
- ### β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ
- ### β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ
- ### β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ
- ### β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ
- ###
- ###
- def run_in_thread(self):
- """run camera in a thread
- put incoming images into an tuple containing camNum_image_timestamp_tuple and stuff it into `self._frame_queue`
- """
- # with self.rich_console.status('Camera# {} is running'.format(self.cam_num)):
- while not self._exit_event.is_set():
- try:
- success, image, timestamp = self.read_next_frame()
- cam_image_timestamp_tuple = (self.cam_num, image, timestamp)
-
- self._frame_queue.put(cam_image_timestamp_tuple) #stuff this frame tuple packet into this camera's Queueue object
-
- # log_msg = self.cam_name+" got a frame at timestamp:"+ str(timestamp) + ' queue size: ' + str(self._frame_queue.qsize())
- # self.rich_console.log(log_msg)
-
- self._barrier.wait() #wait until other cams have grabbed a frame (and the frame_grabber has frame grabbed them)
- except:
- self.rich_console.print_exception()
-
- #shut down when 'exit_event' is tripped
- self.close()
-
-
- def run_in_subprocess(self):
- self.run_in_thread()
-
- ###
- ###
- ### β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ
- ### β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ
- ### β–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ
- ### β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ
- ### β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ
- ###
- ###
-
-
-
- def __enter__(self):
- """Context manager - No need to do anything special on start"""
- return self
-
- def __exit__(self, exc_type, exc_value, exc_traceback):
- """Context manager - close `self.cv2_cap` on exit"""
- self.close()
- return self
-
- def update_console(self, console_msg):
- if self.show_console:
- self.rich_console.log(console_msg) #there should be a way to log this without printing it, but I don't know how....
-
- def read_next_frame(self):
- """ Grab next frame, return `Tuple(success[bool, True], image, timestamp)` on success or `Tuple(success[bool, False], False, False)` on failure
-
- Returns:
- Success[bool]: True if frame image captured successfully
- image: the image that was recieved from the VideoCapture object
- timestamp: unix timestamp from time.time_ns()
- """
- success, image = self.cv2_cap.read()
- timestamp = time.time_ns() #the precision is aspirational, lol
- if success:
- self._vid_cap_timestamps_unix_ns = np.append(self._vid_cap_timestamps_unix_ns, time.time_ns()) #the precision is aspirational, lol
-
- if self._rotation_code is None:
- pass
- elif self._rotation_code == 'cv2.ROTATE_90_CLOCKWISE':
- image = cv2.rotate(image, cv2.ROTATE_90_CLOCKWISE)
- elif self._rotation_code == 'cv2.ROTATE_90_COUNTERCLOCKWISE':
- image = cv2.rotate(image, cv2.ROTATE_90_COUNTERCLOCKWISE)
- elif self._rotation_code == 'cv2.ROTATE_180':
- image = cv2.rotate(image, cv2.ROTATE_180)
- else:
- Exception, 'Invalid rotation code entered for FMC_Camera: {}'.format(self.cam_name)
-
- return success, image, timestamp
- else:
- return success, success, success
-
- def close(self):
- """
- close the video
- """
- self.cv2_cap.release()
- self.rich_console.log("Camera# "+str(self._cam_num)+" shutting down")
-
-
- def wait_key(self):
-
- if self.show_cam_stream:
- self._wait_key = cv2.waitKey(1)
- else:
- self._wait_key = 27
-
- return self._wait_key
-
-
-###
-### β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆ β–ˆβ–ˆ
-### β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ
-### β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ
-### β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ
-### β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ
-###
-###
-if __name__ == '__main__':
-
- with FMC_Camera() as cam:
- console = Console() #create Rich console to catch and print exceptions
- try:
- while True:
- cam.show()
- break
- except Exception:
- console.print_exception()
-
diff --git a/freemocap/dev_scratchpad/dev_alpha_old/FMC_MultiCamera.py b/freemocap/dev_scratchpad/dev_alpha_old/FMC_MultiCamera.py
deleted file mode 100644
index d1a5067d..00000000
--- a/freemocap/dev_scratchpad/dev_alpha_old/FMC_MultiCamera.py
+++ /dev/null
@@ -1,704 +0,0 @@
-##
-##
-## β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆ
-## β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ
-## β–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ
-## β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ
-## β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ
-##
-##
-# Font - ANSI Regular - https://patorjk.com/software/taag/#p=display&f=ANSI%20Regular&t=Play%20Skeleton%20Animation
-
-
-from rich.repr import T
-from FMC_Camera import FMC_Camera
-
-
-import threading
-import pathos.multiprocessing as pathos_mp
-from pathos.helpers import mp as pathos_mp_helper
-import time
-import platform
-import datetime
-
-import cv2
-import matplotlib.pyplot as plt
-import numpy as np
-from pathlib import Path
-
-from rich import print
-from rich import inspect
-from rich.progress import track
-from rich.traceback import install
-
-install(show_locals=True)
-from rich.console import Console
-
-rich_console = Console()
-from rich.progress import track
-
-
-class FMC_MultiCamera:
- ##
- ##
- ## β–ˆβ–ˆ β–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ
- ## β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ
- ## β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ
- ## β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ
- ## β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ
- ##
- ##
- ##
- def __init__(
- self,
- rec_name=None,
- freemocap_data_folder=None,
- num_cams=0,
- cams_to_use_list=None,
- rotation_codes_list=None,
- show_multi_cam_stream_bool=True,
- save_multi_cam_to_mp4=False,
- save_each_cam_to_mp4=True,
- save_to_h5=False,
- save_log_file=False,
- ):
-
- self._init_start_time = time.time_ns() # the precision is aspirational, lol
-
- if rec_name is None:
- self._rec_name = datetime.datetime.now().strftime(
- "sesh_%Y-%m-%d_%H_%M_%S_mc"
- )
- else:
- self._rec_name = rec_name
-
- if freemocap_data_folder is None:
- self._save_path = Path("data/" + self._rec_name)
- else:
- self._save_path = Path(freemocap_data_folder) / self._rec_name
-
- if (
- freemocap_data_folder
- or save_multi_cam_to_mp4
- or save_to_h5
- or save_log_file
- or save_each_cam_to_mp4
- ):
- self._save_path.mkdir(parents=True, exist_ok=True)
- self._path_to_log_file = Path(
- str(self._save_path / self._rec_name) + "_log.txt"
- )
-
- self._save_multi_cam_to_mp4 = save_multi_cam_to_mp4
- if self._save_multi_cam_to_mp4:
- self._output_multi_cam_video_object = (
- None # build this after we get the first multi_frame_image
- )
-
- self._save_each_cam_to_mp4 = save_each_cam_to_mp4
- if self._save_each_cam_to_mp4:
- self._each_cam_video_writer_object_list = (
- None # build this after we get the first multi_frame_image
- )
-
- # log_file_obj = open(self._path_to_log_file,'w+')
- # rich_console = Console(file=log_file_obj)
- rich_console = Console()
-
- if cams_to_use_list:
- self._num_cams = len(cams_to_use_list)
- else:
- self._num_cams = num_cams
- self._cams_to_use_list = cams_to_use_list
-
- self._rotation_codes_list = rotation_codes_list
-
- self._show_multi_cam_stream_bool = show_multi_cam_stream_bool
-
- self.num_frames = 0
-
- rich_console.rule("Starting FreeMoCap MultiCam!")
-
- ###
- ###
- ### β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ
- ### β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ
- ### β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ
- ### β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ
- ### β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ
- ###
- ###
-
- @property
- def num_cams(self):
- """How many cameras to use"""
- return self._num_cams
-
- @num_cams.setter
- def num_cams(self, num_cams_input):
- """Define how many cameras to use"""
- self._num_cams = num_cams_input
-
- @property
- def cams_to_use_list(self):
- """a list denoting which camera IDs to use.
- If both this and `num_cams` are set to default value (`0` and `None`, respectively), use all available cameras).
- """
- return self._cams_to_use_list
-
- @property
- def init_start_time(self):
- """Time that this object was initialized (UNIX Epoch time from `time.time_ns())
-
- Returns:
- float: time this object was created (UNIX Epoch time from `time.time_ns())
- """
- return self._init_start_time
-
- @property
- def each_cam_timestamps_unix_ns(self): # not really a property though?
- return self._each_cam_timestamps_unix_ns
-
- ###
- ###
- ### β–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ
- ### β–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ
- ### β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ
- ### β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ
- ### β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ
-
- #################################################################
- ###
- ###
- ### β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ
- ### β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ
- ### β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ
- ### β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ
- ### β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ
- ###
- ###
- ###
- ###
- def start(self, standalone_mode=False):
- self.standalone_mode = standalone_mode
- if self.cams_to_use_list is None:
- self.find_available_cameras()
-
- # pathos_pool = ProcessPool(nodes=1)
- # pathos_pool.map(self.start_multi_cam_thread_pool)
- # self.start_multi_cam_thread_pool() #threads are mostly fine, but I think processes will be better eventually?
- self.start_multi_cam_process_pool()
- if standalone_mode:
- self.create_diagnostic_images()
-
- ##
- ##
- ## β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ
- ## β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ
- ## β–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ
- ## β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ
- ## β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ
- ##
- ##
- ##
-
- def find_available_cameras(self):
- """find available webcams and return IDs in list."""
-
- if self.num_cams == 0:
- num_cams_to_check = 20 # man, i HOPE you're out there trying to record from more than 20 cameras!!!
- else:
- num_cams_to_check = self.num_cams
-
- if platform.system() == "Windows":
- capBackend = cv2.CAP_DSHOW
- else:
- capBackend = cv2.CAP_ANY
-
- self._cams_to_use_list = []
- for camNum in range(
- num_cams_to_check
- ): # track(range(num_cams_to_check), description='[green]Finding available cameras...' ):
- # print('ATTEMPTING TO OPEN CAMERA AT PORT# {}'.format(camNum))
- cap = cv2.VideoCapture(camNum, capBackend)
- success, image = cap.read()
- if (
- success
- ): # this is apparently a more power check than `cap.isOpened()` which sometimes returns false positives for unknown reason. Will lose the first frame if this method is ever applied to reading in videos instead of streaming from cameras
- # rich_console.print('SUCCESS - CAMERA FOUND at # {}'.format(camNum), style="bold cyan")
- self._cams_to_use_list.append(camNum)
- cap.release()
- else:
- pass
- # rich_console.print('No CAMERA FOUND at # {}'.format(camNum), style="magenta")
-
- rich_console.print("Found cameras at ", self._cams_to_use_list)
-
- self.num_cams = len(self._cams_to_use_list)
- return self.cams_to_use_list
-
- ###
- ###
- ### β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ
- ### β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ
- ### β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ
- ### β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ
- ### β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ
- ###
- ###
- ###
- def start_multi_cam_process_pool(self):
- """
- reates a ProcessPoolExecutor that creates an `FMC_Camera` object for each camera in `self.cams_to_use_list` and sets each to trigger `run_in_process` mode (which just passes to `run_in_thread` mode)
-
- """
- mrManager = pathos_mp_helper.Manager()
- self.cam_frame_queue = mrManager.Queue(maxsize=self.num_cams)
- self.multi_cam_tuple_queue = mrManager.Queue()
- self.barrier = mrManager.Barrier(
- self.num_cams + 1
- ) # each cam + one more for the frame grabber
- self.exit_event = mrManager.Event()
-
- self._each_cam_timestamps_unix_ns = None
- self._cam_process = [None] * self.num_cams
-
- rich_console.rule("starting multi_cam_process_pool")
-
- in_frame_q_list = [self.cam_frame_queue] * self.num_cams
- in_barrier_list = [self.barrier] * self.num_cams
- in_exit_event_list = [self.exit_event] * self.num_cams
-
- if self._rotation_codes_list is None:
- self._rotation_codes_list = [None] * self.num_cams
-
- num_jobs = self.num_cams
- with pathos_mp.ProcessingPool(num_jobs) as self.cam_process_pool:
- self.cam_process_pool.amap(
- FMC_Camera,
- tuple(self.cams_to_use_list),
- tuple(self._rotation_codes_list),
- tuple(in_frame_q_list),
- tuple(in_barrier_list),
- tuple(in_exit_event_list),
- )
- self.incoming_tuple_grabber_thread = threading.Thread(
- target=self.grab_incoming_cam_tuples,
- name="Incoming Frame Tuple Grabber Thread",
- )
- self.incoming_tuple_grabber_thread.start()
- if self._show_multi_cam_stream_bool or self.standalone_mode:
- self.show_multi_cam_opencv()
-
- ###
- ###
- ### β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ
- ### β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ
- ### β–ˆβ–ˆ β–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ
- ### β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ
- ### β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ
- ###
- ###
-
- def grab_incoming_cam_tuples(self):
- """grab incoming cam_tuples, put them into a multi_cam_tuple and stuff that into the multi_cam_tuple_queue"""
-
- # self.show_multi_cam_cv2()
-
- while not self.exit_event.is_set():
- self.barrier.wait() # wait until each camera has grabbed an image and tagged their `barrier.wait()` signals
-
- self.num_frames += 1
-
- these_images_list = [None] * self.num_cams # empty list of size (numCam)
- this_multi_cam_tuple_as_a_list = [None] * self.num_cams
- these_timestamps = np.ndarray(self.num_cams)
-
- for cam_num in range(self.num_cams):
- this_cam_image_timestamp_tuple = self.cam_frame_queue.get()
- this_cam_num = this_cam_image_timestamp_tuple[0]
- this_cam_index = self.cams_to_use_list.port_number(this_cam_num)
- these_images_list[this_cam_index] = this_cam_image_timestamp_tuple[1]
- these_timestamps[this_cam_index] = this_cam_image_timestamp_tuple[2]
- this_multi_cam_tuple_as_a_list[
- this_cam_index
- ] = this_cam_image_timestamp_tuple
-
- this_multi_cam_tuple = tuple(this_multi_cam_tuple_as_a_list)
-
- if self._each_cam_timestamps_unix_ns is None:
- self._each_cam_timestamps_unix_ns = these_timestamps
- else:
- self._each_cam_timestamps_unix_ns = np.vstack(
- (self._each_cam_timestamps_unix_ns, these_timestamps)
- ) # result will be numpy array with `num_frames` rows and `num_cams` columns
-
- self.multi_cam_tuple_queue.put(
- this_multi_cam_tuple, np.mean(these_timestamps)
- )
-
- rich_console.log(
- "Created a multi_cam_tuple - queue size: {}".format(
- self.multi_cam_tuple_queue.qsize()
- )
- )
-
- def stitch_multicam_image(self, multi_cam_tuple):
- """Take in a multi-cam-tuple (containing images from each camera during the period of time defined by the attached timestamps)
-
- Args:
- multi_cam_tuple (tuple of tuples): The multi_cam_tuple produced by `self.grab_incoming_cam_tuples()` comprising a timestamp and a tuple from each of the cameras. Each camera's tuple consists of the camera's ID/Number, the image frame, and the timestamp that frame was recorded. The multi-camtimestamp is the mean of each of the timestamps from the individual cameras.
- Returns:
- multi_cam_image: an image of size camera_res_width*num_cams x camera_res_height The images are synchronized within the precision defined by the timestamps included in the individual camera tuples.
- """
-
- these_images_list = [None] * self.num_cams # empty list of size (numCam)
-
- for this_cam_num in range(self.num_cams):
- these_images_list[this_cam_num] = multi_cam_tuple[this_cam_num][
- 1
- ] # and that's how you navigate nested tuples, lol
-
- multi_cam_image = np.hstack(
- these_images_list
- ) # create multiFrame_image by stitching together (horizontally stacking) incoming camera images (matrices)
- return multi_cam_image
-
- # rich_console.log('Created a multi_cam_image - queue size: {}'.format(self.multi_cam_tuple_queue.qsize()))
-
- ###
- ###
- ### β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ
- ### β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ
- ### β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ
- ### β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ
- ### β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ
- ###
- ### 6
-
- def show_multi_cam_opencv(self):
- """display multi_cam_image using `cv2.imshow` and maybe save it to mp4, who knows?"""
- rich_console.rule("Launching Multi Cam Viewer")
- while not self.exit_event.is_set():
- if not self.multi_cam_tuple_queue.empty():
-
- this_multi_cam_tuple = self.multi_cam_tuple_queue.get()
- self.save_synchronized_videos(this_multi_cam_tuple)
- this_multi_cam_image = self.stitch_multicam_image(this_multi_cam_tuple)
-
- if self._save_multi_cam_to_mp4:
- if self._output_multi_cam_video_object is None:
- self.initialize_multi_cam_output_video(this_multi_cam_image)
-
- self._output_multi_cam_video_object.write(this_multi_cam_image)
-
- if self._save_each_cam_to_mp4:
- if self._each_cam_video_writer_object_list is None:
- self.initialize_each_cam_output_video(this_multi_cam_tuple)
-
- for this_cam_num in range(self.num_cams):
- self._each_cam_video_writer_object_list[this_cam_num].write(
- this_multi_cam_tuple[this_cam_num][1]
- )
-
- cv2.imshow(self._rec_name, this_multi_cam_image)
- key = cv2.waitKey(1)
-
- if key == 27: # exit on ESC
- break
-
- if (
- cv2.getWindowProperty(self._rec_name, cv2.WND_PROP_VISIBLE) < 1
- ): # break loop if window closed
- break
-
- cv2.destroyAllWindows()
-
- if self._save_multi_cam_to_mp4:
- self._output_multi_cam_video_object.release()
-
- if self._save_each_cam_to_mp4:
- for this_cam_num in range(self.num_cams):
- self._each_cam_video_writer_object_list[this_cam_num].release()
-
- rich_console.rule("Shutting down MultiCamera Viewer")
- self.exit_event.set() # send the 'Exit' signal to everyone.
-
- def save_synchronized_videos(self, multi_cam_tuple):
- """save camera streams into individual videos (that can be processed with pre-alpha freemocap"""
- these_images_list = [None] * self.num_cams # empty list of size (numCam)
-
- for this_cam_num in range(self.num_cams):
- this_cam_image = multi_cam_tuple[this_cam_num][
- 1
- ] # and that's how you navigate nested tuples, lol
-
- ###
- ###
- ### β–ˆβ–ˆ β–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ
- ### β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ
- ### β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ
- ### β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ
- ### β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ
- ###
- ###
-
- def initialize_multi_cam_output_video(self, multi_cam_image):
- """use the multi_cam_image to initialize the video
- multicam image will be of size [cam_resolution_width*num_cams by cam_resolution_height]
- Args:
- multi_cam_image ([type]): [description]
- """
- # create video save object
- (
- self._multi_cam_image_height,
- self._multi_cam_image_width,
- channels,
- ) = multi_cam_image.shape
-
- self.multi_cam_image_size = (
- self._multi_cam_image_width,
- self._multi_cam_image_height,
- )
- fourcc = cv2.VideoWriter_fourcc(*"DIVX")
- self._output_multi_cam_vid_fileName = (
- str(self._save_path / self._rec_name) + "_outVid.mp4"
- )
- fps = 25 # this is a bad and stupid guess, but it's actually kinda tricky to guess what is the right thing to put here. I'll fix this later and expect videos to be a bit faster than usual :(
- self._output_multi_cam_video_object = cv2.VideoWriter(
- self._output_multi_cam_vid_fileName, fourcc, fps, self.multi_cam_image_size
- )
-
- def initialize_each_cam_output_video(self, multi_cam_tuple):
-
- self._each_cam_video_writer_object_list = [None] * self.num_cams
- self._each_cam_video_filename_list = [None] * self.num_cams
-
- self.syncedVidsPath = self._save_path / "Synchronized_Videos"
- self.syncedVidsPath.mkdir(parents=True)
-
- for this_cam_num in range(self.num_cams):
- # create video save object
- this_cam_image = multi_cam_tuple[this_cam_num][1]
- this_cam_timestamp_unix_ns = multi_cam_tuple[this_cam_num][2]
- (
- self._cam_image_height,
- self._cam_image_width,
- channels,
- ) = this_cam_image.shape
-
- self._cam_image_size = (self._cam_image_width, self._cam_image_height)
- fourcc = cv2.VideoWriter_fourcc(*"DIVX")
-
- this_cam_vid_filename = (
- self._rec_name + "_Camera_" + str(this_cam_num) + "_synchronized.mp4"
- )
- self._each_cam_video_filename_list[this_cam_num] = (
- self.syncedVidsPath / this_cam_vid_filename
- )
-
- fps = 25 # this is a bad and stupid guess, but it's actually kinda tricky to guess what is the right thing to put here. I'll fix this later and expect videos to be a bit faster than usual :(
- self._each_cam_video_writer_object_list[this_cam_num] = cv2.VideoWriter(
- str(self._each_cam_video_filename_list[this_cam_num]),
- fourcc,
- fps,
- self._cam_image_size,
- )
-
- ##
- ##
- ##
- ## β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ
- ## β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ
- ## β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ
- ## β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ
- ## β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ
- ##
- ##
-
- def create_diagnostic_images(self):
- """plot some diagnostics to assess quality of camera sync"""
- try:
- camTimestamps = (
- self.each_cam_timestamps_unix_ns - self.init_start_time
- ) / 1e9 # subtract start time and convert to sec
-
- npy_save_path = self._save_path / "multi_cam_timestamps_frameNum_camNum.npy"
- np.save(str(npy_save_path), camTimestamps)
- rich_console.log("saving timestamp data to - " + str(npy_save_path))
-
- meanMultiFrameTimestamp = np.mean(camTimestamps, axis=1)
- meanMultiFrameTimespan = np.max(camTimestamps, axis=1) - np.min(
- camTimestamps, axis=1
- ) # what was the timespan covered by each frame
- plt.ion()
- fig = plt.figure(figsize=(18, 10))
- max_frame_duration = 0.1
- ax1 = plt.subplot(
- 231,
- title="Camera Frame Timestamp vs Frame#",
- xlabel="Frame#",
- ylabel="Timestamp (sec)",
- )
- ax2 = plt.subplot(
- 232,
- ylim=(0, max_frame_duration),
- title="Camera Frame Duration Trace",
- xlabel="Frame#",
- ylabel="Duration (sec)",
- )
- ax3 = plt.subplot(
- 233,
- xlim=(0, max_frame_duration),
- title="Camera Frame Duration Histogram (count)",
- xlabel="Duration(s, 1ms bins)",
- ylabel="Probability",
- )
- ax4 = plt.subplot(
- 234,
- title="MuliFrame Timestamp vs Frame#",
- xlabel="Frame#",
- ylabel="Timestamp (sec)",
- )
- ax5 = plt.subplot(
- 235,
- ylim=(0, max_frame_duration),
- title="Multi Frame Duration/Span Trace",
- xlabel="Frame#",
- ylabel="Duration (sec)",
- )
- ax6 = plt.subplot(
- 236,
- xlim=(0, max_frame_duration),
- title="MultiFrame Duration Histogram (count)",
- xlabel="Duration(s, 1ms bins)",
- ylabel="Probability",
- )
-
- for camNum in range(self.num_cams):
- thisCamTimestamps = camTimestamps[:, camNum]
- ax1.plot(thisCamTimestamps, label="Camera#" + str(camNum))
- ax1.legend()
- ax2.plot(np.diff(thisCamTimestamps), ".")
- ax3.hist(
- np.diff(thisCamTimestamps),
- bins=np.arange(0, max_frame_duration, 0.001),
- alpha=0.5,
- )
-
- ax4.plot(
- meanMultiFrameTimestamp,
- color="darkslategrey",
- label="MultiFrame" + str(camNum),
- )
- ax5.plot(
- np.diff(meanMultiFrameTimestamp),
- ".",
- color="darkslategrey",
- label="Frame Duration",
- )
- ax5.plot(
- meanMultiFrameTimespan, ".", color="orangered", label="Frame TimeSpan"
- )
- ax5.legend()
- ax6.hist(
- np.diff(meanMultiFrameTimestamp),
- bins=np.arange(0, max_frame_duration, 0.001),
- density=True,
- alpha=0.5,
- color="darkslategrey",
- label="Frame Duration",
- )
- ax6.hist(
- np.diff(meanMultiFrameTimespan),
- bins=np.arange(0, max_frame_duration, 0.001),
- density=True,
- alpha=0.5,
- color="orangered",
- label="Frame Timespan",
- )
- ax5.legend()
-
- fig_save_path = self._save_path / "recording_diagnostics.png"
- plt.savefig(str(fig_save_path))
- rich_console.log("Saving diagnostic figure to - " + str(fig_save_path))
- plt.show()
- plt.waitforbuttonpress()
- except:
- rich_console.print_exception()
- f = 9
-
- ###
- ### β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ
- ### β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ
- ### β–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ
- ### β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ
- ### β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ
- ###
-
- def __enter__(self):
- """Context manager - No need to do anything special on start"""
- return self
-
- def __exit__(self, exc_type, exc_value, exc_traceback):
- """Context manager - on exit, set `self.exit_event` to activate shutdown sequence"""
- self.create_diagnostic_images()
- return self
-
-
-###
-###
-### β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆ β–ˆβ–ˆ
-### β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ
-### β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ
-### β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ
-### β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ
-###
-###
-
-
-if __name__ == "__main__":
- pathos_mp_helper.freeze_support()
- console = Console() # create rich console to catch and print exceptions
-
- import socket
-
- this_computer_name = socket.gethostname()
-
- freemocap_data_path = None
- in_rotation_codes_list = None
- in_cams_to_use_list = None
-
- if this_computer_name == "jon-hallway-XPS-8930":
- freemocap_data_path = Path("/home/jon/Dropbox/FreeMoCapProject/FreeMocap_Data")
-
- elif this_computer_name == "DESKTOP-DCG6K4F":
- freemocap_data_path = Path(
- r"C:\Users\jonma\Dropbox\FreeMoCapProject\FreeMocap_Data"
- )
- in_rotation_codes_list = [
- "cv2.ROTATE_90_COUNTERCLOCKWISE",
- "cv2.ROTATE_90_COUNTERCLOCKWISE",
- "cv2.ROTATE_90_CLOCKWISE",
- "cv2.ROTATE_90_CLOCKWISE",
- "cv2.ROTATE_90_CLOCKWISE",
- ]
- in_cams_to_use_list = [0, 1, 2, 3, 4]
- elif this_computer_name == "DESKTOP-V3D343U":
- freemocap_data_path = Path(
- r"C:\Users\WindowsPC_Hallway\Dropbox\FreeMoCapProject\FreeMocap_Data"
- )
- elif this_computer_name == "Jons-MacBook-Pro.local":
- freemocap_data_path = Path("/Users/jon/Dropbox/FreeMoCapProject")
-
- try:
- multi_cam = FMC_MultiCamera(
- freemocap_data_folder=str(freemocap_data_path),
- save_each_cam_to_mp4=True,
- rotation_codes_list=in_rotation_codes_list,
- cams_to_use_list=in_cams_to_use_list,
- )
- multi_cam.start(standalone_mode=True)
-
- except Exception:
- console.print_exception()
diff --git a/freemocap/dev_scratchpad/dev_alpha_old/FMC_Session.py b/freemocap/dev_scratchpad/dev_alpha_old/FMC_Session.py
deleted file mode 100644
index fb6c957a..00000000
--- a/freemocap/dev_scratchpad/dev_alpha_old/FMC_Session.py
+++ /dev/null
@@ -1,283 +0,0 @@
-##
-##
-## β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆ β–ˆβ–ˆ
-## β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ
-## β–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ
-## β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ
-## β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆ
-##
-## https://patorjk.com/software/taag/#p=display&f=ANSI%20Regular&t=FMC%20Session
-
-from FMC_MultiCamera import FMC_MultiCamera
-from FMC_Visualizer import FMC_Visualizer
-
-import datetime
-from pathlib import Path
-import pickle
-
-from rich import print, inspect
-from rich.console import Console
-import numpy as np
-
-from freemocap import fmc_anipose
-from aniposelib.boards import CharucoBoard
-
-rich_console = Console()
-
-
-class FMC_Session:
- ##
- ##
- ## β–ˆβ–ˆ β–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ
- ## β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ
- ## β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ
- ## β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ
- ## β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ
- ##
- ##
-
- def __init__(self, sessionID=None, freemocap_data_folder=None, rotation_codes_list=None):
-
- if freemocap_data_path is None:
- user_home_directory = Path.home()
- self.freemocap_data_path = user_home_directory /'FreeMoCap_Data'
-
- if self.freemocap_data_path.exists():
- rich_console.log("FreeMoCap_Data folder found in User home directory - " + str(self.freemocap_data_path))
- elif not self.freemocap_data_path.exists():
- self.freemocap_data_path.mkdir(exist_ok=True)
- rich_console.log("FreeMoCap_Data CREATED in User home directory - " + str(self.freemocap_data_path))
- rich_console.rule("To create a FreeMoCap_Data folder in a different place, use `FMC_Session(freemocap_data_folder=\"path_to_folder\")`")
- else:
- self.freemocap_data_path = freemocap_data_path
-
- if sessionID is None:
- self.sessionID = datetime.datetime.now().strftime("FreeMoCap_Session_%Y-%m-%d_%H_%M_%S")
- else:
- self.sessionID = sessionID
-
- ##
- ## β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆ
- ## β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆ
- ## β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ
- ## β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ
- ## β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ
- ##
- ##
-
- def record_multi_cam(self,freemocap_data_folder=None, in_rotation_codes_list=None, cams_to_use_list=None):
- self.multi_cam = FMC_MultiCamera(
- freemocap_data_folder=str(freemocap_data_path),
- rotation_codes_list=in_rotation_codes_list,
- rec_name=self.sessionID ,
- cams_to_use_list=cams_to_use_list)
- self.multi_cam.start()
-
- ##
- ##
- ## β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ
- ## β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ
- ## β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ
- ## β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ
- ## β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ
- ##
- ##
-
- def camera_capture_volume_calibration(self, calibration_method="anipose_charuco", charucoSquareSize=36):
-
- num_charuco_rows = 7
- num_charuco_cols = 5
- num_charuco_tracked_points = (num_charuco_rows-1) * (num_charuco_cols-1)
- board = CharucoBoard(num_charuco_rows, num_charuco_cols,
- #square_length=1, # here, in mm but any unit works (JSM NOTE - just using '1' so resulting units will be in 'charuco squarelenghts`)
- #marker_length=.8,
- # square_length = 121, #big boi charuco
- # marker_length = 98,
- square_length = charucoSquareSize,#mm
- marker_length = charucoSquareSize*.8,#mm
- marker_bits=4, dict_size=250)
-
-
-
- self.synched_video_path_list = self.multi_cam._each_cam_video_filename_list
-
- video_paths_list_of_list_of_strings = []
-
- for this_path in self.synched_video_path_list:
- video_paths_list_of_list_of_strings.append([str(this_path)])#anipose needs this to be a list of lists (which is annoying by whatevs)
-
- cam_names = ['cam_'+str(cam_num) for cam_num in range(len(self.synched_video_path_list))]
-
- self.anipose_camera_calibration = fmc_anipose.CameraGroup.from_names(cam_names, fisheye=True ) # Looking through their code... it looks lke the 'fisheye=True' doesn't do much (see 2020-03-29 obsidian note)
- error,charuco_frame_data, charuco_frame_numbers = self.anipose_camera_calibration.calibrate_videos(video_paths_list_of_list_of_strings, board)
-
- print("Anipose Calibration Successful!")
-
- #save calibration info to files
- calibration_toml_filename = "{}_camera_calibration.toml".format(self.multi_cam._rec_name)
- self.camera_calibration_toml_path = self.multi_cam._save_path / calibration_toml_filename
- self.anipose_camera_calibration.dump(self.camera_calibration_toml_path)
-
- camera_calibration_info_dict = self.anipose_camera_calibration.get_dicts()
- camera_calibration_pickle_path = self.multi_cam._save_path / "{}_camera_calibration.pickle".format(self.multi_cam._rec_name)
-
- with open(str(camera_calibration_pickle_path), 'wb') as pickle_file:
- pickle.dump(camera_calibration_info_dict, pickle_file)
-
- #convert charuco data into a format that can be 3d reconstructed (effectively providing dummy data for the rest of the 3d reconstruction pipeline)
- self.charuco_nCams_nFrames_nImgPts_XY = np.empty([self.multi_cam.num_cams, self.multi_cam.num_frames, num_charuco_tracked_points, 2])
- self.charuco_nCams_nFrames_nImgPts_XY[:] = np.nan
-
-
- for this_charuco_frame_data, this_charuco_frame_num in zip(charuco_frame_data,charuco_frame_numbers):
- for this_cam_num in range(self.multi_cam.num_cams):
- try:
- self.charuco_nCams_nFrames_nImgPts_XY[this_cam_num, this_charuco_frame_num, :,:] = np.squeeze(this_charuco_frame_data[this_cam_num]["filled"])
- except:
- # print("failed frame:", frame)
- continue
- ####
- ####
- #### β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ
- #### β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ
- #### β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ
- #### β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ
- #### β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ
- ####
- ####
-
- def reconstruct3D(self, data_nCams_nFrames_nImgPts_XYC, calibration_toml_path = None, confidence_threshold=0.3):
-
- if calibration_toml_path: #if the user specified a calibration toml (from a previous Anipose-based calibration) - load it here. Otherwise, assume the calibration is included in `self`
- self.anipose_camera_calibration = fmc_anipose.CameraGroup.load(str(calibration_toml_path))
-
- num_cams, num_frames, num_img_points, num_dims = data_nCams_nFrames_nImgPts_XYC.shape
-
- if num_dims == 3: #if there are 3 dimensions, the third one is 'confidence' and can be used to threshold out low-confidence tracks
- dataOG = data_nCams_nFrames_nImgPts_XYC.copy()
-
- for camNum in range(num_cams):
-
- thisCamX = data_nCams_nFrames_nImgPts_XYC[camNum, :, :,0 ]
- thisCamY = data_nCams_nFrames_nImgPts_XYC[camNum, :, :,1 ]
- thisCamConf = data_nCams_nFrames_nImgPts_XYC[camNum, :, :, 2]
-
- thisCamX[thisCamConf < confidence_threshold] = np.nan
- thisCamY[thisCamConf < confidence_threshold] = np.nan
-
-
- if num_dims == 2:
- data_nCams_nFrames_nImgPts_XY = data_nCams_nFrames_nImgPts_XYC
- elif num_dims == 3:
- data_nCams_nFrames_nImgPts_XY = np.squeeze(data_nCams_nFrames_nImgPts_XYC[:, :, :, 0:2])
-
- dataFlat_nCams_nTotalPoints_XY = data_nCams_nFrames_nImgPts_XY.reshape(num_cams, -1, 2) # reshape data to collapse across 'frames' so it becomes [numCams, numFrames*numPoints, XY]
-
- console.print('Reconstructing 3d points...')
- data3d_flat = self.anipose_camera_calibration.triangulate(dataFlat_nCams_nTotalPoints_XY, progress=True)
-
- dataReprojerr_flat = self.anipose_camera_calibration.reprojection_error( data3d_flat, dataFlat_nCams_nTotalPoints_XY, mean=True)
-
- ##return:
- data_fr_mar_xyz = data3d_flat.reshape(num_frames, num_img_points, 3)
- dataReprojErr = dataReprojerr_flat.reshape(num_frames, num_img_points)
-
- return data_fr_mar_xyz, dataReprojErr
-
- ###
- ###
- ### β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ
- ### β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ
- ### β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆ
- ### β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ
- ### β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ
- ###
- ###
- def run_tracking_methods(self, use_media_pipe_bool=True, reconstruct3D_bool = True, save_to_npy_bool=True):
-
- if use_media_pipe_bool:
- from tracking_methods.fmc_mediapipe_alpha import run_mediapipe
-
- self.mediapipe_nCams_nFrames_nImgPts_XY = run_mediapipe(self.synched_video_path_list)
-
-
- if reconstruct3D_bool:
- self.mediapipe_nFrames_nTrackedPoints_XYZ, self.mediapipe_reprojection_error = self.reconstruct3D(self.mediapipe_nCams_nFrames_nImgPts_XY)
-
-
- if save_to_npy_bool:
- mediapipe3d_filename = self.multi_cam._save_path/'mediapipe_3d_points.npy'
- np.save(mediapipe3d_filename,self.mediapipe_nFrames_nTrackedPoints_XYZ)
-
- f=9
-
-
-
-
-
- ###
- ### β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ
- ### β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ
- ### β–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ
- ### β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ
- ### β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ
- ###
-
- def __enter__(self):
- """Context manager - No need to do anything special on start"""
- return self
-
- def __exit__(self, exc_type, exc_value, exc_traceback):
- """Context manager - no need to do anything special on stop (maybe set 'exit_event?" """
- return self
-
-###
-###
-### β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆ β–ˆβ–ˆ
-### β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ
-### β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ
-### β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ
-### β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ
-###
-###
-
-if __name__ == "__main__":
-
- import socket
- this_computer_name = socket.gethostname()
-
- console = Console()
-
- freemocap_data_path=None
- in_rotation_codes_list=None
- in_cams_to_use_list = None
- charucoSquareSize = 123
-
- if this_computer_name=='jon-hallway-XPS-8930':
- freemocap_data_path = Path('/home/jon/Dropbox/FreeMoCapProject/FreeMocap_Data')
-
- elif this_computer_name == 'DESKTOP-DCG6K4F':
- freemocap_data_path = Path(r'C:\Users\jonma\Dropbox\FreeMoCapProject\FreeMocap_Data')
- this_charucoSquareSize = 123
- in_rotation_codes_list = ['cv2.ROTATE_90_COUNTERCLOCKWISE', 'cv2.ROTATE_90_COUNTERCLOCKWISE', 'cv2.ROTATE_90_CLOCKWISE', 'cv2.ROTATE_90_CLOCKWISE', 'cv2.ROTATE_90_CLOCKWISE', ]
- in_cams_to_use_list = list(np.arange(len(in_rotation_codes_list)))
- try:
- sesh = FMC_Session(
- sessionID = None,
- freemocap_data_folder=str(freemocap_data_path),
- rotation_codes_list=in_rotation_codes_list,
- )
-
- sesh.record_multi_cam(cams_to_use_list = in_cams_to_use_list,)
- sesh.camera_capture_volume_calibration(charucoSquareSize = this_charucoSquareSize)
- sesh.charuco_nFrames_nTrackedPoints_XYZ, sesh.charuco_reprojection_error = sesh.reconstruct3D(sesh.charuco_nCams_nFrames_nImgPts_XY)
-
- charuco3d_filename = sesh.multi_cam._save_path/'charuco_3d_points.npy'
- np.save(charuco3d_filename,sesh.charuco_nFrames_nTrackedPoints_XYZ)
-
- sesh.run_tracking_methods()
- visualizer = FMC_Visualizer(fmc_session_obj=sesh)
- visualizer.start()
-
- except:
- console.print_exception()
\ No newline at end of file
diff --git a/freemocap/dev_scratchpad/dev_alpha_old/FMC_Visualizer.py b/freemocap/dev_scratchpad/dev_alpha_old/FMC_Visualizer.py
deleted file mode 100644
index 8e57aeef..00000000
--- a/freemocap/dev_scratchpad/dev_alpha_old/FMC_Visualizer.py
+++ /dev/null
@@ -1,169 +0,0 @@
-# -*- coding: utf-8 -*-
-"""
-built off the '3D Graphics- Scatter Plot' example from `python -m pyqtgraph.examples`
-"""
-from pathlib import Path
-import sys
-
-import pyqtgraph as pg
-from pyqtgraph import functions as fn
-from pyqtgraph.Qt import QtCore, QtGui
-import pyqtgraph.opengl as gl
-import numpy as np
-
-
-class FMC_Visualizer:
- def __init__(self, fmc_session_obj = None, recording_session_path = None):
-
- #setup QT app window
- self.app = pg.mkQApp("FreeMoCap Data Visualizer")
- self.gl_view_widget = gl.GLViewWidget()
- self.gl_view_widget.show()
- self.gl_view_widget.setWindowTitle('FreeMoCap Data Visualizer')
- self.gl_view_widget.setCameraPosition(distance=10, elevation=-90, azimuth=-90)
-
- grid_distance = 10
- gl_x_plane_grid_item = gl.GLGridItem()
- gl_x_plane_grid_item.rotate(90, 0, 1, 0)
- gl_x_plane_grid_item.translate(grid_distance, 0, 0)
- self.gl_view_widget.addItem(gl_x_plane_grid_item)
-
- gl_y_plane_grid_item = gl.GLGridItem()
- gl_y_plane_grid_item.rotate(90, 1, 0, 0)
- gl_y_plane_grid_item.translate(0, grid_distance, 0)
- self.gl_view_widget.addItem(gl_y_plane_grid_item)
-
- gl_z_plane_grid_item = gl.GLGridItem()
- gl_z_plane_grid_item.translate(0, 0, grid_distance)
- self.gl_view_widget.addItem(gl_z_plane_grid_item)
-
- origin_location_array = np.array([0,0, 0])
- x_axis_line_array = np.array([[0,0, 0], [1,0,0]])
- y_axis_line_array = np.array([[0,0, 0], [0,1,0]])
- z_axis_line_array = np.array([[0,0, 0], [0,0,1]])
-
- # self.origin_location_scatter_item = gl.GLScatterPlotItem(pos=origin_location_array, color=(1,1,1,1), size=.1, pxMode=False)
- self.origin_x_axis_gl_lineplot_item = gl.GLLinePlotItem(pos=x_axis_line_array, color=(1,0,0,1), width=1., antialias=True)
- self.origin_y_axis_gl_lineplot_item = gl.GLLinePlotItem(pos=y_axis_line_array, color=(0,1,0,1), width=1., antialias=True)
- self.origin_z_axis_gl_lineplot_item = gl.GLLinePlotItem(pos=z_axis_line_array, color=(0,0,1,1), width=1., antialias=True)
-
- # self.gl_view_widget.addItem(self.origin_location_scatter_item)
- self.gl_view_widget.addItem(self.origin_x_axis_gl_lineplot_item)
- self.gl_view_widget.addItem(self.origin_y_axis_gl_lineplot_item)
- self.gl_view_widget.addItem(self.origin_z_axis_gl_lineplot_item)
-
- if fmc_session_obj is None:
- if recording_session_path:
- self.recording_session_path = Path(recording_session_path)
- else:
- #JSM NOTE - add something to load the last recorded session if nothing is specified
- pass
-
- # load charuco data
- self.charuco_3d_path = self.recording_session_path / "charuco_3d_points.npy"
- self.charuco_nFrames_nTrackedPoints_XYZ = np.load(str(self.charuco_3d_path))
- self.charuco_nFrames_nTrackedPoints_XYZ = self.charuco_nFrames_nTrackedPoints_XYZ/1000 #convert to meters
-
- # load mediapipe data
- self.mediapipe_3d_path = self.recording_session_path / "mediapipe_3d_points.npy"
- self.mediapipe_nFrames_nTrackedPoints_XYZ = np.load(str(self.mediapipe_3d_path))
- self.mediapipe_nFrames_nTrackedPoints_XYZ = self.mediapipe_nFrames_nTrackedPoints_XYZ/1000 #convert to meters
- else:
- # load charuco data
- self.charuco_nFrames_nTrackedPoints_XYZ = fmc_session_obj.charuco_nFrames_nTrackedPoints_XYZ/1000 #convert to meters
-
- # load mediapipe data
- self.mediapipe_nFrames_nTrackedPoints_XYZ = fmc_session_obj.mediapipe_nFrames_nTrackedPoints_XYZ/1000 #convert to meters
-
- self.frame_num = 0
- self.num_frames = self.charuco_nFrames_nTrackedPoints_XYZ.shape[0]
-
-
- self.charuco_gl_scatter_item = gl.GLScatterPlotItem(pos=self.charuco_nFrames_nTrackedPoints_XYZ[self.frame_num,:,:], color=(1,1,1,.3), size=.1, pxMode=False)
- self.gl_view_widget.addItem(self.charuco_gl_scatter_item)
-
- self.charuco_gl_lineplot_item = gl.GLLinePlotItem(pos=self.charuco_nFrames_nTrackedPoints_XYZ[self.frame_num,:,:], color=(0,1,1,1), width=1., antialias=True)
- self.gl_view_widget.addItem(self.charuco_gl_lineplot_item)
-
-
- # Plot Media Pipe stuff
- self.mediapipe_gl_scatter_item = gl.GLScatterPlotItem(pos=self.mediapipe_nFrames_nTrackedPoints_XYZ[self.frame_num,:,:], color=(1,0,1,.3), size=.025, pxMode=False)
- self.gl_view_widget.addItem(self.mediapipe_gl_scatter_item)
-
- #mediapipe body connect-the-dots order
- self.mediapipe_head_indexes = [8, 6, 5, 4, 0, 10, 9, 0, 1, 2, 3, 7 ]
- self.mediapipe_tors_indexes = [12, 11, 24, 23, 12]
- self.mediapipe_rArm_indexes = [12, 14, 16, 18, 20, 16, 22 ]
- self.mediapipe_lArm_indexes = [11, 13, 15, 17, 19, 15, 21]
- self.mediapipe_rLeg_indexes = [24, 26, 28, 30, 32, 28, ]
- self.mediapipe_lLeg_indexes = [23, 25, 27, 29, 31, 27, ]
-
- rHandIDstart = 33
- lHandIDstart = 54
- mediapipe_hand_indexes = [0,1,2,3,4,3,2,1,0,5,6,7,8,7,6,5,9,10,11,12,11,10,9,13,14,15,16,15,14,13,17,18,19,20,19,18,17,0]
-
-
- self.mediapipe_rHand_indexes = [this_index + rHandIDstart for this_index in mediapipe_hand_indexes]
- self.mediapipe_lHand_indexes = [this_index + lHandIDstart for this_index in mediapipe_hand_indexes]
-
- self.mediapipe_head_gl_lineplot_item = gl.GLLinePlotItem(pos=self.mediapipe_nFrames_nTrackedPoints_XYZ[self.frame_num,self.mediapipe_head_indexes,:], color=(1,0,1,1), width=1., antialias=True)
- self.mediapipe_tors_gl_lineplot_item = gl.GLLinePlotItem(pos=self.mediapipe_nFrames_nTrackedPoints_XYZ[self.frame_num,self.mediapipe_tors_indexes,:], color=(1,0,1,1), width=1., antialias=True)
- self.mediapipe_rArm_gl_lineplot_item = gl.GLLinePlotItem(pos=self.mediapipe_nFrames_nTrackedPoints_XYZ[self.frame_num,self.mediapipe_rArm_indexes,:], color=(1,0,1,1), width=1., antialias=True)
- self.mediapipe_lArm_gl_lineplot_item = gl.GLLinePlotItem(pos=self.mediapipe_nFrames_nTrackedPoints_XYZ[self.frame_num,self.mediapipe_lArm_indexes,:], color=(1,0,1,1), width=1., antialias=True)
- self.mediapipe_rLeg_gl_lineplot_item = gl.GLLinePlotItem(pos=self.mediapipe_nFrames_nTrackedPoints_XYZ[self.frame_num,self.mediapipe_rLeg_indexes,:], color=(1,0,1,1), width=1., antialias=True)
- self.mediapipe_lLeg_gl_lineplot_item = gl.GLLinePlotItem(pos=self.mediapipe_nFrames_nTrackedPoints_XYZ[self.frame_num,self.mediapipe_lLeg_indexes,:], color=(1,0,1,1), width=1., antialias=True)
-
- self.mediapipe_rHand_gl_lineplot_item = gl.GLLinePlotItem(pos=self.mediapipe_nFrames_nTrackedPoints_XYZ[self.frame_num,self.mediapipe_rHand_indexes,:], color=(1,1,0,1), width=2., antialias=True)
- self.mediapipe_lHand_gl_lineplot_item = gl.GLLinePlotItem(pos=self.mediapipe_nFrames_nTrackedPoints_XYZ[self.frame_num,self.mediapipe_lHand_indexes,:], color=(0,1,1,1), width=2., antialias=True)
-
-
- self.gl_view_widget.addItem(self.mediapipe_head_gl_lineplot_item)
- self.gl_view_widget.addItem(self.mediapipe_tors_gl_lineplot_item)
- self.gl_view_widget.addItem(self.mediapipe_rArm_gl_lineplot_item)
- self.gl_view_widget.addItem(self.mediapipe_lArm_gl_lineplot_item)
- self.gl_view_widget.addItem(self.mediapipe_rLeg_gl_lineplot_item)
- self.gl_view_widget.addItem(self.mediapipe_lLeg_gl_lineplot_item)
- self.gl_view_widget.addItem(self.mediapipe_rHand_gl_lineplot_item)
- self.gl_view_widget.addItem(self.mediapipe_lHand_gl_lineplot_item)
-
-
- self.qt_timer = QtCore.QTimer()
- self.qt_timer.timeout.connect(self.update)
- self.qt_timer.start(50)
-
-
-
- def update(self):
-
- self.frame_num +=1
- if self.frame_num > self.num_frames:
- self.frame_num = 0
-
-
- self.charuco_gl_scatter_item.setData(pos=self.charuco_nFrames_nTrackedPoints_XYZ[self.frame_num,:,:])
- self.charuco_gl_lineplot_item.setData(pos=self.charuco_nFrames_nTrackedPoints_XYZ[self.frame_num,:,:])
-
- self.mediapipe_gl_scatter_item.setData(pos=self.mediapipe_nFrames_nTrackedPoints_XYZ[self.frame_num,:,:])
-
- self.mediapipe_head_gl_lineplot_item.setData(pos=self.mediapipe_nFrames_nTrackedPoints_XYZ[self.frame_num, self.mediapipe_head_indexes,:])
- self.mediapipe_tors_gl_lineplot_item.setData(pos=self.mediapipe_nFrames_nTrackedPoints_XYZ[self.frame_num, self.mediapipe_tors_indexes,:])
- self.mediapipe_rArm_gl_lineplot_item.setData(pos=self.mediapipe_nFrames_nTrackedPoints_XYZ[self.frame_num, self.mediapipe_rArm_indexes,:])
- self.mediapipe_lArm_gl_lineplot_item.setData(pos=self.mediapipe_nFrames_nTrackedPoints_XYZ[self.frame_num, self.mediapipe_lArm_indexes,:])
- self.mediapipe_rLeg_gl_lineplot_item.setData(pos=self.mediapipe_nFrames_nTrackedPoints_XYZ[self.frame_num, self.mediapipe_rLeg_indexes,:])
- self.mediapipe_lLeg_gl_lineplot_item.setData(pos=self.mediapipe_nFrames_nTrackedPoints_XYZ[self.frame_num, self.mediapipe_lLeg_indexes,:])
-
- self.mediapipe_rHand_gl_lineplot_item.setData(pos=self.mediapipe_nFrames_nTrackedPoints_XYZ[self.frame_num, self.mediapipe_rHand_indexes,:])
- self.mediapipe_lHand_gl_lineplot_item.setData(pos=self.mediapipe_nFrames_nTrackedPoints_XYZ[self.frame_num, self.mediapipe_lHand_indexes,:])
-
- if self.frame_num % 10 == 0:
- print("Frame Num : " + str(self.frame_num) + " - ViewPoint - Distance: " + str(self.gl_view_widget.opts['distance']) + " Elevation: " + str(self.gl_view_widget.opts['elevation']) + " Azimuth: " + str(self.gl_view_widget.opts['azimuth']) )
-
- def start(self):
- if (sys.flags.interactive != 1) or not hasattr(QtCore, "PYQT_VERSION"):
- QtGui.QApplication.instance().exec_()
-
-
-if __name__ == '__main__':
- visualizer = FMC_Visualizer(recording_session_path = "C:/Users/jonma/Dropbox/FreeMoCapProject/FreeMocap_Data/FreeMoCap_Session_2021-12-09_11_05_31")
- visualizer.start()
-
diff --git a/freemocap/dev_scratchpad/dev_alpha_old/__init__.py b/freemocap/dev_scratchpad/dev_alpha_old/__init__.py
deleted file mode 100644
index e69de29b..00000000
diff --git a/freemocap/dev_scratchpad/dev_alpha_old/capture_volume_calibration.py b/freemocap/dev_scratchpad/dev_alpha_old/capture_volume_calibration.py
deleted file mode 100644
index 7a6666e5..00000000
--- a/freemocap/dev_scratchpad/dev_alpha_old/capture_volume_calibration.py
+++ /dev/null
@@ -1,326 +0,0 @@
-from rich import print
-from rich.console import Console
-from FMC_MultiCamera import FMC_MultiCamera
-import socket
-from pathlib import Path
-from pathos.helpers import mp as pathos_mp_helper
-import cv2
-from copy import deepcopy
-import numpy as np
-
-from itertools import combinations
-
-import matplotlib.pyplot as plt
-
-aruco_dict = cv2.aruco.Dictionary_get(cv2.aruco.DICT_4X4_250)
-charuco_length = 7
-charuco_width = 5
-
-board = cv2.aruco.CharucoBoard_create(charuco_length, charuco_width, 1, 0.8, aruco_dict)
-num_charuco_corners = (charuco_length - 1) * (charuco_width - 1)
-
-
-def detect_charuco_board(image):
- """
- Charuco base pose estimation.
- more-or-less copied from - https://mecaruco2.readthedocs.io/en/latest/notebooks_rst/Aruco/sandbox/ludovic/aruco_calibration_rotation.html
- """
- charuco_corners = []
- charuco_ids = []
-
- # SUB PIXEL CORNER DETECTION CRITERION
- criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 100, 0.00001)
-
- gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
- aruco_square_corners, aruco_square_ids, rejectedImgPoints = cv2.aruco.detectMarkers(
- gray, aruco_dict
- )
-
- if len(aruco_square_corners) > 0:
- # SUB PIXEL DETECTION
- for this_corner in aruco_square_corners:
- cv2.cornerSubPix(
- gray, this_corner, winSize=(3, 3), zeroZone=(-1, -1), criteria=criteria
- )
- res2 = cv2.aruco.interpolateCornersCharuco(
- aruco_square_corners, aruco_square_ids, gray, board
- )
-
- if res2[1] is not None and res2[2] is not None and len(res2[1]) > 3:
- charuco_corners = res2[1]
- charuco_ids = res2[2]
-
- return charuco_corners, charuco_ids, aruco_square_corners, aruco_square_ids
-
-
-if __name__ == "__main__":
- pathos_mp_helper.freeze_support()
-
- console = Console() # create rich console to catch and print exceptions
-
- this_computer_name = socket.gethostname()
-
- freemocap_data_path = None
- in_rotation_codes_list = None
- in_cams_to_use_list = None
-
- if this_computer_name == "jon-hallway-XPS-8930":
- freemocap_data_path = Path("/home/jon/Dropbox/FreeMoCapProject/FreeMocap_Data")
- in_rotation_codes_list = [
- "cv2.ROTATE_90_COUNTERCLOCKWISE",
- "cv2.ROTATE_90_COUNTERCLOCKWISE",
- "cv2.ROTATE_90_CLOCKWISE",
- "cv2.ROTATE_90_CLOCKWISE",
- "cv2.ROTATE_90_CLOCKWISE",
- ]
- elif this_computer_name == "DESKTOP-DCG6K4F":
- freemocap_data_path = Path(
- r"C:\Users\jonma\Dropbox\FreeMoCapProject\FreeMocap_Data"
- )
- elif this_computer_name == "DESKTOP-V3D343U":
- freemocap_data_path = Path(
- r"C:\Users\WindowsPC_Hallway\Dropbox\FreeMoCapProject\FreeMocap_Data"
- )
- in_cams_to_use_list = [0, 1, 2, 3]
- elif this_computer_name == "Jons-MacBook-Pro.local":
- freemocap_data_path = Path("/Users/jon/Dropbox/FreeMoCapProject")
-
- try:
- multi_cam = FMC_MultiCamera(
- cams_to_use_list=in_cams_to_use_list,
- show_multi_cam_stream_bool=False,
- freemocap_data_folder=str(freemocap_data_path),
- rotation_codes_list=in_rotation_codes_list,
- )
- multi_cam.start()
-
- console.rule("Launching Multi Cam Viewer")
- current_loop_count = 0
- aruco_square_corners = [[] for _ in range(multi_cam.num_cams)]
- aruco_square_ids = [np.array([]) for _ in range(multi_cam.num_cams)]
- charuco_corners = [np.array([]) for _ in range(multi_cam.num_cams)]
- charuco_ids = [np.array([]) for _ in range(multi_cam.num_cams)]
-
- camera_pair_list = list(combinations(np.arange(multi_cam.num_cams), 2))
- camera_pair_joint_view_count = [0 for _ in range(len(camera_pair_list))]
- each_cameras_shared_board_view_count_array = np.zeros(
- (multi_cam.num_cams, multi_cam.num_cams)
- )
- each_cameras_shared_board_view_count_total = np.zeros(multi_cam.num_cams)
-
- charuco_points_from_previous_frames = [[] for _ in range(multi_cam.num_cams)]
-
- multi_cam_queue_size_list = []
-
- # #set up plots
- # plt.ion()
- # fig = plt.figure()
- # ax_queue_size = plt.subplot(121, title='Multi Camera - Queueue Size', xlabel='Frame# I guess/? Maybe Loop#/?', ylabel='Multi frames in queue')
- # ax_shared_views = plt.subplot(122, title='Shared Charuco Board Views', xlabel='Frame#/?', ylabel='Number of shared views')
-
- # artist_for_queue_trace = ax_queue_size.plot(0)
-
- # artists_for_shared_view_traces_list = []
- # for this_cam_num in range(multi_cam.num_cams):
- # artists_for_shared_view_traces_list.append(ax_shared_views.plot(0, label=f'Cam {this_cam_num}'))
- # ax_shared_views.legend()
-
- while not multi_cam.exit_event.is_set():
- if not multi_cam.multi_cam_tuple_queue.empty():
-
- this_multi_cam_tuple = multi_cam.multi_cam_tuple_queue.get()
- current_loop_count += 1
-
- # multi_cam.save_synchronized_videos(this_multi_cam_tuple)
-
- # this_multi_cam_image_raw = multi_cam.stitch_multicam_image(this_multi_cam_tuple)
-
- # if multi_cam._save_multi_cam_to_mp4:
- # if multi_cam._output_multi_cam_video_object is None:
- # multi_cam.initialize_multi_cam_output_video(this_multi_cam_image_raw)
-
- # multi_cam._output_multi_cam_video_object.write(this_multi_cam_image_raw)
-
- if multi_cam._save_each_cam_to_mp4:
- if multi_cam._each_cam_video_writer_object_list is None:
- multi_cam.initialize_each_cam_output_video(this_multi_cam_tuple)
-
- for this_cam_num in range(multi_cam.num_cams):
- multi_cam._each_cam_video_writer_object_list[
- this_cam_num
- ].write(this_multi_cam_tuple[this_cam_num][1])
-
- new_cam_image_list = []
- full_charuco_detected_on_this_frame = [
- False for _ in range(multi_cam.num_cams)
- ]
-
- for this_cam_num in range(multi_cam.num_cams):
- this_cam_tuple = this_multi_cam_tuple[this_cam_num]
- this_cam_image = this_cam_tuple[1]
-
- if current_loop_count % 10 == 0:
- (
- charuco_corners[this_cam_num],
- charuco_ids[this_cam_num],
- aruco_square_corners[this_cam_num],
- aruco_square_ids[this_cam_num],
- ) = detect_charuco_board(this_cam_image)
-
- if len(charuco_ids[this_cam_num]) == num_charuco_corners:
- full_charuco_detected_on_this_frame[this_cam_num] = True
-
- # image_w_markers = cv2.aruco.drawDetectedMarkers(this_cam_image, aruco_square_corners[this_cam_num], aruco_square_ids[this_cam_num])
-
- image_w_markers = cv2.aruco.drawDetectedCornersCharuco(
- this_cam_image,
- np.array(charuco_corners[this_cam_num]),
- np.array(charuco_ids[this_cam_num]),
- )
-
- this_cam_name = "Camera " + str(this_cam_num)
-
- text_to_write_on_this_camera = ""
- current_cam_corner_count_str = (
- this_cam_name
- + ": "
- + str(len(charuco_ids[this_cam_num]))
- + " of "
- + str(num_charuco_corners)
- + " detected | Full Board: "
- + str(full_charuco_detected_on_this_frame[this_cam_num])
- )
- this_cam_shared_views_str = " | Shared Views: " + str(
- each_cameras_shared_board_view_count_total[this_cam_num]
- )
- text_to_write_on_this_camera = (
- current_cam_corner_count_str + this_cam_shared_views_str
- )
-
- if this_cam_num == 0:
- queue_size_str = "Multi-Camera Queue Size: " + str(
- multi_cam.multi_cam_tuple_queue.qsize()
- )
- queue_text_position = (10, 20)
- cv2.putText(
- image_w_markers, # numpy array on which text is written
- queue_size_str, # text
- queue_text_position, # position at which writing has to start
- cv2.FONT_HERSHEY_SIMPLEX, # font family
- 0.5, # font size
- (255, 10, 100, 255), # font color
- 2,
- ) # font stroke
- cv2.putText(
- image_w_markers, # numpy array on which text is written
- queue_size_str, # text
- queue_text_position, # position at which writing has to start
- cv2.FONT_HERSHEY_SIMPLEX, # font family
- 0.5, # font size
- (30, 10, 0, 255), # font color
- 3,
- ) # font stroke
-
- position = (10, 50)
- cv2.putText(
- image_w_markers, # numpy array on which text is written
- text_to_write_on_this_camera, # text
- position, # position at which writing has to start
- cv2.FONT_HERSHEY_SIMPLEX, # font family
- 0.5, # font size
- (30, 10, 0, 255), # font color
- 3,
- ) # font stroke
- cv2.putText(
- image_w_markers, # numpy array on which text is written
- text_to_write_on_this_camera, # text
- position, # position at which writing has to start
- cv2.FONT_HERSHEY_SIMPLEX, # font family
- 0.5, # font size
- (209, 180, 0, 255), # font color
- 1,
- ) # font stroke
-
- if full_charuco_detected_on_this_frame[this_cam_num]:
- cv2.polylines(
- image_w_markers,
- np.int32([charuco_corners[this_cam_num]]),
- True,
- (0, 100, 255),
- 2,
- )
- # for these_corners in charuco_points_from_previous_frames[this_cam_num]:
- # if len(these_corners)>0:
- # cv2.polylines(image_w_markers, np.int32([these_corners[this_cam_num]]), True, (0,100,255,255/2), 2)
-
- charuco_points_from_previous_frames[this_cam_num].append(
- charuco_corners[this_cam_num]
- )
-
- new_cam_image_list.append(this_cam_image)
-
- # determine paired board views
- for this_cam_num in range(multi_cam.num_cams):
- if full_charuco_detected_on_this_frame[this_cam_num]:
- for this_other_camera_num in range(multi_cam.num_cams):
- if this_other_camera_num != this_cam_num:
- if full_charuco_detected_on_this_frame[
- this_other_camera_num
- ]:
- each_cameras_shared_board_view_count_array[
- this_cam_num, this_other_camera_num
- ] += 1
- each_cameras_shared_board_view_count_total = np.sum(
- each_cameras_shared_board_view_count_array, axis=1
- )
- # print(each_cameras_shared_board_view_count)
-
- for this_pair_num, this_cam_pair in enumerate(camera_pair_list):
- camera_one_id = this_cam_pair[0]
- camera_two_id = this_cam_pair[1]
-
- if (
- full_charuco_detected_on_this_frame[camera_one_id]
- and full_charuco_detected_on_this_frame[camera_two_id]
- ):
- camera_pair_joint_view_count[this_pair_num] += 1
-
- # update plots
- multi_cam_queue_size_list.append(
- multi_cam.multi_cam_tuple_queue.qsize()
- )
-
- # artist_for_queue_trace[0].set_data((np.arange(current_loop_count),multi_cam_queue_size_list))
- # plt.pause(0.01)
- # plt.draw()
- # for camNum in range(multi_cam.num_cams):
- # ax_shared_views.plot(0, label=f'Cam {camNum}')
-
- multi_cam_image = np.hstack(new_cam_image_list)
-
- cv2.imshow(multi_cam._rec_name, multi_cam_image)
-
- key = cv2.waitKey(1)
-
- if key == 27: # exit on ESC
- break
-
- if (
- cv2.getWindowProperty(multi_cam._rec_name, cv2.WND_PROP_VISIBLE) < 1
- ): # break loop if window closed
- break
-
- cv2.destroyAllWindows()
-
- if multi_cam._save_multi_cam_to_mp4:
- multi_cam._output_multi_cam_video_object.release()
-
- if multi_cam._save_each_cam_to_mp4:
- for this_cam_num in range(multi_cam.num_cams):
- multi_cam._each_cam_video_writer_object_list[this_cam_num].release()
-
- console.rule("Shutting down MultiCamera Viewer")
- multi_cam.exit_event.set() # send the 'Exit' signal to everyone.
-
- except Exception:
- console.print_exception()
diff --git a/freemocap/dev_scratchpad/dev_alpha_old/default_json_definitions/freemocap_mediapipe_json.json b/freemocap/dev_scratchpad/dev_alpha_old/default_json_definitions/freemocap_mediapipe_json.json
deleted file mode 100644
index 72880b7b..00000000
--- a/freemocap/dev_scratchpad/dev_alpha_old/default_json_definitions/freemocap_mediapipe_json.json
+++ /dev/null
@@ -1,735 +0,0 @@
-{
- "body": {
- "body_mass_segments": {
- "head": {
- "parent": "neck",
- "child": "head_center",
- "anthropometric_definition": {
- "proportional_length": 0.064,
- "proportional_mass": 0.081,
- "center_of_mass_proximal": 0,
- "center_of_mass_distal": 1
- },
- "spherical_joint_limits": {
- "azimuth": [
- 0,
- 180
- ],
- "elevation": [
- 0,
- 180
- ]
- }
- },
- "torso": {
- "parent": "neck",
- "child": "sacrum",
- "anthropometric_definition": {
- "proportional_length": 0.288,
- "proportional_mass": 0.497,
- "center_of_mass_proximal": 50,
- "center_of_mass_distal": 50
- },
- "spherical_joint_limits": {
- "azimuth": [
- 0,
- 180
- ],
- "elevation": [
- 0,
- 180
- ]
- }
- },
- "right_clavicle": {
- "parent": "neck",
- "child": "right_shoulder",
- "anthropometric_definition": {
- "proportional_length": 0.129,
- "proportional_mass": null,
- "center_of_mass_proximal": 0.712,
- "center_of_mass_distal": 0.288
- },
- "spherical_joint_limits": {
- "azimuth": [
- 0,
- 360
- ],
- "elevation": [
- 0,
- 360
- ]
- }
- },
- "right_upper_arm": {
- "parent": "right_shoulder",
- "child": "right_elbow",
- "anthropometric_definition": {
- "proportional_length": 0.186,
- "proportional_mass": 0.028,
- "center_of_mass_proximal": 0.436,
- "center_of_mass_distal": 0.564
- },
- "spherical_joint_limits": {
- "azimuth": [
- 0,
- 360
- ],
- "elevation": [
- 0,
- 360
- ]
- }
- },
- "right_lower_arm": {
- "parent": "right_elbow",
- "child": "right_wrist",
- "anthropometric_definition": {
- "proportional_length": 0.146,
- "proportional_mass": 0.016,
- "center_of_mass_proximal": 0.43,
- "center_of_mass_distal": 0.57
- },
- "spherical_joint_limits": {
- "azimuth": [
- 0,
- 360
- ],
- "elevation": [
- 0,
- 360
- ]
- }
- },
- "right_hand": {
- "parent": "right_wrist",
- "child": "right_hand_middle_knuckle",
- "anthropometric_definition": {
- "proportional_length": 0.108,
- "proportional_mass": 0.006,
- "center_of_mass_proximal": 0.506,
- "center_of_mass_distal": 0.494
- },
- "spherical_joint_limits": {
- "azimuth": [
- 0,
- 360
- ],
- "elevation": [
- 0,
- 360
- ]
- }
- },
- "right_hip": {
- "parent": "sacrum",
- "child": "right_hip",
- "anthropometric_definition": {
- "proportional_length": 0.096,
- "proportional_mass": 0.071,
- "center_of_mass_proximal": 0.5,
- "center_of_mass_distal": 0.5
- },
- "spherical_joint_limits": {
- "azimuth": [
- 0,
- 360
- ],
- "elevation": [
- 0,
- 360
- ]
- }
- },
- "right_upper_leg": {
- "parent": "right_hip",
- "child": "right_knee",
- "anthropometric_definition": {
- "proportional_length": 0.245,
- "proportional_mass": 0.1,
- "center_of_mass_proximal": 0.433,
- "center_of_mass_distal": 0.567
- },
- "spherical_joint_limits": {
- "azimuth": [
- 0,
- 360
- ],
- "elevation": [
- 0,
- 360
- ]
- }
- },
- "right_lower_leg": {
- "parent": "right_knee",
- "child": "right_ankle",
- "anthropometric_definition": {
- "proportional_length": 0.246,
- "proportional_mass": 0.0456,
- "center_of_mass_proximal": 0.433,
- "center_of_mass_distal": 0.567
- },
- "spherical_joint_limits": {
- "azimuth": [
- 0,
- 360
- ],
- "elevation": [
- 0,
- 360
- ]
- }
- },
- "right_thumb": {
- "parent": "right_wrist",
- "child": "right_thumb",
- "anthropometric_definition": {
- "proportional_length": 0.05,
- "proportional_mass": null,
- "center_of_mass_proximal": 0.5,
- "center_of_mass_distal": 0.5
- },
- "spherical_joint_limits": {
- "azimuth": [
- 0,
- 360
- ],
- "elevation": [
- 0,
- 360
- ]
- }
- },
- "right_foot ": {
- "parent": "right_ankle",
- "child": "right_foot_index",
- "anthropometric_definition": {
- "proportional_length": 0.152,
- "proportional_mass": 0.0145,
- "center_of_mass_proximal": 0.5,
- "center_of_mass_distal": 0.5
- },
- "spherical_joint_limits": {
- "azimuth": [
- 0,
- 360
- ],
- "elevation": [
- 0,
- 360
- ]
- }
- },
- "left_clavicle": {
- "parent": "neck",
- "child": "left_shoulder",
- "anthropometric_definition": {
- "proportional_length": 0.129,
- "proportional_mass": null,
- "center_of_mass_proximal": 0.712,
- "center_of_mass_distal": 0.288
- },
- "spherical_joint_limits": {
- "azimuth": [
- 0,
- 360
- ],
- "elevation": [
- 0,
- 360
- ]
- }
- },
- "left_upper_arm": {
- "parent": "left_shoulder",
- "child": "left_elbow",
- "anthropometric_definition": {
- "proportional_length": 0.186,
- "proportional_mass": 0.028,
- "center_of_mass_proximal": 0.436,
- "center_of_mass_distal": 0.564
- },
- "spherical_joint_limits": {
- "azimuth": [
- 0,
- 360
- ],
- "elevation": [
- 0,
- 360
- ]
- }
- },
- "left_lower_arm": {
- "parent": "left_elbow",
- "child": "left_wrist",
- "anthropometric_definition": {
- "proportional_length": 0.146,
- "proportional_mass": 0.016,
- "center_of_mass_proximal": 0.43,
- "center_of_mass_distal": 0.57
- },
- "spherical_joint_limits": {
- "azimuth": [
- 0,
- 360
- ],
- "elevation": [
- 0,
- 360
- ]
- }
- },
- "left_hand": {
- "parent": "left_wrist",
- "child": "left_hand_middle_knuckle",
- "anthropometric_definition": {
- "proportional_length": 0.108,
- "proportional_mass": 0.006,
- "center_of_mass_proximal": 0.506,
- "center_of_mass_distal": 0.494
- },
- "spherical_joint_limits": {
- "azimuth": [
- 0,
- 360
- ],
- "elevation": [
- 0,
- 360
- ]
- }
- },
- "left_thumb": {
- "parent": "left_wrist",
- "child": "left_thumb",
- "anthropometric_definition": {
- "proportional_length": 0.05,
- "proportional_mass": null,
- "center_of_mass_proximal": 0.5,
- "center_of_mass_distal": 0.5
- },
- "spherical_joint_limits": {
- "azimuth": [
- 0,
- 360
- ],
- "elevation": [
- 0,
- 360
- ]
- }
- },
- "left_hip": {
- "parent": "sacrum",
- "child": "left_hip",
- "anthropometric_definition": {
- "proportional_length": 0.096,
- "proportional_mass": 0.071,
- "center_of_mass_proximal": 0.5,
- "center_of_mass_distal": 0.5
- },
- "spherical_joint_limits": {
- "azimuth": [
- 0,
- 360
- ],
- "elevation": [
- 0,
- 360
- ]
- }
- },
- "left_upper_leg": {
- "parent": "left_hip",
- "child": "left_knee",
- "anthropometric_definition": {
- "proportional_length": 0.245,
- "proportional_mass": 0.1,
- "center_of_mass_proximal": 0.433,
- "center_of_mass_distal": 0.567
- },
- "spherical_joint_limits": {
- "azimuth": [
- 0,
- 360
- ],
- "elevation": [
- 0,
- 360
- ]
- }
- },
- "left_lower_leg": {
- "parent": "left_knee",
- "child": "left_ankle",
- "anthropometric_definition": {
- "proportional_length": 0.246,
- "proportional_mass": 0.0456,
- "center_of_mass_proximal": 0.433,
- "center_of_mass_distal": 0.567
- },
- "spherical_joint_limits": {
- "azimuth": [
- 0,
- 360
- ],
- "elevation": [
- 0,
- 360
- ]
- }
- },
- "left_foot ": {
- "parent": "left_ankle",
- "child": "left_foot_index",
- "anthropometric_definition": {
- "proportional_length": 0.152,
- "proportional_mass": 0.0145,
- "center_of_mass_proximal": 0.5,
- "center_of_mass_distal": 0.5
- },
- "spherical_joint_limits": {
- "azimuth": [
- 0,
- 360
- ],
- "elevation": [
- 0,
- 360
- ]
- }
- }
- },
- "virtual_markers": {
- "head_center": {
- "left_ear": 0.333,
- "right_ear": 0.333,
- "nose": 0.334
- },
- "neck": {
- "left_shoulder": 0.5,
- "right_shoulder": 0.5
- },
- "sacrum": {
- "left_hip": 0.5,
- "right_hip": 0.5
- },
- "left_hand_middle_knuckle": {
- "left_index": 0.5,
- "left_pinky": 0.5
- },
- "right_hand_middle_knuckle": {
- "right_index": 0.5,
- "right_pinky": 0.5
- },
- "center_of_mass": {
- "etc": 0.9
- }
- },
- "tracked_point_names": [
- "nose",
- "left_eye_inner",
- "left_eye",
- "left_eye_outer",
- "right_eye_inner",
- "right_eye",
- "right_eye_outer",
- "left_ear",
- "right_ear",
- "mouth_left",
- "mouth_right",
- "left_shoulder",
- "right_shoulder",
- "left_elbow",
- "right_elbow",
- "left_wrist",
- "right_wrist",
- "left_pinky",
- "right_pinky",
- "left_index",
- "right_index",
- "left_thumb",
- "right_thumb",
- "left_hip",
- "right_hip",
- "left_knee",
- "right_knee",
- "right_ankle",
- "left_ankle",
- "left_heel",
- "right_heel",
- "left_foot_index",
- "right_foot_index"
- ],
- "tracked_point_to_rigify_fk_rig_bone_connections":{
- "nose": {
- "head": {
- "track_type":"bone_tail",
- "weight":1.0
- },
- "left_eye_inner": {},
- "left_eye": {},
- "left_eye_outer": {},
- "right_eye_inner": {},
- "right_eye": {},
- "right_eye_outer": {},
- "left_ear": {},
- "right_ear": {},
- "mouth_left": {},
- "mouth_right": {},
- "left_shoulder": {
- "shoulder.L": {
- "track_type":"bone_tail",
- "weight":1.0
- },
- "upper_arm.L": {
- "track_type":"bone_head",
- "weight":1.0
- }
- },
- "right_shoulder": {
- "shoulder.R": {
- "track_type":"bone_tail",
- "weight":1.0
- },
- "upper_arm.R": {
- "track_type":"bone_head",
- "weight":1.0
- }
- },
- "left_elbow": {
- "upper_arm.L": {
- "track_type":"bone_tail",
- "weight":1.0
- },
- "forearm.L": {
- "track_type":"bone_head",
- "weight":1.0
- }
- },
- "right_elbow": {
- "upper_arm.R": {
- "track_type":"bone_tail",
- "weight":1.0
- },
- "forearm.R": {
- "track_type":"bone_head",
- "weight":1.0
- }
- },
- "left_wrist": {
- "forearm.L": {
- "track_type":"bone_tail",
- "weight":1.0
- },
- "hand.L": {
- "track_type":"bone_head",
- "weight":1.0
- }
- },
- "right_wrist": {
- "forearm.R": {
- "track_type":"bone_tail",
- "weight":1.0
- },
- "hand.R": {
- "track_type":"bone_head",
- "weight":1.0
- }
- },
- "left_pinky": {
- "hand.L": {
- "track_type":"bone_tail",
- "weight":1.0
- }
- },
- "right_pinky": {
- "hand.R": {
- "track_type":"bone_tail",
- "weight":1.0
- }
- },
- "left_index": {},
- "right_index": {},
- "left_thumb": {},
- "right_thumb": {},
- "left_hip": {
- "pelvis.L": {
- "track_type":"bone_tail",
- "weight":1.0
- },
- "thigh.L": {
- "track_type":"bone_head",
- "weight":1.0
- }
- },
- "right_hip": {
- "pelvis.R": {
- "track_type":"bone_tail",
- "weight":1.0
- },
- "thigh.R": {
- "track_type":"bone_head",
- "weight":1.0
- }
- },
- "left_knee": {
- "thigh.L": {
- "track_type":"bone_tail",
- "weight":1.0
- },
- "shin.L": {
- "track_type":"bone_head",
- "weight":1.0
- }
- },
- "right_knee": {
- "shin.R": {
- "track_type":"bone_tail",
- "weight":1.0
- },
- "foot.R": {
- "track_type":"bone_head",
- "weight":1.0
- }
- },
- "right_ankle": {
- "shin.R": {
- "track_type":"bone_tail",
- "weight":1.0
- },
- "foot.R": {
- "track_type":"bone_head",
- "weight":1.0
- }
- },
- "left_ankle": {
- "shin.L": {
- "track_type":"bone_tail",
- "weight":1.0
- },
- "foot.L": {
- "track_type":"bone_head",
- "weight":1.0
- }
- },
- "left_heel": {
- "foot.L": {
- "track_type":"bone_tail",
- "weight":1.0
- },
- "toe.L": {
- "track_type":"bone_head",
- "weight":1.0
- }
- },
- "right_heel": {
- "foot.R": {
- "track_type":"bone_tail",
- "weight":1.0
- },
- "toe.R": {
- "track_type":"bone_head",
- "weight":1.0
- }
- },
- "left_foot_index": {
- "toe.L": {
- "track_type":"bone_tail",
- "weight":1.0
- }
- },
- "right_foot_index":{
- "toe.R": {
- "track_type":"bone_tail",
- "weight":1.0
- }
- }
- }
- }
-},
- "hands": {
- "body_segments": {
- "constrain_length_bool": false,
- "left_upper_arm": {
- "parent": "left_shoulder",
- "child": "left_elbow",
- "anthropometric_definition": {
- "proportional_length": 0.186,
- "proportional_mass": 0.028,
- "center_of_mass_proximal": 0.436,
- "center_of_mass_distal": 0.564
- },
- "spherical_joint_limits": {
- "azimuth": [
- 0,
- 360
- ],
- "elevation": [
- 0,
- 360
- ]
- }
- },
- "etc": {}
- },
- "virtual_markers": {
- "neck": {
- "left_shoulder": 0.5,
- "right_shoudler": 0.5
- },
- "center_of_mass": {
- "etc": 0.9
- }
- },
- "dotto_names": [
- "nose",
- "left_eye_inner",
- "butt",
- "etc"
- ]
- },
- "face": {
- "body_segments": {
- "constrain_length_bool": false,
- "left_upper_arm": {
- "parent": "left_shoulder",
- "child": "left_elbow",
- "anthropometric_definition": {
- "proportional_length": 0.186,
- "proportional_mass": 0.028,
- "center_of_mass_proximal": 0.436,
- "center_of_mass_distal": 0.564
- },
- "spherical_joint_limits": {
- "azimuth": [
- 0,
- 360
- ],
- "elevation": [
- 0,
- 360
- ]
- }
- },
- "etc": {}
- },
- "virtual_markers": {
- "neck": {
- "left_shoulder": 0.5,
- "right_shoudler": 0.5
- },
- "center_of_mass": {
- "etc": 0.9
- }
- },
- "dotto_names": [
- "nose",
- "left_eye_inner",
- "butt",
- "etc"
- ]
- }
-}
\ No newline at end of file
diff --git a/freemocap/dev_scratchpad/dev_alpha_old/fmc_alpha_runme.py b/freemocap/dev_scratchpad/dev_alpha_old/fmc_alpha_runme.py
deleted file mode 100644
index f1e016fd..00000000
--- a/freemocap/dev_scratchpad/dev_alpha_old/fmc_alpha_runme.py
+++ /dev/null
@@ -1,13 +0,0 @@
-import freemocap as fmc
-
-from FMC_MultiCamera import FMC_MultiCamera
-
-from pathos.helpers import mp as pathos_mp_helper
-
-if __name__ =='__main__':
- pathos_mp_helper.freeze_support()
-
- multi_cam = FMC_MultiCamera(freemocap_data_folder='C:/Users/WindowsPC_Hallway/Dropbox/FreeMoCapProject/FreeMocap_Data')
- sessionID = multi_cam._rec_name
- multi_cam.start(standalone_mode=True)
- f=9
diff --git a/freemocap/dev_scratchpad/dev_alpha_old/freemocap_alpha_runme_script.py b/freemocap/dev_scratchpad/dev_alpha_old/freemocap_alpha_runme_script.py
deleted file mode 100644
index 806fdad3..00000000
--- a/freemocap/dev_scratchpad/dev_alpha_old/freemocap_alpha_runme_script.py
+++ /dev/null
@@ -1,35 +0,0 @@
-from pathlib import Path
-
-from pathos.helpers import mp as pathos_mp_helper
-from rich.console import Console
-
-from FMC_MultiCamera import FMC_MultiCamera
-import freemocap as fmc
-
-
-
-if __name__ == '__main__':
- pathos_mp_helper.freeze_support()
- console = Console() #create rich console to catch and print exceptions
-
- import socket
- this_computer_name = socket.gethostname()
-
- freemocap_data_path=None
- in_rotation_codes_list=None
-
- if this_computer_name=='jon-hallway-XPS-8930':
- freemocap_data_path = Path('/home/jon/Dropbox/FreeMoCapProject/FreeMocap_Data')
- in_rotation_codes_list = ['cv2.ROTATE_90_COUNTERCLOCKWISE', 'cv2.ROTATE_90_COUNTERCLOCKWISE', 'cv2.ROTATE_90_CLOCKWISE', 'cv2.ROTATE_90_CLOCKWISE', 'cv2.ROTATE_90_CLOCKWISE', ]
- elif this_computer_name == 'DESKTOP-DCG6K4F':
- freemocap_data_path = Path(r'C:\Users\jonma\Dropbox\FreeMoCapProject\FreeMocap_Data')
-
-
- try:
- multi_cam = FMC_MultiCamera(freemocap_data_folder=str(freemocap_data_path), rotation_codes_list=in_rotation_codes_list)
- multi_cam.start(standalone_mode=True)
- except Exception:
- console.print_exception()
-
- fmc.RunMe(multi_cam._rec_name, stage=3)
-
\ No newline at end of file
diff --git a/freemocap/dev_scratchpad/dev_alpha_old/old_FMC_MultiCameraRecorder.py b/freemocap/dev_scratchpad/dev_alpha_old/old_FMC_MultiCameraRecorder.py
deleted file mode 100644
index 43f3b7ab..00000000
--- a/freemocap/dev_scratchpad/dev_alpha_old/old_FMC_MultiCameraRecorder.py
+++ /dev/null
@@ -1,455 +0,0 @@
-##
-##
-## β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆ
-## β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ
-## β–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ
-## β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ
-## β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ
-##
-##
-#Font - ANSI Regular - https://patorjk.com/software/taag/#p=display&f=ANSI%20Regular&t=Play%20Skeleton%20Animation
-
-
-from os import mkdir
-from FMC_Camera import FMC_Camera
-
-import concurrent.futures
-import logging
-import queue
-import threading
-import pathos.multiprocessing as pathos_mp
-from pathos.helpers import mp as pathos_mp_helper
-import time
-import platform
-import datetime
-
-import cv2
-import matplotlib.pyplot as plt
-import numpy as np
-import h5py
-from pathlib import Path
-
-from rich import print
-from rich import inspect
-from rich.progress import track
-from rich.traceback import install
-install(show_locals=True)
-from rich.console import Console
-rich_console = Console()
-from rich.progress import track
-
-
-class FMC_MultiCameraRecorder:
- ##
- ##
- ## β–ˆβ–ˆ β–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ
- ## β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ
- ## β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ
- ## β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ
- ## β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ
- ##
- ##
- ##
- def __init__(
- self,
- rec_name = None,
- save_path = None,
- num_cams = 0,
- cams_to_use_list = None,
- show_multi_cam_stream = True,
- save_to_mp4 = True,
- save_to_h5 = False,
- save_log_file = False
- ):
-
- self._init_start_time = time.time_ns()#the precision is aspirational, lol
-
- if rec_name is None:
- self._rec_name = datetime.datetime.now().strftime("FMC_MultiCamRecording_%Y-%b-%d_%H_%M_%S")
- else:
- self._rec_name = rec_name
-
-
- if save_path is None:
- self._save_path = Path('data/' + self._rec_name)
- else:
- self._save_path = Path(save_path)
-
- if save_path or save_to_mp4 or save_to_h5 or save_log_file:
- self._save_path.mkdir(parents=True)
- self._path_to_log_file = Path(str(self._save_path / self._rec_name) + '_log.txt')
-
- self._save_to_mp4 = save_to_mp4
- if self._save_to_mp4:
- self._output_video_object = None #build this after we get the first multi_frame_image
-
- # log_file_obj = open(self._path_to_log_file,'w+')
- # rich_console = Console(file=log_file_obj)
- rich_console = Console()
-
- self._num_cams = num_cams
- self._cams_to_use_list = cams_to_use_list
-
-
-
-
- rich_console.rule('Starting FreeMoCap MultiCam Recorder!')
-
-
-
-
- ###
- ###
- ### β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ
- ### β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ
- ### β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ
- ### β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ
- ### β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ
- ###
- ###
-
- @property
- def num_cams(self):
- """How many cameras to use"""
- return self._num_cams
-
- @num_cams.setter
- def num_cams(self, num_cams_input):
- """Define how many cameras to use"""
- self._num_cams = num_cams_input
-
- @property
- def cams_to_use_list(self):
- """ a list denoting which camera IDs to use.
- If both this and `num_cams` are set to default value (`0` and `None`, respectively), use all available cameras).
- """
- return self._cams_to_use_list
-
- @property
- def init_start_time(self):
- """Time that this object was initialized (UNIX Epoch time from `time.time_ns())
-
- Returns:
- float: time this object was created (UNIX Epoch time from `time.time_ns())
- """
- return self._init_start_time
-
- @property
- def each_cam_timestamps_unix_ns(self): #not really a property though?
- return self._each_cam_timestamps_unix_ns
- ###
- ###
- ### β–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ
- ### β–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ
- ### β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ
- ### β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ
- ### β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ
- ###
- ###
- def start(self):
-
- if self.cams_to_use_list is None:
- self.find_available_cameras()
-
- # pathos_pool = ProcessPool(nodes=1)
- # pathos_pool.map(self.start_multi_cam_thread_pool)
- # self.start_multi_cam_thread_pool() #threads are mostly fine, but I think processes will be better eventually?
- self.start_multi_cam_process_pool() # as of 2021-10-26, this doesn't work :(
- self.create_diagnostic_images()
-
-
-
- def find_available_cameras(self):
- """find available webcams and return IDs in list."""
-
- if self.num_cams == 0:
- num_cams_to_check = 20 #man, i HOPE you're out there trying to record from more than 20 cameras!!!
- else:
- num_cams_to_check = self.num_cams
-
- if platform.system() == 'Windows':
- capBackend = cv2.CAP_DSHOW
- else:
- capBackend = cv2.CAP_ANY
-
- self._cams_to_use_list = []
- for camNum in track(range(num_cams_to_check), description='[green]Finding available cameras...' ):
- cap = cv2.VideoCapture(camNum, capBackend)
- if cap.isOpened():
- self._cams_to_use_list.append(camNum)
- cap.release()
- rich_console.print("Found cameras at ", self._cams_to_use_list)
-
- self.num_cams = len(self._cams_to_use_list)
- return self.cams_to_use_list
- ###
- ###
- ### β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ
- ### β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ
- ### β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ
- ### β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ
- ### β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ
- ###
- ###
-
- def start_multi_cam_thread_pool(self):
- """creates a threading.ThreadPoolExecutor that creates an `FMC_Camera` object for each camera in `self.cams_to_use_list` and sets each to trigger `run_in_thread` mode
-
- NOTE - Eventually I want these to be in different processes, I think?
- """
- self.cam_frame_queue = queue.Queue(maxsize=self.num_cams)
- self.multi_cam_image_queue = queue.Queue()
-
- self.exit_event = threading.Event()
-
- self._each_cam_timestamps_unix_ns = None
- self._cam_thread = [None] * self.num_cams
-
- rich_console.rule('starting multi_cam_thread_pool')
-
- while not self.exit_event.is_set():
- with concurrent.futures.ThreadPoolExecutor(max_workers=self.num_cams+1) as executor:
- self.barrier = threading.Barrier(self.num_cams, action=self.grab_incoming_cam_tuples)
- for this_cam_num in self.cams_to_use_list: #i feel like there is some cooler way to do this using 'map' and 'zip' or whatever, but this feels easier on the ol' brain noggin lol
- self._cam_thread[this_cam_num] = executor.submit(FMC_Camera, cam_num=this_cam_num, frame_queue = self.cam_frame_queue, barrier = self.barrier, exit_event = self.exit_event)
- executor.submit(self.show_multi_cam_cv2)
-
-###
-###
-### β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ
-### β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ
-### β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ
-### β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ
-### β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ
-###
-###
-###
- def start_multi_cam_process_pool(self):
- """
- reates a ProcessPoolExecutor that creates an `FMC_Camera` object for each camera in `self.cams_to_use_list` and sets each to trigger `run_in_process` mode (which just passes to `run_in_thread` mode)
-
- """
- mrManager = pathos_mp_helper.Manager()
- self.cam_frame_queue = mrManager.Queue(maxsize=self.num_cams)
- self.multi_cam_image_queue = mrManager.Queue()
- self.barrier = mrManager.Barrier(self.num_cams+1) #each cam + one more for the frame grabber
- self.exit_event = mrManager.Event()
-
- self._each_cam_timestamps_unix_ns = None
- self._cam_process = [None] * self.num_cams
-
- rich_console.rule('starting multi_cam_process_pool')
-
- in_frame_q_list = [self.cam_frame_queue]*self.num_cams
- in_barrier_list = [self.barrier]*self.num_cams
- in_exit_event_list = [self.exit_event]*self.num_cams
- # nsole_list = [self.rich_console]*self.num_cams
-
-
- num_jobs = self.num_cams
- with pathos_mp.ProcessingPool(num_jobs) as pp_pool: #lol
- pp_pool.amap(
- FMC_Camera,
- tuple(self.cams_to_use_list),
- tuple(in_frame_q_list),
- tuple(in_barrier_list),
- tuple(in_exit_event_list),
- )
- incoming_frame_grabber_thread = threading.Thread(target=self.grab_incoming_cam_tuples, name='Incoming Frame Grabber')
- incoming_frame_grabber_thread.start()
- self.show_multi_cam_cv2()
-
-
-
- ###
- ###
- ### β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ
- ### β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ
- ### β–ˆβ–ˆ β–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ
- ### β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ
- ### β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ
- ###
- ###
-
-
- def grab_incoming_cam_tuples(self):
- """grab incoming cam_tuples, put them into a multi_cam_tuple and stuff that into the multi_cam_tuple_queue"""
-
- # self.show_multi_cam_cv2()
-
- while not self.exit_event.is_set():
- self.barrier.wait() #wait until each camera has grabbed an image and tagged their `barrier.wait()` signals
-
- these_images_list = [None]*self.num_cams #empty list of size (numCam)
- these_timestamps = np.ndarray(self.num_cams)
-
- for cam_num in range(self.num_cams):
- this_cam_image_timestamp_tuple = self.cam_frame_queue.get()
- this_cam_num = this_cam_image_timestamp_tuple[0]
- these_images_list[this_cam_num] = this_cam_image_timestamp_tuple[1]
- these_timestamps[this_cam_num] = this_cam_image_timestamp_tuple[2]
-
- if self._each_cam_timestamps_unix_ns is None:
- self._each_cam_timestamps_unix_ns = these_timestamps
- else:
- self._each_cam_timestamps_unix_ns = np.vstack((self._each_cam_timestamps_unix_ns, these_timestamps)) #result will be numpy array with `num_frames` rows and `num_cams` columns
-
-
- multi_cam_image = np.hstack(these_images_list) #create multiFrame_image by stitching together incoming camera images
- self.multi_cam_image_queue.put(multi_cam_image)
- # rich_console.log('Created a multi_cam_image - queue size: {}'.format(self.multi_cam_image_queue.qsize()))
-
- ###
- ###
- ### β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ
- ### β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ
- ### β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ
- ### β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ
- ### β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ
- ###
- ###
-
- def show_multi_cam_cv2(self):
- """display multi_cam_image using `cv2.imshow` and maybe save it to mp4, who knows?
- """
- rich_console.rule('Launching Multi Cam Viewer')
- while not self.exit_event.is_set():
- if not self.multi_cam_image_queue.empty():
- multi_cam_image = self.multi_cam_image_queue.get()
-
- if self._save_to_mp4:
- if self._output_video_object is None:
- self.initialize_video(multi_cam_image)
- self._output_video_object.write(multi_cam_image)
-
- cv2.imshow(self._rec_name, multi_cam_image)
- key = cv2.waitKey(1)
-
- if key == 27: # exit on ESC
- self.exit_event.set()
-
- if cv2.getWindowProperty(self._rec_name, cv2.WND_PROP_VISIBLE) < 1: #break loop if window closed
- self.exit_event.set()
-
- cv2.destroyAllWindows()
- if self._save_to_mp4:
- self._output_video_object.release()
- rich_console.rule('Shutting down MultiCamera Viewer')
- self.exit_event.set() #send the 'Exit' signal to everyone.
-
- ###
- ###
- ### β–ˆβ–ˆ β–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ
- ### β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ
- ### β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ
- ### β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ
- ### β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ
- ###
- ###
-
- def initialize_video(self, multi_cam_image):
- """use the multi_cam_image to initialize the video
- multicam image will be of size [cam_resolution_width*num_cams by cam_resolution_height]
- Args:
- multi_cam_image ([type]): [description]
- """
- #create video save object
- self._multi_cam_image_height, self._multi_cam_image_width, channels = multi_cam_image.shape
-
- self.multi_cam_image_size = ( self._multi_cam_image_width, self._multi_cam_image_height)
- fourcc = cv2.VideoWriter_fourcc(*'DIVX')
- self._outputVid_fileName = str(self._save_path / self._rec_name) + '_outVid.mp4'
- fps = 30 #this is a bad and stupid guess, but it's actually kinda tricky to guess what is the right thing to put here. I'll fix this later and expect videos to be a bit faster than usual :(
- self._output_video_object = cv2.VideoWriter(self._outputVid_fileName, fourcc, fps, self.multi_cam_image_size)
- ##
- ##
- ## β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ
- ## β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ
- ## β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ
- ## β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ
- ## β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ
- ##
- ##
-
- def create_diagnostic_images(self):
- """plot some diagnostics to assess quality of camera sync"""
- try:
- camTimestamps = (self.each_cam_timestamps_unix_ns-self.init_start_time)/1e9 #subtract start time and convert to sec
-
- npy_save_path = self._save_path /'multi_cam_timestamps_frameNum_camNum.npy'
- np.save(str(npy_save_path), camTimestamps)
- rich_console.log('saving timestamp data to - ' + str(npy_save_path) )
-
- meanMultiFrameTimestamp = np.mean(camTimestamps, axis=1)
- meanMultiFrameTimespan = np.max(camTimestamps, axis=1) - np.min(camTimestamps, axis=1) #what was the timespan covered by each frame
- plt.ion()
- fig = plt.figure(figsize=(18,10))
- max_frame_duration = .1
- ax1 = plt.subplot(231, title='Camera Frame Timestamp vs Frame#', xlabel='Frame#', ylabel='Timestamp (sec)')
- ax2 = plt.subplot(232, ylim=(0,max_frame_duration), title='Camera Frame Duration Trace', xlabel='Frame#', ylabel='Duration (sec)')
- ax3 = plt.subplot(233, xlim=(0,max_frame_duration), title='Camera Frame Duration Histogram (count)', xlabel='Duration(s, 1ms bins)', ylabel='Probability')
- ax4 = plt.subplot(234, title='MuliFrame Timestamp vs Frame#', xlabel='Frame#', ylabel='Timestamp (sec)')
- ax5 = plt.subplot(235, ylim=(0,max_frame_duration), title='Multi Frame Duration/Span Trace', xlabel='Frame#', ylabel='Duration (sec)')
- ax6 = plt.subplot(236, xlim=(0,max_frame_duration), title='MultiFrame Duration Histogram (count)', xlabel='Duration(s, 1ms bins)', ylabel='Probability')
-
- for camNum in range(self.num_cams):
- thisCamTimestamps = camTimestamps[:,camNum]
- ax1.plot(thisCamTimestamps, label='Camera#'+str(camNum))
- ax1.legend()
- ax2.plot(np.diff(thisCamTimestamps),'.')
- ax3.hist(np.diff(thisCamTimestamps), bins=np.arange(0,max_frame_duration,.001), alpha=0.5)
-
- ax4.plot(meanMultiFrameTimestamp, color='darkslategrey', label='MultiFrame'+str(camNum))
- ax5.plot(np.diff(meanMultiFrameTimestamp),'.',color='darkslategrey', label='Frame Duration')
- ax5.plot(meanMultiFrameTimespan, '.', color='orangered', label='Frame TimeSpan')
- ax5.legend()
- ax6.hist(np.diff(meanMultiFrameTimestamp), bins=np.arange(0,max_frame_duration,.001), density=True, alpha=0.5, color='darkslategrey', label='Frame Duration')
- ax6.hist(np.diff(meanMultiFrameTimespan), bins=np.arange(0,max_frame_duration,.001), density=True, alpha=0.5, color='orangered', label='Frame Timespan')
- ax5.legend()
-
- fig_save_path = self._save_path / 'recording_diagnostics.png'
- plt.savefig(str(fig_save_path))
- rich_console.log('Saving diagnostic figure to - '+str(fig_save_path))
- plt.show()
- plt.waitforbuttonpress()
- except:
- rich_console.print_exception()
- f=9
-
- ###
- ### β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ
- ### β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ
- ### β–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ
- ### β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ
- ### β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ
- ###
-
- def __enter__(self):
- """Context manager - No need to do anything special on start"""
- return self
-
- def __exit__(self, exc_type, exc_value, exc_traceback):
- """Context manager - on exit, set `self.exit_event` to activate shutdown sequence """
- return self
-###
-###
-### β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆ β–ˆβ–ˆ
-### β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ
-### β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ
-### β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ
-### β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ
-###
-###
-
-
-if __name__ == '__main__':
- pathos_mp_helper.freeze_support()
- console = Console() #create rich console to catch and print exceptions
- try:
- fmc_multi_cam_recorder = FMC_MultiCameraRecorder()
- fmc_multi_cam_recorder.start()
-
- except Exception:
- console.print_exception()
-
-
diff --git a/freemocap/dev_scratchpad/dev_alpha_old/qt_gui_FMC_Camera b/freemocap/dev_scratchpad/dev_alpha_old/qt_gui_FMC_Camera
deleted file mode 100644
index 44cde715..00000000
--- a/freemocap/dev_scratchpad/dev_alpha_old/qt_gui_FMC_Camera
+++ /dev/null
@@ -1,83 +0,0 @@
-from PyQt5.QtWidgets import QApplication, QLabel, QVBoxLayout, QWidget
-
-import pyqtgraph as pg
-from pyqtgraph.Qt import QtGui, QtCore
-from pyqtgraph.widgets.RawImageWidget import RawImageGLWidget
-
-from time import perf_counter
-
-import cv2
-import numpy as np
-
-if RawImageGLWidget is not None:
- # don't limit frame rate to vsync
- sfmt = QtGui.QSurfaceFormat()
- sfmt.setSwapInterval(0)
- QtGui.QSurfaceFormat.setDefaultFormat(sfmt)
-
-app = QApplication([])
-app.setApplicationName("FMC_Camera QT GUI")
-
-qt_window = QWidget()
-qt_window.setWindowTitle('FMC_Camera')
-
-layout = QVBoxLayout()
-
-qt_raw_image_gl_widget = RawImageGLWidget()
-layout.addWidget(qt_raw_image_gl_widget)
-
-qt_fps_label = QLabel()
-layout.addWidget(qt_fps_label)
-
-qt_window.setLayout(layout)
-qt_window.show()
-
-
-
-# create open-cv video capture object
-cap = cv2.VideoCapture(0, cv2.CAP_DSHOW)
-
-cap.set(cv2.CAP_PROP_EXPOSURE, -7)
-cap.set(cv2.CAP_PROP_FRAME_WIDTH, 640)
-cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 480)
-cap.set(cv2.CAP_PROP_FOURCC, cv2.VideoWriter_fourcc('M', 'J', 'P', 'G'))
-
-success, image = cap.read()
-assert success, 'Camera Failed to load image'
-vidWidth, vidHeight, vidNumColorChannels = image.shape
-
-
-
-ptr = 0
-lastTime = perf_counter()
-fps = None
-def update():
- global lastTime, fps
-
- #read image from camera
- success, image = cap.read()
- if success:
- print('image loaded')
- image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) #convert image from BGR to RGB color format
-
- qt_raw_image_gl_widget.setImage(image)
-
-
-
- now = perf_counter()
- dt = now - lastTime
- lastTime = now
- if fps is None:
- fps = 1.0/dt
- else:
- s = np.clip(dt*3., 0, 1)
- fps = fps * (1-s) + (1.0/dt) * s
- qt_fps_label.setText('%0.2f fps' % fps)
- app.processEvents() ## force complete redraw for every plot
-
-timer = QtCore.QTimer()
-timer.timeout.connect(update)
-timer.start(0)
-
-if __name__ == '__main__':
- app.exec()
\ No newline at end of file
diff --git a/freemocap/dev_scratchpad/dev_alpha_old/scratch/VideoTemplate_pyqt5.py b/freemocap/dev_scratchpad/dev_alpha_old/scratch/VideoTemplate_pyqt5.py
deleted file mode 100644
index 7fd9439a..00000000
--- a/freemocap/dev_scratchpad/dev_alpha_old/scratch/VideoTemplate_pyqt5.py
+++ /dev/null
@@ -1,209 +0,0 @@
-# -*- coding: utf-8 -*-
-
-# Form implementation generated from reading ui file '.\VideoTemplate.ui'
-#
-# Created by: PyQt5 UI code generator 5.15.4
-#
-# WARNING: Any manual changes made to this file will be lost when pyuic5 is
-# run again. Do not edit this file unless you know what you are doing.
-
-
-from PyQt5 import QtCore, QtGui, QtWidgets
-
-
-class Ui_MainWindow(object):
- def setupUi(self, MainWindow):
- MainWindow.setObjectName("MainWindow")
- MainWindow.resize(695, 798)
- self.centralwidget = QtWidgets.QWidget(MainWindow)
- self.centralwidget.setObjectName("centralwidget")
- self.gridLayout_2 = QtWidgets.QGridLayout(self.centralwidget)
- self.gridLayout_2.setObjectName("gridLayout_2")
- self.cudaCheck = QtWidgets.QCheckBox(self.centralwidget)
- self.cudaCheck.setObjectName("cudaCheck")
- self.gridLayout_2.addWidget(self.cudaCheck, 9, 0, 1, 2)
- self.numbaCheck = QtWidgets.QCheckBox(self.centralwidget)
- self.numbaCheck.setObjectName("numbaCheck")
- self.gridLayout_2.addWidget(self.numbaCheck, 9, 2, 1, 2)
- self.downsampleCheck = QtWidgets.QCheckBox(self.centralwidget)
- self.downsampleCheck.setObjectName("downsampleCheck")
- self.gridLayout_2.addWidget(self.downsampleCheck, 8, 0, 1, 2)
- self.scaleCheck = QtWidgets.QCheckBox(self.centralwidget)
- self.scaleCheck.setObjectName("scaleCheck")
- self.gridLayout_2.addWidget(self.scaleCheck, 4, 0, 1, 1)
- self.gridLayout = QtWidgets.QGridLayout()
- self.gridLayout.setObjectName("gridLayout")
- self.rawRadio = QtWidgets.QRadioButton(self.centralwidget)
- self.rawRadio.setObjectName("rawRadio")
- self.gridLayout.addWidget(self.rawRadio, 3, 0, 1, 1)
- self.gfxRadio = QtWidgets.QRadioButton(self.centralwidget)
- self.gfxRadio.setChecked(True)
- self.gfxRadio.setObjectName("gfxRadio")
- self.gridLayout.addWidget(self.gfxRadio, 2, 0, 1, 1)
- self.stack = QtWidgets.QStackedWidget(self.centralwidget)
- self.stack.setObjectName("stack")
- self.page = QtWidgets.QWidget()
- self.page.setObjectName("page")
- self.gridLayout_3 = QtWidgets.QGridLayout(self.page)
- self.gridLayout_3.setObjectName("gridLayout_3")
- self.graphicsView = GraphicsView(self.page)
- self.graphicsView.setObjectName("graphicsView")
- self.gridLayout_3.addWidget(self.graphicsView, 0, 0, 1, 1)
- self.stack.addWidget(self.page)
- self.page_2 = QtWidgets.QWidget()
- self.page_2.setObjectName("page_2")
- self.gridLayout_4 = QtWidgets.QGridLayout(self.page_2)
- self.gridLayout_4.setObjectName("gridLayout_4")
- self.rawImg = RawImageWidget(self.page_2)
- sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Preferred)
- sizePolicy.setHorizontalStretch(0)
- sizePolicy.setVerticalStretch(0)
- sizePolicy.setHeightForWidth(self.rawImg.sizePolicy().hasHeightForWidth())
- self.rawImg.setSizePolicy(sizePolicy)
- self.rawImg.setObjectName("rawImg")
- self.gridLayout_4.addWidget(self.rawImg, 0, 0, 1, 1)
- self.stack.addWidget(self.page_2)
- self.gridLayout.addWidget(self.stack, 0, 0, 1, 1)
- self.rawGLRadio = QtWidgets.QRadioButton(self.centralwidget)
- self.rawGLRadio.setObjectName("rawGLRadio")
- self.gridLayout.addWidget(self.rawGLRadio, 4, 0, 1, 1)
- self.gridLayout_2.addLayout(self.gridLayout, 1, 0, 1, 4)
- self.dtypeCombo = QtWidgets.QComboBox(self.centralwidget)
- self.dtypeCombo.setObjectName("dtypeCombo")
- self.dtypeCombo.addItem("")
- self.dtypeCombo.addItem("")
- self.dtypeCombo.addItem("")
- self.gridLayout_2.addWidget(self.dtypeCombo, 3, 2, 1, 1)
- self.label = QtWidgets.QLabel(self.centralwidget)
- self.label.setObjectName("label")
- self.gridLayout_2.addWidget(self.label, 3, 0, 1, 1)
- self.rgbLevelsCheck = QtWidgets.QCheckBox(self.centralwidget)
- self.rgbLevelsCheck.setObjectName("rgbLevelsCheck")
- self.gridLayout_2.addWidget(self.rgbLevelsCheck, 4, 1, 1, 1)
- self.horizontalLayout_2 = QtWidgets.QHBoxLayout()
- self.horizontalLayout_2.setObjectName("horizontalLayout_2")
- self.minSpin2 = SpinBox(self.centralwidget)
- self.minSpin2.setEnabled(False)
- self.minSpin2.setObjectName("minSpin2")
- self.horizontalLayout_2.addWidget(self.minSpin2)
- self.label_3 = QtWidgets.QLabel(self.centralwidget)
- self.label_3.setAlignment(QtCore.Qt.AlignCenter)
- self.label_3.setObjectName("label_3")
- self.horizontalLayout_2.addWidget(self.label_3)
- self.maxSpin2 = SpinBox(self.centralwidget)
- self.maxSpin2.setEnabled(False)
- self.maxSpin2.setObjectName("maxSpin2")
- self.horizontalLayout_2.addWidget(self.maxSpin2)
- self.gridLayout_2.addLayout(self.horizontalLayout_2, 5, 2, 1, 1)
- self.horizontalLayout = QtWidgets.QHBoxLayout()
- self.horizontalLayout.setObjectName("horizontalLayout")
- self.minSpin1 = SpinBox(self.centralwidget)
- self.minSpin1.setObjectName("minSpin1")
- self.horizontalLayout.addWidget(self.minSpin1)
- self.label_2 = QtWidgets.QLabel(self.centralwidget)
- self.label_2.setAlignment(QtCore.Qt.AlignCenter)
- self.label_2.setObjectName("label_2")
- self.horizontalLayout.addWidget(self.label_2)
- self.maxSpin1 = SpinBox(self.centralwidget)
- self.maxSpin1.setObjectName("maxSpin1")
- self.horizontalLayout.addWidget(self.maxSpin1)
- self.gridLayout_2.addLayout(self.horizontalLayout, 4, 2, 1, 1)
- self.horizontalLayout_3 = QtWidgets.QHBoxLayout()
- self.horizontalLayout_3.setObjectName("horizontalLayout_3")
- self.minSpin3 = SpinBox(self.centralwidget)
- self.minSpin3.setEnabled(False)
- self.minSpin3.setObjectName("minSpin3")
- self.horizontalLayout_3.addWidget(self.minSpin3)
- self.label_4 = QtWidgets.QLabel(self.centralwidget)
- self.label_4.setAlignment(QtCore.Qt.AlignCenter)
- self.label_4.setObjectName("label_4")
- self.horizontalLayout_3.addWidget(self.label_4)
- self.maxSpin3 = SpinBox(self.centralwidget)
- self.maxSpin3.setEnabled(False)
- self.maxSpin3.setObjectName("maxSpin3")
- self.horizontalLayout_3.addWidget(self.maxSpin3)
- self.gridLayout_2.addLayout(self.horizontalLayout_3, 6, 2, 1, 1)
- self.lutCheck = QtWidgets.QCheckBox(self.centralwidget)
- self.lutCheck.setObjectName("lutCheck")
- self.gridLayout_2.addWidget(self.lutCheck, 7, 0, 1, 1)
- self.alphaCheck = QtWidgets.QCheckBox(self.centralwidget)
- self.alphaCheck.setObjectName("alphaCheck")
- self.gridLayout_2.addWidget(self.alphaCheck, 7, 1, 1, 1)
- self.gradient = GradientWidget(self.centralwidget)
- sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Preferred)
- sizePolicy.setHorizontalStretch(0)
- sizePolicy.setVerticalStretch(0)
- sizePolicy.setHeightForWidth(self.gradient.sizePolicy().hasHeightForWidth())
- self.gradient.setSizePolicy(sizePolicy)
- self.gradient.setObjectName("gradient")
- self.gridLayout_2.addWidget(self.gradient, 7, 2, 1, 2)
- spacerItem = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)
- self.gridLayout_2.addItem(spacerItem, 3, 3, 1, 1)
- self.fpsLabel = QtWidgets.QLabel(self.centralwidget)
- font = QtGui.QFont()
- font.setPointSize(12)
- self.fpsLabel.setFont(font)
- self.fpsLabel.setAlignment(QtCore.Qt.AlignCenter)
- self.fpsLabel.setObjectName("fpsLabel")
- self.gridLayout_2.addWidget(self.fpsLabel, 0, 0, 1, 4)
- self.rgbCheck = QtWidgets.QCheckBox(self.centralwidget)
- self.rgbCheck.setObjectName("rgbCheck")
- self.gridLayout_2.addWidget(self.rgbCheck, 3, 1, 1, 1)
- self.label_5 = QtWidgets.QLabel(self.centralwidget)
- self.label_5.setObjectName("label_5")
- self.gridLayout_2.addWidget(self.label_5, 2, 0, 1, 1)
- self.horizontalLayout_4 = QtWidgets.QHBoxLayout()
- self.horizontalLayout_4.setObjectName("horizontalLayout_4")
- self.framesSpin = QtWidgets.QSpinBox(self.centralwidget)
- self.framesSpin.setButtonSymbols(QtWidgets.QAbstractSpinBox.NoButtons)
- self.framesSpin.setProperty("value", 10)
- self.framesSpin.setObjectName("framesSpin")
- self.horizontalLayout_4.addWidget(self.framesSpin)
- self.widthSpin = QtWidgets.QSpinBox(self.centralwidget)
- self.widthSpin.setButtonSymbols(QtWidgets.QAbstractSpinBox.PlusMinus)
- self.widthSpin.setMaximum(10000)
- self.widthSpin.setProperty("value", 512)
- self.widthSpin.setObjectName("widthSpin")
- self.horizontalLayout_4.addWidget(self.widthSpin)
- self.heightSpin = QtWidgets.QSpinBox(self.centralwidget)
- self.heightSpin.setButtonSymbols(QtWidgets.QAbstractSpinBox.NoButtons)
- self.heightSpin.setMaximum(10000)
- self.heightSpin.setProperty("value", 512)
- self.heightSpin.setObjectName("heightSpin")
- self.horizontalLayout_4.addWidget(self.heightSpin)
- self.gridLayout_2.addLayout(self.horizontalLayout_4, 2, 1, 1, 2)
- self.sizeLabel = QtWidgets.QLabel(self.centralwidget)
- self.sizeLabel.setText("")
- self.sizeLabel.setObjectName("sizeLabel")
- self.gridLayout_2.addWidget(self.sizeLabel, 2, 3, 1, 1)
- MainWindow.setCentralWidget(self.centralwidget)
-
- self.retranslateUi(MainWindow)
- self.stack.setCurrentIndex(1)
- QtCore.QMetaObject.connectSlotsByName(MainWindow)
-
- def retranslateUi(self, MainWindow):
- _translate = QtCore.QCoreApplication.translate
- MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
- self.cudaCheck.setText(_translate("MainWindow", "Use CUDA (GPU) if available"))
- self.numbaCheck.setText(_translate("MainWindow", "Use Numba if available"))
- self.downsampleCheck.setText(_translate("MainWindow", "Auto downsample"))
- self.scaleCheck.setText(_translate("MainWindow", "Scale Data"))
- self.rawRadio.setText(_translate("MainWindow", "RawImageWidget"))
- self.gfxRadio.setText(_translate("MainWindow", "GraphicsView + ImageItem"))
- self.rawGLRadio.setText(_translate("MainWindow", "RawGLImageWidget"))
- self.dtypeCombo.setItemText(0, _translate("MainWindow", "uint8"))
- self.dtypeCombo.setItemText(1, _translate("MainWindow", "uint16"))
- self.dtypeCombo.setItemText(2, _translate("MainWindow", "float"))
- self.label.setText(_translate("MainWindow", "Data type"))
- self.rgbLevelsCheck.setText(_translate("MainWindow", "RGB"))
- self.label_3.setText(_translate("MainWindow", "<--->"))
- self.label_2.setText(_translate("MainWindow", "<--->"))
- self.label_4.setText(_translate("MainWindow", "<--->"))
- self.lutCheck.setText(_translate("MainWindow", "Use Lookup Table"))
- self.alphaCheck.setText(_translate("MainWindow", "alpha"))
- self.fpsLabel.setText(_translate("MainWindow", "FPS"))
- self.rgbCheck.setText(_translate("MainWindow", "RGB"))
- self.label_5.setText(_translate("MainWindow", "Image size"))
-from pyqtgraph import GradientWidget, GraphicsView, SpinBox
-from pyqtgraph.widgets.RawImageWidget import RawImageWidget
diff --git a/freemocap/dev_scratchpad/dev_alpha_old/scratch/cv2_cam_thread_queue_jsm.py b/freemocap/dev_scratchpad/dev_alpha_old/scratch/cv2_cam_thread_queue_jsm.py
deleted file mode 100644
index 1ad545ae..00000000
--- a/freemocap/dev_scratchpad/dev_alpha_old/scratch/cv2_cam_thread_queue_jsm.py
+++ /dev/null
@@ -1,256 +0,0 @@
-
-# %%
-import concurrent.futures
-import logging
-import queue
-import random
-import threading
-import time
-import platform
-
-import cv2
-import matplotlib.pyplot as plt
-import numpy as np
-import h5py
-from pathlib import Path
-
-from rich import print
-from rich import inspect
-
-def CamRecordThread(camCap, webcam_frames_queue, barrier, exit_event, camNum):
- """Pretend we're getting a number from the network."""
- while not exit_event.is_set():
-
- try:
- success, frame_image = camCap.read()
- timestamp = time.time()
- cam_num_tuple = (camNum, )
- frame_timestamp_tuple = (frame_image, timestamp)
- cam_frame_timestamp_tuple = cam_num_tuple+frame_timestamp_tuple
- webcam_frames_queue.put(cam_frame_timestamp_tuple)
- log_msg = 'Camera '+ str(camNum)+" got a frame at timestamp:"+ str(timestamp) + ' queue size: ' + str(webcam_frames_queue.qsize())
- print(log_msg)
- logging.info(log_msg)
- barrier.wait()
-
- except Exception as ex:
- template = "An exception of type {0} occurred. Arguments:\n{1!r}"
- message = template.format(type(ex).__name__, ex.args)
- logging.info(message)
- print(message)
- exit_event.set()
-
-
- camCap.release()
- logging.info("Producer received exit_event. Exiting")
-
-# def incoming_frames_handler(webcam_frames_queue, exit_event):
-# """Pretend we're saving a number in the database."""
-# while not exit_event.is_set() or not webcam_frames_queue.empty():
-# try:
-# cam_frame_timestamp_tuple= webcam_frames_queue.get() #tuple(camNum, (frame_image,timestamp))
-
-# camID = cam_frame_timestamp_tuple[0]
-# frame_timestamp_tuple = cam_frame_timestamp_tuple[1]
-# thisFrame = frame_timestamp_tuple[0]
-# thisTimestamp = frame_timestamp_tuple[1]
-
-# allTimestamps.append(thisTimestamp)
-# camTimestamps_list[camID] = np.append(camTimestamps_list[camID], thisTimestamp)
-
-# logging.info(
-# "IncomingFrameHandler got the frame from camera#"+str(camID)+" with timestamp: %s (size=%d)", str(thisTimestamp), webcam_frames_queue.qsize()
-# )
-
-
-
-# except:
-# print('something broke in the incoming_frame_handler')
-# exit_event.set()
-
-# logging.info("Consumer received exit_event . Exiting")
-
-def saveMultiViewToMP4():
- multiIm = None
- theseFrames_list = [None]* numCams #create an empty list with numCams entries (Python is weird sometimes, lol)
- theseFrameTuples_list = theseFrames_list
- theseTimestamps = np.empty(numCams)
-
- while webcam_frames_queue.qsize() > 0:
- this_cam_frame_timestamp_tuple = webcam_frames_queue.get() #(camNum,(frame,timestamp))
- camNum = this_cam_frame_timestamp_tuple[0]
- theseFrames_list[camNum] = this_cam_frame_timestamp_tuple[1]
- thisTimestamp = this_cam_frame_timestamp_tuple[2]
- theseTimestamps[camNum] = thisTimestamp
- camTimestamps_list[camNum] = np.append(camTimestamps_list[camNum], thisTimestamp)
-
- # allMultiframes.append(theseFrameTuples_list)
-
- for camNum, image in enumerate(theseFrames_list):
- if camNum==0:
- multiIm = image
- else:
- multiIm = cv2.hconcat([multiIm, image])
-
- multiFrame_queue.put(multiIm)
- print('multiframe_q size: {}'.format(multiFrame_queue.qsize()))
-
-
-
-
-
-
-
-def saveMultiViewToH5():
- multiFrameNum = len(h5OutFile)
- thisFrameName = 'MultiFrame_{}'.format(str(multiFrameNum).zfill(12)) # 12 zeros is probably enough. prove me wrong, you crazy apes <3
- thisMultiFrameH5Group = h5OutFile.create_group(thisFrameName, track_order=True)
-
- theseFrames_list = [None]*numCams #empty list of size (numCam)
- theseTimestamps_unixEpoch = np.ndarray(numCams)
-
- while webcam_frames_queue.qsize() > 0:
- this_cam_frame_timestamp_tuple = webcam_frames_queue.get()
- thisCamNum = this_cam_frame_timestamp_tuple[0]
- theseFrames_list[thisCamNum] = this_cam_frame_timestamp_tuple[1] #the image frame from thisCamera on thisMultiFrame time period
- thisTimestamp = this_cam_frame_timestamp_tuple[2] #the timestamp that this image frame was recieved by the camera
- theseTimestamps_unixEpoch[thisCamNum] = thisTimestamp #the timestamps of each frame in this multiframe (size:numCams)
- camTimestamps_list[thisCamNum] = np.append(camTimestamps_list[thisCamNum], thisTimestamp)#this'll get plotted later as a time sync diagnostic debug whosit :D
-
- thisMultiFrame = np.hstack(theseFrames_list) #horizontally stack each image into a numpy array with dimensions (imageHeight, imageWidth*numCams, 3(RGB)). Equivalent to cv2.hconcat((image0,image1,...,imageN))
-
- theseTimeStamps_fromRecStart = theseTimestamps_unixEpoch-init_time
- thisMultiFrameH5Group.create_dataset('multiFrameImage', data = thisMultiFrame)
- thisMultiFrameH5Group.create_dataset('each_timestamp_unix', data= theseTimestamps_unixEpoch)
- thisMultiFrameH5Group.create_dataset('each_timestamp_fromRecordStart', data= theseTimeStamps_fromRecStart)
- thisMultiFrameH5Group.create_dataset('mean_timestamp_unixEpoch', data= np.mean(theseTimestamps_unixEpoch))
- thisMultiFrameH5Group.create_dataset('mean_timestamp_fromRecordStart', data= np.mean(theseTimeStamps_fromRecStart))
- thisMultiFrameH5Group.create_dataset('timestamp', data= np.mean(theseTimeStamps_fromRecStart)) #this is the most intuitive timestamp to use per frame, it's a copy of the more verbosely named 'meanTimestamp_fromRecordStart'
- print('wrote ' + thisFrameName +' to H5Py - multiframe_q size: {}'.format(multiFrame_queue.qsize()))
-
-def ShowMultiView(multiFrame_queue, outputVidObj):
- while not exit_event.is_set():
- multiIm = multiFrame_queue.get()
- outputVidObj.write(multiIm)
- cv2.imshow('m', multiIm)
- key = cv2.waitKey(1)
- if key == 27: # exit on ESC
- exit_event.set()
- cv2.destroyAllWindows()
- outputVidObj.release()
-
-
-if __name__ == "__main__":
-
- init_time = time.time()
- vidSaveFolderPath = Path('saveFrames_'+str(time.time()))
- vidSaveFolderPath.mkdir()
-
- format = "%(asctime)s: %(message)s"
- logging.basicConfig(filename=str(vidSaveFolderPath / 'log.txt'),format=format, level=logging.INFO,
- datefmt="%H:%M:%S")
-
- logging.info('Logging started :D')
-
- numCams = 3
- fps=30
- camCap_list = []
- allTimestamps = []
- camTimestamps_list = []
- camImPath_list = []
- camAx_list = []
- cam_artist = []
- multiFr = None
-
-
- for camNum in range(numCams):
- camTimestamps_list.append(np.empty(0)) #we'll put the timestamps for each camea in here
-
- logging.info('starting camera ' + str(camNum))
-
- if platform.system() == 'Windows':
- camCap_list.append(cv2.VideoCapture(camNum, cv2.CAP_DSHOW))
- else:
- camCap_list.append(cv2.VideoCapture(camNum, cv2.CAP_ANY))
-
- camCap_list[camNum].set(cv2.CAP_PROP_FPS,fps)
- camCap_list[camNum].set(cv2.CAP_PROP_EXPOSURE,-9)
- logging.info('camera '+str(camNum)+ ' started')
- success, image = camCap_list[-1].read()
- assert success, "Camera {} failed to produce an image on startup".format(camNum)
- if multiFr is None:
- multiFr = image
- else:
- multiFr = cv2.hconcat([multiFr, image])
-
- #create video save object
- multiFr_height, multiFr_width, channels = multiFr.shape
- multiFrameSize = (multiFr_width, multiFr_height)
- fourcc = cv2.VideoWriter_fourcc(*'DIVX')
- outputVid_fileName = str(vidSaveFolderPath / 'outVid.mp4')
- outputVidObj = cv2.VideoWriter(outputVid_fileName, fourcc, fps, multiFrameSize)
-
- webcam_frames_queue = queue.Queue()
- multiFrame_queue = queue.Queue()
- exit_event = threading.Event()
-
- with h5py.File(str(vidSaveFolderPath/"multiFrames_saved_as_numpy_arrays.hdf5"), "w", track_order=True) as h5OutFile:
- with concurrent.futures.ThreadPoolExecutor(max_workers=numCams+1) as executor:
- # barrier = threading.Barrier(numCams, action=saveMultiViewToH5)
- barrier = threading.Barrier(numCams, action=saveMultiViewToMP4)
- for camNum, camCap in enumerate(camCap_list):
- print('starting thread for cam# '+str(camNum))
- executor.submit(CamRecordThread, camCap, webcam_frames_queue, barrier, exit_event, camNum)
-
- executor.submit(ShowMultiView, multiFrame_queue, outputVidObj)
- # print('starting frame handler')
- # executor.submit(incoming_frames_handler, webcam_frames_queue, exit_event)
-
- runtime = 10
- logging.info("Main: Record for {} seconds".format(runtime))
- time.sleep(runtime)
-
- exit_event.set() #send the 'Exit' signal to everyone
- print('closing streams, I guess?')
-
- print('closing h5 file too, I think?')
-
- print('all done!')
-
-
-
-
-# %% get multiFrame framerate and frameTimespread
- camTimestamps = np.stack(camTimestamps_list, axis=0) #a nice, matlaby 2d array
- meanMultiFrameTimestamp = np.mean(camTimestamps, axis=0)
- meanMultiFrameTimespan = np.max(camTimestamps, axis=0) - np.min(camTimestamps, axis=0) #what was the timespan covered by each frame
-#%%
-plt.ion()
-fig = plt.figure(figsize=(18,10))
-max_frame_duration = .1
-ax1 = plt.subplot(231, title='Camera Frame Timestamp vs Frame#', xlabel='Frame#', ylabel='Timestamp (sec)')
-ax2 = plt.subplot(232, ylim=(0,max_frame_duration), title='Camera Frame Duration Trace', xlabel='Frame#', ylabel='Duration (sec)')
-ax3 = plt.subplot(233, xlim=(0,max_frame_duration), title='Camera Frame Duration Histogram (count)', xlabel='Duration(s, 1ms bins)', ylabel='Probability')
-ax4 = plt.subplot(234, title='MuliFrame Timestamp vs Frame#', xlabel='Frame#', ylabel='Timestamp (sec)')
-ax5 = plt.subplot(235, ylim=(0,max_frame_duration), title='Multi Frame Duration/Span Trace', xlabel='Frame#', ylabel='Duration (sec)')
-ax6 = plt.subplot(236, xlim=(0,max_frame_duration), title='MultiFrame Duration Histogram (count)', xlabel='Duration(s, 1ms bins)', ylabel='Probability')
-
-for camNum, thisCamTimestamps in enumerate(camTimestamps_list):
- ax1.plot(thisCamTimestamps, label='Camera#'+str(camNum))
- ax1.legend()
- ax2.plot(np.diff(thisCamTimestamps),'.')
- ax3.hist(np.diff(thisCamTimestamps), bins=np.arange(0,max_frame_duration,.001), alpha=0.5)
-
-ax4.plot(meanMultiFrameTimestamp, color='darkslategrey', label='MultiFrame'+str(camNum))
-ax5.plot(np.diff(meanMultiFrameTimestamp),'.',color='darkslategrey', label='Frame Duration')
-ax5.plot(meanMultiFrameTimespan, '.', color='orangered', label='Frame TimeSpan')
-ax5.legend()
-ax6.hist(np.diff(meanMultiFrameTimestamp), bins=np.arange(0,max_frame_duration,.001), density=True, alpha=0.5, color='darkslategrey', label='Frame Duration')
-ax6.hist(np.diff(meanMultiFrameTimespan), bins=np.arange(0,max_frame_duration,.001), density=True, alpha=0.5, color='orangered', label='Frame Timespan')
-ax5.legend()
-plt.show()
-plt.savefig(str(vidSaveFolderPath / 'recording_diagnostics.png'))
-f=9
-
-
-# outVidObj.release()
\ No newline at end of file
diff --git a/freemocap/dev_scratchpad/dev_alpha_old/scratch/fmc_pyfiglet.py b/freemocap/dev_scratchpad/dev_alpha_old/scratch/fmc_pyfiglet.py
deleted file mode 100644
index ca4e416e..00000000
--- a/freemocap/dev_scratchpad/dev_alpha_old/scratch/fmc_pyfiglet.py
+++ /dev/null
@@ -1,20 +0,0 @@
-from pyfiglet import Figlet
-
-def figlet(input_string, font_name='banner3'):
- """simple wrapper for pyfiglet, take in string and retrun in figlet ascii format (default font ('banner3')"""
-
- f = Figlet(font=font_name)
-
- return f.renderText(str(input_string))
-
-if __name__== '__main__':
- import sys
- input_string = ''
-
- for thisArg in sys.argv[1:]:
- input_string = input_string + thisArg +' '
-
- if not input_string:
- input_string = 'henlo big txt'
-
- print(figlet(input_string))
diff --git a/freemocap/dev_scratchpad/dev_alpha_old/scratch/geeksforgeeks_qt_camera.py b/freemocap/dev_scratchpad/dev_alpha_old/scratch/geeksforgeeks_qt_camera.py
deleted file mode 100644
index e560af2e..00000000
--- a/freemocap/dev_scratchpad/dev_alpha_old/scratch/geeksforgeeks_qt_camera.py
+++ /dev/null
@@ -1,216 +0,0 @@
-# importing required libraries
-from PyQt5.QtWidgets import *
-from PyQt5.QtMultimedia import *
-from PyQt5.QtMultimediaWidgets import *
-import os
-import sys
-import time
-
-# Main window class
-class MainWindow(QMainWindow):
-
- # constructor
- def __init__(self):
- super().__init__()
-
- # setting geometry
- self.setGeometry(100, 100,
- 800, 600)
-
- # setting style sheet
- self.setStyleSheet("background : lightgrey;")
-
- # getting available cameras
- self.available_cameras = QCameraInfo.availableCameras()
-
- # if no camera found
- if not self.available_cameras:
- # exit the code
- sys.exit()
-
- # creating a status bar
- self.status = QStatusBar()
-
- # setting style sheet to the status bar
- self.status.setStyleSheet("background : white;")
-
- # adding status bar to the main window
- self.setStatusBar(self.status)
-
- # path to save
- self.save_path = ""
-
- # creating a QCameraViewfinder object
- self.viewfinder = QCameraViewfinder()
-
- # showing this viewfinder
- self.viewfinder.show()
-
- # making it central widget of main window
- self.setCentralWidget(self.viewfinder)
-
- # Set the default camera.
- self.select_camera(0)
-
- # creating a tool bar
- toolbar = QToolBar("Camera Tool Bar")
-
- # adding tool bar to main window
- self.addToolBar(toolbar)
-
- # creating a photo action to take photo
- click_action = QAction("Click photo", self)
-
- # adding status tip to the photo action
- click_action.setStatusTip("This will capture picture")
-
- # adding tool tip
- click_action.setToolTip("Capture picture")
-
-
- # adding action to it
- # calling take_photo method
- click_action.triggered.connect(self.click_photo)
-
- # adding this to the tool bar
- toolbar.addAction(click_action)
-
- # similarly creating action for changing save folder
- change_folder_action = QAction("Change save location",
- self)
-
- # adding status tip
- change_folder_action.setStatusTip("Change folder where picture will be saved saved.")
-
- # adding tool tip to it
- change_folder_action.setToolTip("Change save location")
-
- # setting calling method to the change folder action
- # when triggered signal is emitted
- change_folder_action.triggered.connect(self.change_folder)
-
- # adding this to the tool bar
- toolbar.addAction(change_folder_action)
-
-
- # creating a combo box for selecting camera
- camera_selector = QComboBox()
-
- # adding status tip to it
- camera_selector.setStatusTip("Choose camera to take pictures")
-
- # adding tool tip to it
- camera_selector.setToolTip("Select Camera")
- camera_selector.setToolTipDuration(2500)
-
- # adding items to the combo box
- camera_selector.addItems([camera.description()
- for camera in self.available_cameras])
-
- # adding action to the combo box
- # calling the select camera method
- camera_selector.currentIndexChanged.connect(self.select_camera)
-
- # adding this to tool bar
- toolbar.addWidget(camera_selector)
-
- # setting tool bar stylesheet
- toolbar.setStyleSheet("background : white;")
-
-
-
- # setting window title
- self.setWindowTitle("PyQt5 Cam")
-
- # showing the main window
- self.show()
-
- # method to select camera
- def select_camera(self, i):
-
- # getting the selected camera
- self.camera = QCamera(self.available_cameras[i])
-
- # setting view finder to the camera
- self.camera.setViewfinder(self.viewfinder)
-
- # setting capture mode to the camera
- self.camera.setCaptureMode(QCamera.CaptureStillImage)
-
- # if any error occur show the alert
- self.camera.error.connect(lambda: self.alert(self.camera.errorString()))
-
- # start the camera
- self.camera.start()
-
- # creating a QCameraImageCapture object
- self.capture = QCameraImageCapture(self.camera)
-
- # showing alert if error occur
- self.capture.error.connect(lambda error_msg, error,
- msg: self.alert(msg))
-
- # when image captured showing message
- self.capture.imageCaptured.connect(lambda d,
- i: self.status.showMessage("Image captured : "
- + str(self.save_seq)))
-
- # getting current camera name
- self.current_camera_name = self.available_cameras[i].description()
-
- # inital save sequence
- self.save_seq = 0
-
- # method to take photo
- def click_photo(self):
-
- # time stamp
- timestamp = time.strftime("%d-%b-%Y-%H_%M_%S")
-
- # capture the image and save it on the save path
- self.capture.capture(os.path.join(self.save_path,
- "%s-%04d-%s.jpg" % (
- self.current_camera_name,
- self.save_seq,
- timestamp
- )))
-
- # increment the sequence
- self.save_seq += 1
-
- # change folder method
- def change_folder(self):
-
- # open the dialog to select path
- path = QFileDialog.getExistingDirectory(self,
- "Picture Location", "")
-
- # if path is selected
- if path:
-
- # update the path
- self.save_path = path
-
- # update the sequence
- self.save_seq = 0
-
- # method for alerts
- def alert(self, msg):
-
- # error message
- error = QErrorMessage(self)
-
- # setting text to the error message
- error.showMessage(msg)
-
-# Driver code
-if __name__ == "__main__" :
-
- # create pyqt5 app
- App = QApplication(sys.argv)
-
- # create the instance of our Window
- window = MainWindow()
-
- # start the app
- sys.exit(App.exec())
diff --git a/freemocap/dev_scratchpad/dev_alpha_old/scratch/jsm_cam_VideoSpeedTest.py b/freemocap/dev_scratchpad/dev_alpha_old/scratch/jsm_cam_VideoSpeedTest.py
deleted file mode 100644
index 32723a88..00000000
--- a/freemocap/dev_scratchpad/dev_alpha_old/scratch/jsm_cam_VideoSpeedTest.py
+++ /dev/null
@@ -1,313 +0,0 @@
-#jsm - 2021-Oct-23 - based on pyqtgrph.example VideoSpeedTest
-
-# -*- coding: utf-8 -*-
-"""
-Tests the speed of image updates for an ImageItem and RawImageWidget.
-The speed will generally depend on the type of data being shown, whether
-it is being scaled and/or converted by lookup table, and whether OpenGL
-is used by the view widget
-"""
-
-
-import argparse
-import sys
-
-import numpy as np
-
-import pyqtgraph as pg
-from pyqtgraph.Qt import QtGui, QtCore, QT_LIB
-from time import perf_counter
-
-import cv2
-
-pg.setConfigOption('imageAxisOrder', 'row-major')
-
-import importlib
-ui_template = importlib.import_module(f'VideoTemplate_{QT_LIB.lower()}')
-
-try:
- import cupy as cp
- pg.setConfigOption("useCupy", True)
- _has_cupy = True
-except ImportError:
- cp = None
- _has_cupy = False
-
-try:
- import numba
- _has_numba = True
-except ImportError:
- numba = None
- _has_numba = False
-
-try:
- from pyqtgraph.widgets.RawImageWidget import RawImageGLWidget
-except ImportError:
- RawImageGLWidget = None
-
-parser = argparse.ArgumentParser(description="Benchmark for testing video performance")
-parser.add_argument('--cuda', default=False, action='store_true', help="Use CUDA to process on the GPU", dest="cuda")
-parser.add_argument('--dtype', default='uint8', choices=['uint8', 'uint16', 'float'], help="Image dtype (uint8, uint16, or float)")
-parser.add_argument('--frames', default=3, type=int, help="Number of image frames to generate (default=3)")
-parser.add_argument('--image-mode', default='mono', choices=['mono', 'rgb'], help="Image data mode (mono or rgb)", dest='image_mode')
-parser.add_argument('--levels', default=None, type=lambda s: tuple([float(x) for x in s.split(',')]), help="min,max levels to scale monochromatic image dynamic range, or rmin,rmax,gmin,gmax,bmin,bmax to scale rgb")
-parser.add_argument('--lut', default=False, action='store_true', help="Use color lookup table")
-parser.add_argument('--lut-alpha', default=False, action='store_true', help="Use alpha color lookup table", dest='lut_alpha')
-parser.add_argument('--size', default='512x512', type=lambda s: tuple([int(x) for x in s.split('x')]), help="WxH image dimensions default='512x512'")
-args = parser.parse_args(sys.argv[1:])
-
-if RawImageGLWidget is not None:
- # don't limit frame rate to vsync
- sfmt = QtGui.QSurfaceFormat()
- sfmt.setSwapInterval(0)
- QtGui.QSurfaceFormat.setDefaultFormat(sfmt)
-
-app = pg.mkQApp("Video Speed Test Example")
-
-win = QtGui.QMainWindow()
-win.setWindowTitle('pyqtgraph example: VideoSpeedTest')
-ui = ui_template.Ui_MainWindow()
-ui.setupUi(win)
-win.show()
-
-if RawImageGLWidget is None:
- ui.rawGLRadio.setEnabled(False)
- ui.rawGLRadio.setText(ui.rawGLRadio.text() + " (OpenGL not available)")
-else:
- ui.rawGLImg = RawImageGLWidget()
- ui.stack.addWidget(ui.rawGLImg)
-
-# read in CLI args
-ui.cudaCheck.setChecked(args.cuda and _has_cupy)
-ui.cudaCheck.setEnabled(_has_cupy)
-ui.numbaCheck.setChecked(_has_numba and pg.getConfigOption("useNumba"))
-ui.numbaCheck.setEnabled(_has_numba)
-ui.framesSpin.setValue(args.frames)
-ui.widthSpin.setValue(args.size[0])
-ui.heightSpin.setValue(args.size[1])
-ui.dtypeCombo.setCurrentText(args.dtype)
-ui.rgbCheck.setChecked(args.image_mode=='rgb')
-ui.maxSpin1.setOpts(value=255, step=1)
-ui.minSpin1.setOpts(value=0, step=1)
-levelSpins = [ui.minSpin1, ui.maxSpin1, ui.minSpin2, ui.maxSpin2, ui.minSpin3, ui.maxSpin3]
-if args.cuda and _has_cupy:
- xp = cp
-else:
- xp = np
-if args.levels is None:
- ui.scaleCheck.setChecked(False)
- ui.rgbLevelsCheck.setChecked(False)
-else:
- ui.scaleCheck.setChecked(True)
- if len(args.levels) == 2:
- ui.rgbLevelsCheck.setChecked(False)
- ui.minSpin1.setValue(args.levels[0])
- ui.maxSpin1.setValue(args.levels[1])
- elif len(args.levels) == 6:
- ui.rgbLevelsCheck.setChecked(True)
- for spin,val in zip(levelSpins, args.levels):
- spin.setValue(val)
- else:
- raise ValueError("levels argument must be 2 or 6 comma-separated values (got %r)" % (args.levels,))
-ui.lutCheck.setChecked(args.lut)
-ui.alphaCheck.setChecked(args.lut_alpha)
-
-
-#ui.graphicsView.useOpenGL() ## buggy, but you can try it if you need extra speed.
-
-vb = pg.ViewBox()
-ui.graphicsView.setCentralItem(vb)
-vb.setAspectLocked()
-pg_img = pg.ImageItem()
-vb.addItem(pg_img)
-
-
-cap = cv2.VideoCapture(0, cv2.CAP_DSHOW)
-success, image = cap.read()
-assert success, 'Camera Failed to load image'
-vidWidth, vidHeight, vidNumColorChannels = image.shape
-
-
-
-
-LUT = None
-def updateLUT():
- global LUT, ui
- dtype = ui.dtypeCombo.currentText()
- if dtype == 'uint8':
- n = 256
- else:
- n = 4096
- LUT = ui.gradient.getLookupTable(n, alpha=ui.alphaCheck.isChecked())
- if _has_cupy and xp == cp:
- LUT = cp.asarray(LUT)
-ui.gradient.sigGradientChanged.connect(updateLUT)
-updateLUT()
-
-ui.alphaCheck.toggled.connect(updateLUT)
-
-def updateScale():
- global ui, levelSpins
- if ui.rgbLevelsCheck.isChecked():
- for s in levelSpins[2:]:
- s.setEnabled(True)
- else:
- for s in levelSpins[2:]:
- s.setEnabled(False)
-
-updateScale()
-
-ui.rgbLevelsCheck.toggled.connect(updateScale)
-
-cache = {}
-def mkData():
- with pg.BusyCursor():
- global data, cache, ui, xp
- frames = ui.framesSpin.value()
- width = ui.widthSpin.value()
- height = ui.heightSpin.value()
- cacheKey = (ui.dtypeCombo.currentText(), ui.rgbCheck.isChecked(), frames, width, height)
- if cacheKey not in cache:
- if cacheKey[0] == 'uint8':
- dt = xp.uint8
- loc = 128
- scale = 64
- mx = 255
- elif cacheKey[0] == 'uint16':
- dt = xp.uint16
- loc = 4096
- scale = 1024
- mx = 2**16 - 1
- elif cacheKey[0] == 'float':
- dt = xp.float32
- loc = 1.0
- scale = 0.1
- mx = 1.0
- else:
- raise ValueError(f"unable to handle dtype: {cacheKey[0]}")
-
- chan_shape = (height, width)
- if ui.rgbCheck.isChecked():
- frame_shape = chan_shape + (3,)
- else:
- frame_shape = chan_shape
- data = xp.empty((frames,) + frame_shape, dtype=dt)
- view = data.reshape((-1,) + chan_shape)
- for idx in range(view.shape[0]):
- subdata = xp.random.normal(loc=loc, scale=scale, size=chan_shape)
- # note: gaussian filtering has been removed as it slows down array
- # creation greatly.
- if cacheKey[0] != 'float':
- xp.clip(subdata, 0, mx, out=subdata)
- view[idx] = subdata
-
- data[:, 10:50, 10] = mx
- data[:, 48, 9:12] = mx
- data[:, 47, 8:13] = mx
- cache = {cacheKey: data} # clear to save memory (but keep one to prevent unnecessary regeneration)
-
- data = cache[cacheKey]
- updateLUT()
- updateSize()
-
-def updateSize():
- global ui, vb
- frames = ui.framesSpin.value()
- width = ui.widthSpin.value()
- height = ui.heightSpin.value()
- dtype = xp.dtype(str(ui.dtypeCombo.currentText()))
- rgb = 3 if ui.rgbCheck.isChecked() else 1
- ui.sizeLabel.setText('%d MB' % (frames * width * height * rgb * dtype.itemsize / 1e6))
- vb.setRange(QtCore.QRectF(0, 0, width, height))
-
-
-def noticeCudaCheck():
- global xp, cache
- cache = {}
- if ui.cudaCheck.isChecked():
- if _has_cupy:
- xp = cp
- else:
- xp = np
- ui.cudaCheck.setChecked(False)
- else:
- xp = np
- mkData()
-
-
-def noticeNumbaCheck():
- pg.setConfigOption('useNumba', _has_numba and ui.numbaCheck.isChecked())
-
-
-mkData()
-
-
-ui.dtypeCombo.currentIndexChanged.connect(mkData)
-ui.rgbCheck.toggled.connect(mkData)
-ui.widthSpin.editingFinished.connect(mkData)
-ui.heightSpin.editingFinished.connect(mkData)
-ui.framesSpin.editingFinished.connect(mkData)
-
-ui.widthSpin.valueChanged.connect(updateSize)
-ui.heightSpin.valueChanged.connect(updateSize)
-ui.framesSpin.valueChanged.connect(updateSize)
-ui.cudaCheck.toggled.connect(noticeCudaCheck)
-ui.numbaCheck.toggled.connect(noticeNumbaCheck)
-
-
-ptr = 0
-lastTime = perf_counter()
-fps = None
-def update():
- global ui, ptr, lastTime, fps, LUT, pg_img
- if ui.lutCheck.isChecked():
- useLut = LUT
- else:
- useLut = None
-
- downsample = ui.downsampleCheck.isChecked()
-
- if ui.scaleCheck.isChecked():
- if ui.rgbLevelsCheck.isChecked():
- useScale = [
- [ui.minSpin1.value(), ui.maxSpin1.value()],
- [ui.minSpin2.value(), ui.maxSpin2.value()],
- [ui.minSpin3.value(), ui.maxSpin3.value()]]
- else:
- useScale = [ui.minSpin1.value(), ui.maxSpin1.value()]
- else:
- useScale = None
-
- #read image from camera
- success, image = cap.read()
- assert success, 'Camera Failed to load image'
- image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) #convert image from BGR to RGB color format
-
- if ui.rawRadio.isChecked():
- ui.rawImg.setImage(image, lut=useLut, levels=useScale)
- ui.stack.setCurrentIndex(1)
- elif ui.rawGLRadio.isChecked():
- ui.rawGLImg.setImage(image, lut=useLut, levels=useScale)
- ui.stack.setCurrentIndex(2)
- else:
- pg_img.setImage(cv2.rotate(image, cv2.ROTATE_180), autoLevels=False, levels=useScale, lut=useLut, autoDownsample=downsample)
- ui.stack.setCurrentIndex(0)
- #img.setImage(data[ptr%data.shape[0]], autoRange=False)
-
- ptr += 1
- now = perf_counter()
- dt = now - lastTime
- lastTime = now
- if fps is None:
- fps = 1.0/dt
- else:
- s = np.clip(dt*3., 0, 1)
- fps = fps * (1-s) + (1.0/dt) * s
- ui.fpsLabel.setText('%0.2f timestamp_manager' % fps)
- app.processEvents() ## force complete redraw for every plot
-timer = QtCore.QTimer()
-timer.timeout.connect(update)
-timer.start(0)
-
-if __name__ == '__main__':
- pg.exec()
diff --git a/freemocap/dev_scratchpad/dev_alpha_old/scratch/jsm_cam_VideoSpeedTest_minimal.py b/freemocap/dev_scratchpad/dev_alpha_old/scratch/jsm_cam_VideoSpeedTest_minimal.py
deleted file mode 100644
index c043dbb3..00000000
--- a/freemocap/dev_scratchpad/dev_alpha_old/scratch/jsm_cam_VideoSpeedTest_minimal.py
+++ /dev/null
@@ -1,105 +0,0 @@
-#jsm - 2021-Oct-23 - based on pyqtgrph.example VideoSpeedTest (gutted to simplest form)
-
-import sys
-
-import numpy as np
-
-import pyqtgraph as pg
-from pyqtgraph.Qt import QtGui, QtCore, QT_LIB
-from time import perf_counter
-
-import cv2
-
-pg.setConfigOption('imageAxisOrder', 'row-major')
-
-import importlib
-ui_template = importlib.import_module(f'VideoTemplate_{QT_LIB.lower()}')
-
-try:
- from pyqtgraph.widgets.RawImageWidget import RawImageGLWidget
-except ImportError:
- RawImageGLWidget = None
-
-
-
-if RawImageGLWidget is not None:
- # don't limit frame rate to vsync
- sfmt = QtGui.QSurfaceFormat()
- sfmt.setSwapInterval(0)
- QtGui.QSurfaceFormat.setDefaultFormat(sfmt)
-
-app = pg.mkQApp("Simple QT Webcam Viewer")
-
-win = QtGui.QMainWindow()
-win.setWindowTitle(' based on - pyqtgraph example: VideoSpeedTest')
-ui = ui_template.Ui_MainWindow()
-ui.setupUi(win)
-win.show()
-
-if RawImageGLWidget is None:
- ui.rawGLRadio.setEnabled(False)
- ui.rawGLRadio.setText(ui.rawGLRadio.text() + " (OpenGL not available)")
-else:
- ui.rawGLImg = RawImageGLWidget()
- ui.stack.addWidget(ui.rawGLImg)
-
-vb = pg.ViewBox()
-ui.graphicsView.setCentralItem(vb)
-vb.setAspectLocked()
-pg_img = pg.ImageItem()
-vb.addItem(pg_img)
-
-
-cap = cv2.VideoCapture(0, cv2.CAP_DSHOW)
-
-cap.set(cv2.CAP_PROP_EXPOSURE, -7)
-
-cap.set(cv2.CAP_PROP_FRAME_WIDTH, 640)
-cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 480)
-
-cap.set(cv2.CAP_PROP_FOURCC, cv2.VideoWriter_fourcc('M', 'J', 'P', 'G'))
-
-success, image = cap.read()
-assert success, 'Camera Failed to load image'
-vidWidth, vidHeight, vidNumColorChannels = image.shape
-
-
-
-ptr = 0
-lastTime = perf_counter()
-fps = None
-def update():
- global ui, lastTime, fps, pg_img
-
- #read image from camera
- success, image = cap.read()
- assert success, 'Camera Failed to load image'
- image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) #convert image from BGR to RGB color format
-
- if ui.rawRadio.isChecked():
- ui.rawImg.setImage(image)
- ui.stack.setCurrentIndex(1)
- elif ui.rawGLRadio.isChecked():
- ui.rawGLImg.setImage(image)
- ui.stack.setCurrentIndex(2)
- else:
- pg_img.setImage(cv2.rotate(image, cv2.ROTATE_180))
- ui.stack.setCurrentIndex(0)
-
-
- now = perf_counter()
- dt = now - lastTime
- lastTime = now
- if fps is None:
- fps = 1.0/dt
- else:
- s = np.clip(dt*3., 0, 1)
- fps = fps * (1-s) + (1.0/dt) * s
- ui.fpsLabel.setText('%0.2f timestamp_manager' % fps)
- app.processEvents() ## force complete redraw for every plot
-timer = QtCore.QTimer()
-timer.timeout.connect(update)
-timer.start(0)
-
-if __name__ == '__main__':
- pg.exec()
diff --git a/freemocap/dev_scratchpad/dev_alpha_old/scratch/kinda_gui/test_gui.py b/freemocap/dev_scratchpad/dev_alpha_old/scratch/kinda_gui/test_gui.py
deleted file mode 100644
index 6956929a..00000000
--- a/freemocap/dev_scratchpad/dev_alpha_old/scratch/kinda_gui/test_gui.py
+++ /dev/null
@@ -1,97 +0,0 @@
-import sys
-import time
-# Import QApplication and the required widgets from PyQt5.QtWidgets
-
-
-from PyQt5.QtCore import Qt
-from PyQt5.QtWidgets import QApplication
-from PyQt5.QtWidgets import QMainWindow
-from PyQt5.QtWidgets import QWidget
-from PyQt5.QtWidgets import QLineEdit
-from PyQt5.QtWidgets import QPushButton
-from PyQt5.QtWidgets import QCheckBox
-from PyQt5.QtWidgets import QHBoxLayout
-from PyQt5.QtWidgets import QVBoxLayout
-from PyQt5.QtWidgets import QLabel
-from test_iPython_gui import IPythonConsoleWidget
-
-from PyQt5.QtGui import QPixmap
-
-import freemocap as fmc
-
-sessionParam_dict = {
- "useOpenPose": False,
-}
-
-def import_fmc():
-
- import_text = 'import freemocap as fmc'
- print('sending command:' + import_text)
-
- iPyWidget.print_text(import_text)
- iPyWidget.execute_command(import_text)
-
-def set_useOpenPose(useOpenPose_button):
-
- if useOpenPose_button.isChecked():
- sessionParam_dict['useOpenPose'] = True
- runMeButton.setText('fmc.RunMe(useOpenPose=True)')
- else:
- sessionParam_dict['useOpenPose'] = False
- runMeButton.setText('fmc.RunMe()')
-
-
-def run_fmc():
- useOpenPoseBool = sessionParam_dict['useOpenPose']
- fmc.RunMe(useOpenPose=useOpenPoseBool)
-
- # fmc_runme_text = 'fmc.RunMe()'
- # print('sending command:' + fmc_runme_text)
-
- # iPyWidget.print_text(fmc_runme_text)
- # iPyWidget.execute_command(fmc_runme_text)
-
-app = QApplication(sys.argv)
-
-window = QWidget()
-window.setWindowTitle('PyQT Test')
-
-main_layout = QHBoxLayout() #This is the whole GUI window
-
-# logo_label = QLabel()
-# logo_pixmap = QPixmap('freemocap-logo--blackOutline_squareTransCanvas-01.png')
-# logo_label.setPixmap(logo_pixmap)
-# logo_label.setScaledContents(True)
-# main_layout.addWidget(logo_label)
-
-
-#Make a vertical box of check boxes
-button_layout = QVBoxLayout()
-
-useOpenPose_button = QCheckBox('useOpenPose')
-useOpenPose_button.stateChanged.connect(set_useOpenPose)
-button_layout.addWidget(QCheckBox('useOpenPose'))
-# button_layout.addWidget(QCheckBox('useDLC'))
-# button_layout.addWidget(QCheckBox('useMediaPipe'))
-
-# importFMC_button = QPushButton('import freemocap as fmc')
-# importFMC_button.clicked.connect(import_fmc)
-# button_layout.addWidget(importFMC_button)
-
-
-runMeButton = QPushButton('fmc.RunMe()')
-runMeButton.clicked.connect(run_fmc)
-button_layout.addWidget(runMeButton)
-
-main_layout.addLayout(button_layout)
-
-
-#Add the IpYthon console widget
-iPyWidget = IPythonConsoleWidget()
-main_layout.addWidget(iPyWidget)
-iPyWidget.print_text('import freemocap as fmc')
-
-window.setLayout(main_layout)
-
-window.show()
-sys.exit(app.exec_())
\ No newline at end of file
diff --git a/freemocap/dev_scratchpad/dev_alpha_old/scratch/kinda_gui/test_iPython_gui.py b/freemocap/dev_scratchpad/dev_alpha_old/scratch/kinda_gui/test_iPython_gui.py
deleted file mode 100644
index f683ad59..00000000
--- a/freemocap/dev_scratchpad/dev_alpha_old/scratch/kinda_gui/test_iPython_gui.py
+++ /dev/null
@@ -1,61 +0,0 @@
-# originially cribbed from - https://stackoverflow.com/a/67829211/14662833
-
-from qtpy.QtWidgets import QApplication
-from qtconsole.rich_jupyter_widget import RichJupyterWidget
-from qtconsole.inprocess import QtInProcessKernelManager
-
-
-class IPythonConsoleWidget(RichJupyterWidget):
-
- def __init__(self, customBanner=None, *args, **kwargs):
- super(IPythonConsoleWidget, self).__init__(*args, **kwargs)
-
- if customBanner is not None:
- self.banner = customBanner
-
- self.font_size = 10
- self.kernel_manager = QtInProcessKernelManager()
- self.kernel_manager.start_kernel(show_banner=False)
- self.kernel_manager.kernel.gui = 'qt'
- self.kernel_client = self._kernel_manager.client()
- self.kernel_client.start_channels()
-
- def stop():
- self.kernel_client.stop_channels()
- self.kernel_manager.shutdown_kernel()
- self.guisupport.get_app_qt().exit()
-
- self.exit_requested.connect(stop)
-
- def push_vars(self, variableDict):
- """
- Given a dictionary containing name / value pairs, push those variables
- to the Jupyter console widget
- """
- self.kernel_manager.kernel.shell.push(variableDict)
-
- def clear(self):
- """
- Clears the terminal
- """
- self._control.clear()
-
- def print_text(self, text):
- """
- Prints some plain text to the console
- """
- self._append_plain_text(text)
-
- def execute_command(self, command):
- """
- Execute a command in the frame of the console widget
- """
- self._execute(command, False)
-
-
-
-if __name__ == '__main__':
- app = QApplication([])
- widget = IPythonConsoleWidget()
- widget.show()
- app.exec_()
\ No newline at end of file
diff --git a/freemocap/dev_scratchpad/dev_alpha_old/scratch/qt_cv_webcam_tutorial/models.py b/freemocap/dev_scratchpad/dev_alpha_old/scratch/qt_cv_webcam_tutorial/models.py
deleted file mode 100644
index 756d6ac6..00000000
--- a/freemocap/dev_scratchpad/dev_alpha_old/scratch/qt_cv_webcam_tutorial/models.py
+++ /dev/null
@@ -1,41 +0,0 @@
-# from - https://www.pythonforthelab.com/blog/step-by-step-guide-to-building-a-gui/
-
-import cv2
-
-class Camera:
- def __init__(self, cam_num):
- self.cap = None
- self.cam_num = cam_num
-
- def initialize(self):
- self.cap = cv2.VideoCapture(self.cam_num, cv2.CAP_DSHOW)
- self.cap.set(cv2.CAP_PROP_FOURCC, cv2.VideoWriter_fourcc('M', 'J', 'P', 'G'))
-
- def get_frame(self):
- success_bool, self.last_frame = self.cap.read()
- return self.last_frame
-
- def acquire_movie(self, num_frames):
- movie = []
- for _ in range(num_frames):
- movie.append(self.get_frame())
-
- return movie
-
- def set_brightness(self, value):
- self.cap.set(cv2.CAP_PROP_BRIGHTNESS, value)
-
- def get_brightness(self):
- return self.cap.get(cv2.CAP_PROP_BRIGHTNESS)
-
- def __str__(self):
- return 'OpenCV Camera {}'.format(self.cam_num)
-
- def close_camera(self):
- self.cap.release()
-
-if __name__ == '__main__':
- cam = Camera(0)
- cam.initialize()
- print(cam)
- cam.close_camera()
\ No newline at end of file
diff --git a/freemocap/dev_scratchpad/dev_alpha_old/scratch/qt_cv_webcam_tutorial/pyqtgraph_parameter_tree.py b/freemocap/dev_scratchpad/dev_alpha_old/scratch/qt_cv_webcam_tutorial/pyqtgraph_parameter_tree.py
deleted file mode 100644
index 8886464b..00000000
--- a/freemocap/dev_scratchpad/dev_alpha_old/scratch/qt_cv_webcam_tutorial/pyqtgraph_parameter_tree.py
+++ /dev/null
@@ -1,96 +0,0 @@
-"""
-This example demonstrates the use of pyqtgraph's parametertree system. This provides
-a simple way to generate user interfaces that control sets of parameters. The example
-demonstrates a variety of different parameter types (int, float, list, etc.)
-as well as some customized parameter types
-
-"""
-import pyqtgraph as pg
-# `makeAllParamTypes` creates several parameters from a dictionary of config specs.
-# This contains information about the options for each parameter so they can be directly
-# inserted into the example parameter tree. To create your own parameters, simply follow
-# the guidelines demonstrated by other parameters created here.
-from pyqtgraph.Qt import QtGui
-
-
-app = pg.mkQApp("Parameter Tree Example")
-import pyqtgraph.parametertree.parameterTypes as pTypes
-from pyqtgraph.parametertree import Parameter, ParameterTree
-
-
-params = [
- # makeAllParamTypes(),
- {'name': 'Camera Parameters', 'type': 'group', 'children': [
- {'name': 'Save State', 'type': 'action'},
- {'name': 'Restore State', 'type': 'action', 'children': [
- {'name': 'Add missing items', 'type': 'bool', 'value': True},
- {'name': 'Remove extra items', 'type': 'bool', 'value': True},
- ]},
- ]},
- {'name': 'Custom context menu', 'type': 'group', 'children': [
- {'name': 'List contextMenu', 'type': 'float', 'value': 0, 'context': [
- 'menu1',
- 'menu2'
- ]},
- {'name': 'Dict contextMenu', 'type': 'float', 'value': 0, 'context': {
- 'changeName': 'Title',
- 'internal': 'What the user sees',
- }},
- ]},
-]
-
-## Create tree of Parameter objects
-p = Parameter.create(name='params', type='group', children=params)
-
-## If anything changes in the tree, print a message
-def change(param, changes):
- print("tree changes:")
- for param, change, data in changes:
- path = p.childPath(param)
- if path is not None:
- childName = '.'.join(path)
- else:
- childName = param.name()
- print(' parameter: %s'% childName)
- print(' change: %s'% change)
- print(' data: %s'% str(data))
- print(' ----------')
-
-p.sigTreeStateChanged.connect(change)
-
-
-def valueChanging(param, value):
- print("Value changing (not finalized): %s %s" % (param, value))
-
-# Too lazy for recursion:
-for child in p.children():
- child.sigValueChanging.connect(valueChanging)
- for ch2 in child.children():
- ch2.sigValueChanging.connect(valueChanging)
-
-
-
-
-## Create two ParameterTree widgets, both accessing the same data
-t = ParameterTree()
-t.setParameters(p, showTop=False)
-t.setWindowTitle('pyqtgraph example: Parameter Tree')
-t2 = ParameterTree()
-t2.setParameters(p, showTop=False)
-
-win = QtGui.QWidget()
-layout = QtGui.QGridLayout()
-win.setLayout(layout)
-layout.addWidget(QtGui.QLabel("These are two views of the same data. They should always display the same values."), 0, 0, 1, 2)
-layout.addWidget(t, 1, 0, 1, 1)
-layout.addWidget(t2, 1, 1, 1, 1)
-win.show()
-
-## test save/restore
-state = p.saveState()
-p.restoreState(state)
-compareState = p.saveState()
-assert pg.eq(compareState, state)
-
-if __name__ == '__main__':
- pg.exec()
diff --git a/freemocap/dev_scratchpad/dev_alpha_old/scratch/qt_cv_webcam_tutorial/qt_cv_webcam_tut.py b/freemocap/dev_scratchpad/dev_alpha_old/scratch/qt_cv_webcam_tutorial/qt_cv_webcam_tut.py
deleted file mode 100644
index 4d46914c..00000000
--- a/freemocap/dev_scratchpad/dev_alpha_old/scratch/qt_cv_webcam_tutorial/qt_cv_webcam_tut.py
+++ /dev/null
@@ -1,25 +0,0 @@
-# from - https://www.pythonforthelab.com/blog/step-by-step-guide-to-building-a-gui/
-from PyQt5.QtWidgets import QApplication, QMainWindow, QPushButton, QVBoxLayout, QWidget
-
-def button_pressed():
- print('button done been pressed')
-
-app = QApplication([])
-main_window = QMainWindow()
-central_widget = QWidget()
-
-button_1 = QPushButton("test1", central_widget)
-button_1.clicked.connect(button_pressed)
-
-button_2 = QPushButton("test2", central_widget)
-button_2.clicked.connect(button_pressed)
-
-layout = QVBoxLayout(central_widget)
-layout.addWidget(button_2)
-layout.addWidget(button_1)
-
-main_window.setCentralWidget(central_widget)
-
-main_window.show()
-
-app.exit(app.exec_())
\ No newline at end of file
diff --git a/freemocap/dev_scratchpad/dev_alpha_old/scratch/qt_cv_webcam_tutorial/start.py b/freemocap/dev_scratchpad/dev_alpha_old/scratch/qt_cv_webcam_tutorial/start.py
deleted file mode 100644
index 147c0ae3..00000000
--- a/freemocap/dev_scratchpad/dev_alpha_old/scratch/qt_cv_webcam_tutorial/start.py
+++ /dev/null
@@ -1,12 +0,0 @@
-from PyQt5.QtWidgets import QApplication
-
-from models import Camera
-from views import StartWindow
-
-camera = Camera(0)
-camera.initialize()
-
-app = QApplication([])
-start_window = StartWindow(camera)
-start_window.show()
-app.exit(app.exec_())
\ No newline at end of file
diff --git a/freemocap/dev_scratchpad/dev_alpha_old/scratch/qt_cv_webcam_tutorial/views.py b/freemocap/dev_scratchpad/dev_alpha_old/scratch/qt_cv_webcam_tutorial/views.py
deleted file mode 100644
index f2a22dd9..00000000
--- a/freemocap/dev_scratchpad/dev_alpha_old/scratch/qt_cv_webcam_tutorial/views.py
+++ /dev/null
@@ -1,37 +0,0 @@
-from PyQt5.QtWidgets import QMainWindow, QWidget, QPushButton, QVBoxLayout, QApplication
-
-from pyqtgraph import ImageView
-
-import numpy as np
-
-class StartWindow(QMainWindow):
- def __init__(self, camera):
- super().__init__()
- self.camera = camera
- self.central_widget = QWidget()
- self.acquire_frame = QPushButton('Acquire Frame', self.central_widget)
- self.start_movie = QPushButton('Start Movie', self.central_widget)
- self.image_view = ImageView()
-
- self.layout = QVBoxLayout(self.central_widget)
- self.layout.addWidget(self.image_view)
- self.layout.addWidget(self.acquire_frame)
- self.layout.addWidget(self.start_movie)
- self.setCentralWidget(self.central_widget)
-
- self.acquire_frame.clicked.connect(self.update_image)
-
- def button_clicked(self):
- print('botton clicnked')
-
- def update_image(self):
- frame = self.camera.get_frame()
- self.image_view.setImage(frame.T)
- print('Maximum in frame: {}, Minimum in frame: {}'.format(np.max(frame), np.min(frame)))
-
-
-if __name__ == '__main__':
- app = QApplication([])
- window = StartWindow()
- window.show()
- app.exit(app.exec_())
\ No newline at end of file
diff --git a/freemocap/dev_scratchpad/dev_alpha_old/tracking_methods/__init__.py b/freemocap/dev_scratchpad/dev_alpha_old/tracking_methods/__init__.py
deleted file mode 100644
index e69de29b..00000000
diff --git a/freemocap/dev_scratchpad/dev_alpha_old/tracking_methods/fmc_mediapipe_alpha.py b/freemocap/dev_scratchpad/dev_alpha_old/tracking_methods/fmc_mediapipe_alpha.py
deleted file mode 100644
index 890620ea..00000000
--- a/freemocap/dev_scratchpad/dev_alpha_old/tracking_methods/fmc_mediapipe_alpha.py
+++ /dev/null
@@ -1,178 +0,0 @@
-from pathlib import Path
-import copy
-
-import numpy as np
-from rich.progress import Progress
-import cv2
-import mediapipe as mp
-
-# from numba import jit
-
-mp_drawing = mp.solutions.drawing_utils
-mp_drawing_styles = mp.solutions.drawing_styles
-mp_holistic = mp.solutions.holistic
-
-
-def run_mediapipe(synched_video_path_list, dummyRun=False):
- """
- Run MediaPipe on synced videos, and save body tracking data to be parsed
- """
- num_vids = len(synched_video_path_list)
-
- with mp_holistic.Holistic(
- static_image_mode = False, #use 'static image mode' to avoid system getting 'stuck' on ghost skeletons?
- model_complexity = 2, #in this house, we turn the Speed/Accuracy dial all the way towards accuracy \o/)
- ) as holistic:
-
- mediapipe_results_from_all_videos_list = [] # Create an empty list that holds each cameras data
- each_video_resolution_height = [] # mediapipe gives results in normalized screen coordinate, so we need this to convert to pixels
- each_video_resolution_width = []
-
- for this_vid_path in ( synched_video_path_list): # Run MediaPipe 'Holistic' (body, hands, face) tracker on each video in the list of synched videos
- mediaPipe_results_from_this_video_list = [] # Create an empty list for mediapipes data
- if not dummyRun:
- cap = cv2.VideoCapture(str(this_vid_path))
-
- frame_num = -1
- num_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
- success, image_raw = cap.read() # load first image from video
-
- with Progress() as progress:
- progressBar = progress.add_task("[magenta]MediaPiping: {}".format(this_vid_path.name),total=num_frames,) # make progressbar
-
- while success:
-
- if frame_num % 5 == 0:
- progress.update( progressBar, advance=5 ) # increment progress bar everyh 5th frame
-
- frame_num += 1
-
- image_height, image_width, _ = image_raw.shape
- image = cv2.cvtColor(image_raw, cv2.COLOR_BGR2RGB), #Convert the BGR image to RGB before processing
- image = image[0] #unpack the tuple into a straight up image
- results = holistic.process( image) # NOTE: THIS IS WHERE THE MAGIC HAPENS
-
- mediaPipe_results_from_this_video_list.append( results ) # Append data to mediapipe data list
-
- # load the next image (will break `while-loop` on the last frame)
- success, image_raw = cap.read() # load next image from video
-
- each_video_resolution_height.append(image_height)
- each_video_resolution_width.append(image_width)
-
- mediapipe_results_from_all_videos_list.append( mediaPipe_results_from_this_video_list) # Append that cameras data for every frame to the camera datalist
-
- ##
- ##
- ## #Parse MediaPipe into FMC Format
- ##
- ##
-
- #standard MediaPipe output
- numBodyPoints = 33
- numFacePoints = 468 #ton of face points because it's a mesh (rather than individually tracked points)
- numHandPoints = 21 #remember, your average person has almost exactly 2 hands
-
- numTrackedPoints = (numBodyPoints + numHandPoints * 2 + numFacePoints ) # Get total points
-
- # Create array of nans the size of number of cams, frame, points, XYC
- mediaPipeData_nCams_nFrames_nImgPts_XYC = np.empty((int(num_vids), int(num_frames), int(numTrackedPoints), 3)) # create empty array
- mediaPipeData_nCams_nFrames_nImgPts_XYC[:] = np.NaN # Fill it with NaNs!
-
- list_of_frames_with_full_data = []
-
- for vid_num in range(num_vids): # Loop through each camera
- this_vid_mediapipe_results_per_frame = mediapipe_results_from_all_videos_list[vid_num]
- for frame_num in range(num_frames): # Loop through each frame
-
- this_frame_mediapipe_results = this_vid_mediapipe_results_per_frame[frame_num]
-
- thisFrame_X_body = np.empty(numBodyPoints)
- thisFrame_X_body[:] = np.nan
- thisFrame_Y_body = thisFrame_X_body.copy()
- thisFrame_C_body = thisFrame_X_body.copy() #'C' is for 'condfidence' (mediapipe calls it 'visibility')
-
- thisFrame_X_face = np.empty(numFacePoints)
- thisFrame_X_face[:] = np.nan
- thisFrame_Y_face = thisFrame_X_face.copy()
- thisFrame_C_face = thisFrame_X_face.copy()
-
- thisFrame_hands = np.empty(numHandPoints)
- thisFrame_hands[:]= np.nan
-
- thisFrame_X_lefthand = thisFrame_hands.copy()
- thisFrame_Y_lefthand = thisFrame_hands.copy()
- thisFrame_C_lefthand = thisFrame_hands.copy()
-
- thisFrame_X_righthand = thisFrame_hands.copy()
- thisFrame_Y_righthand = thisFrame_hands.copy()
- thisFrame_C_righthand = thisFrame_hands.copy()
-
- fullFrame = True #keep track of which frames have 'full' data (all body, all hands, all face data present)
- try:
- # pull out ThisFrame's mediapipe data (`mpData.pose_landmarks.landmark` returns something iterable Β―\_(ツ)_/Β―)
- thisFrame_poseDataLandMarks = this_frame_mediapipe_results.pose_landmarks.landmark # body ('pose') data
- # stuff body data into pre-allocated nan array
- thisFrame_X_body[:numBodyPoints] = [pp.x for pp in thisFrame_poseDataLandMarks] # PoseX data - Normalized screen coords (in range [0, 1]) - need multiply by image resultion for pixels
- thisFrame_Y_body[:numBodyPoints] = [pp.y for pp in thisFrame_poseDataLandMarks] # PoseY data
- thisFrame_C_body[:numBodyPoints] = [pp.visibility for pp in thisFrame_poseDataLandMarks] #'visibility' is MediaPose's 'confidence' measure in range [0,1]
- except:
- fullFrame = False
-
- # Right hand data
- try:
- thisFrame_rHandDataLandMarks = this_frame_mediapipe_results.right_hand_landmarks.landmark # right hand data
- thisFrame_X_righthand[:numHandPoints] = [pp.x for pp in thisFrame_rHandDataLandMarks] # PoseX data - Normalized screen coords (in range [0, 1]) - need multiply by image resultion for pixels
- thisFrame_Y_righthand[:numHandPoints] = [pp.y for pp in thisFrame_rHandDataLandMarks] # PoseY data
- thisFrame_C_righthand[:numHandPoints] = [pp.visibility for pp in thisFrame_rHandDataLandMarks] #'visibility' is MediaPose's 'confidence' measure in range [0,1]
- except:
- fullFrame = False
-
- # Left hand data
- try:
- thisFrame_lHandDataLandMarks = this_frame_mediapipe_results.left_hand_landmarks.landmark # left hand data
- thisFrame_X_lefthand[:numHandPoints ] = [pp.x for pp in thisFrame_lHandDataLandMarks] # PoseX data - Normalized screen coords (in range [0, 1]) - need multiply by image resultion for pixels
- thisFrame_Y_lefthand[:numHandPoints] = [pp.y for pp in thisFrame_lHandDataLandMarks] # PoseY data
- thisFrame_C_lefthand[:numHandPoints] = [pp.visibility for pp in thisFrame_lHandDataLandMarks] #'visibility' is MediaPose's 'confidence' measure in range [0,1]
- except:
- fullFrame = False
-
- # FaceMeshData
- try:
- thisFrame_faceDataLandMarks = this_frame_mediapipe_results.face_landmarks.landmark # face (mesh) data
- thisFrame_X_face[:numFacePoints] = [pp.x for pp in thisFrame_faceDataLandMarks] # PoseX data - Normalized screen coords (in range [0, 1]) - need multiply by image resultion for pixels
- thisFrame_Y_face[:numFacePoints] = [pp.y for pp in thisFrame_faceDataLandMarks] # PoseY data
- # NOTE - There's also Z data in here, but we're gonna ignore it
- thisFrame_C_face[:numFacePoints] = [ pp.visibility for pp in thisFrame_faceDataLandMarks ] #'visibility' is MediaPose's 'confidence' measure in range [0,1]
- except:
- fullFrame = False
-
- if fullFrame:
- list_of_frames_with_full_data.append(frame_num)
-
- thisFrame_X = np.concatenate((thisFrame_X_body,thisFrame_X_righthand,thisFrame_X_lefthand,thisFrame_X_face))
- thisFrame_Y = np.concatenate((thisFrame_Y_body,thisFrame_Y_righthand,thisFrame_Y_lefthand,thisFrame_Y_face))
- thisFrame_C = np.concatenate((thisFrame_C_body,thisFrame_C_righthand,thisFrame_C_lefthand,thisFrame_C_face))
-
- # stuff this frame's data into pre-allocated mediaPipeData_.... array
- mediaPipeData_nCams_nFrames_nImgPts_XYC[vid_num, frame_num, :, 0] = thisFrame_X *each_video_resolution_width[vid_num]# convert from normalized screen coordinates to pixel coordinates
- mediaPipeData_nCams_nFrames_nImgPts_XYC[vid_num, frame_num, :, 1] = thisFrame_Y *each_video_resolution_height[vid_num]
- mediaPipeData_nCams_nFrames_nImgPts_XYC[vid_num, frame_num, :, 2] = thisFrame_C
-
-
- mediaPipeData_nCams_nFrames_nImgPts_XYC[:, :, 34:, 2] = 1 #hand and face data don't get 'visibility'/'confidence' scores, so we'll just set them all to 1
-
- return mediaPipeData_nCams_nFrames_nImgPts_XYC
-
-
-
-
-if __name__ == "__main__":
- synched_vid_folder_path = Path(r"C:\Users\jonma\Dropbox\FreeMoCapProject\FreeMocap_Data\sesh_2021-12-06_08_52_10_mc\SyncedVideos")
- synched_video_path_list = [vid_path for vid_path in synched_vid_folder_path.glob("*.mp4")]
-
- mediaPipeData_nCams_nFrames_nImgPts_XYC = run_mediapipe(synched_video_path_list=synched_video_path_list)
- mediapipe2d_filename = synched_vid_folder_path.parent/'mediapipe_2d_points.npy'
- np.save(mediapipe2d_filename, mediaPipeData_nCams_nFrames_nImgPts_XYC)
-
-
\ No newline at end of file
diff --git a/freemocap/dev_scratchpad/examine_reprojection_error.ipynb b/freemocap/dev_scratchpad/examine_reprojection_error.ipynb
deleted file mode 100644
index ea3be12d..00000000
--- a/freemocap/dev_scratchpad/examine_reprojection_error.ipynb
+++ /dev/null
@@ -1,130 +0,0 @@
-{
- "cells": [
- {
- "cell_type": "code",
- "execution_count": 1,
- "metadata": {},
- "outputs": [],
- "source": [
- "import numpy as np\n",
- "import matplotlib.pyplot as plt\n",
- "import matplotlib\n",
- "from pathlib import Path\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "session_data_arrays_folder = Path(r\"C:\\Users\\jonma\\Dropbox\\FreeMoCapProject\\FreeMocap_Data\\sesh_2022-04-20_07_41_59_paul_tiktok_ayub_0\\DataArrays\")\n",
- "\n",
- "xyz_file = session_data_arrays_folder / \"mediaPipeSkel_3d_smoothed.npy\"\n",
- "reprojection_error_file = session_data_arrays_folder / \"mediaPipeSkel_reprojErr.npy\"\n",
- "\n",
- "mediapipe_fr_mar_dim = np.load(xyz_file)\n",
- "mediapipe_fr_mar_reprojectionError = np.load(reprojection_error_file)"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "f = mediapipe_fr_mar_reprojectionError.flatten()\n",
- "fig = plt.figure()\n",
- "ax1 = fig.add_subplot(211)\n",
- "ax1.hist(f, 1000, density=True)\n",
- "ax1.set_xlim(0,30)\n",
- "\n",
- "ax2 = fig.add_subplot(212)\n",
- "xmin=0\n",
- "xmax = 30\n",
- "threshold_line = .95\n",
- "ax2.hist(f, 1000, cumulative=True, density=True)\n",
- "\n",
- "red_line_xs = [xmin, xmax]\n",
- "red_line_ys= [threshold_line, threshold_line]\n",
- "ax2.plot(red_line_xs, red_line_ys, 'r-')\n",
- "ax2.set_xlim(xmin, xmax)\n",
- "ax2.set_ylim(.8, 1)\n",
- "\n",
- "plt.show()\n"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "lets call the cut off around `12, which will retain a little more than 95% of the data"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 3,
- "metadata": {},
- "outputs": [
- {
- "ename": "TypeError",
- "evalue": "Cannot interpret '3' as a data type",
- "output_type": "error",
- "traceback": [
- "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",
- "\u001b[1;31mTypeError\u001b[0m Traceback (most recent call last)",
- "\u001b[1;32m~\\AppData\\Local\\Temp\\ipykernel_27320\\1137016094.py\u001b[0m in \u001b[0;36m<module>\u001b[1;34m\u001b[0m\n\u001b[1;32m----> 1\u001b[1;33m \u001b[0mf\u001b[0m \u001b[1;33m=\u001b[0m \u001b[0mnp\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mndarray\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;36m9\u001b[0m\u001b[1;33m,\u001b[0m\u001b[1;36m3\u001b[0m\u001b[1;33m,\u001b[0m\u001b[1;36m4\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m\u001b[0;32m 2\u001b[0m \u001b[0mf\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n",
- "\u001b[1;31mTypeError\u001b[0m: Cannot interpret '3' as a data type"
- ]
- }
- ],
- "source": [
- "f = np.ndarray(9,3,4)\n",
- "f"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "g"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": []
- }
- ],
- "metadata": {
- "kernelspec": {
- "display_name": "Python 3.7.13 ('freemocap-env')",
- "language": "python",
- "name": "python3"
- },
- "language_info": {
- "codemirror_mode": {
- "name": "ipython",
- "version": 3
- },
- "file_extension": ".py",
- "mimetype": "text/x-python",
- "name": "python",
- "nbconvert_exporter": "python",
- "pygments_lexer": "ipython3",
- "version": "3.7.13"
- },
- "orig_nbformat": 4,
- "vscode": {
- "interpreter": {
- "hash": "122c9931a57dd91c579842728ee2ee1c7ffefd770186c077f442b22e7e57f48e"
- }
- }
- },
- "nbformat": 4,
- "nbformat_minor": 2
-}
diff --git a/freemocap/dev_scratchpad/fit_skel_to_dots.ipynb b/freemocap/dev_scratchpad/fit_skel_to_dots.ipynb
deleted file mode 100644
index 93f5396a..00000000
--- a/freemocap/dev_scratchpad/fit_skel_to_dots.ipynb
+++ /dev/null
@@ -1,100 +0,0 @@
-{
- "cells": [
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "import numpy as np\n",
- "from scipy import optimize\n",
- "import json\n",
- "from rich import print"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "# load data"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "skel_fr_mar_dim_og = np.load(r\"C:\\Users\\jonma\\Dropbox\\FreeMoCapProject\\FreeMocap_Data\\sesh_2022-01-03_19_14_39\\DataArrays\\mediaPipeSkel_3d_smoothed.npy\")"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "# load mediapipe definitons"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "mediapipe_json = open(r\"C:\\Users\\jonma\\Dropbox\\GitKrakenRepos\\freemocap\\freemocap\\dev_scratchpad\\dev_alpha\\default_json_definitions\\freemocap_mediapipe_json.json\")\n",
- "mediapipe_formatting_dict = json.load(mediapipe_json)\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "#take a look, if you want!\n",
- "#print(mediapipe_definitions_dict)"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "# get skeleton constraints, based on parent-child relationships defined in the jason\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "\n"
- ]
- }
- ],
- "metadata": {
- "interpreter": {
- "hash": "82e606d03bb5ea8b8ecb178c4510354cd9c1f96cd94fcd95b722a3ff15cb0c24"
- },
- "kernelspec": {
- "display_name": "Python 3.7.11 64-bit ('fmc43-pip': conda)",
- "language": "python",
- "name": "python3"
- },
- "language_info": {
- "codemirror_mode": {
- "name": "ipython",
- "version": 3
- },
- "file_extension": ".py",
- "mimetype": "text/x-python",
- "name": "python",
- "nbconvert_exporter": "python",
- "pygments_lexer": "ipython3",
- "version": "3.7.12"
- },
- "orig_nbformat": 4
- },
- "nbformat": 4,
- "nbformat_minor": 2
-}
diff --git a/freemocap/dev_scratchpad/fmc_rich.py b/freemocap/dev_scratchpad/fmc_rich.py
deleted file mode 100644
index 6f55dec3..00000000
--- a/freemocap/dev_scratchpad/fmc_rich.py
+++ /dev/null
@@ -1,66 +0,0 @@
-#%% Working from this youtube vid - https://www.youtube.com/watch?v=JrGFQp9njas
-from rich import print
-from rich import pretty
-pretty.install() #makes all print statement output pretty
-
-from rich import inspect
-
-#%%
-print('[red]hello[/red] :poop:')
-# %%
-locals()
-#%%
-print(locals())
-
-# %%
-inspect('asdf')
-# %%
-
-inspect('asfdf',methods=True)
-
-
-# %%
-from rich.console import Console
-console = Console()
-console.print('[green]hello[/green] :poop:')
-console.log('hello :poop:', style='bold blue')
-console.info('hello :poop:', style='bold green')
-# inspect(console, methods=True)
-
-# %%
-from rich.table import Table
-
-table = Table(show_header=True, header_style="bold magenta")
-table.add_column("Date", style="dim", width=12)
-table.add_column("Title")
-table.add_column("Production Budget", justify="right")
-table.add_column("Box Office", justify="right")
-table.add_row(
- "Dev 20, 2019", "Star Wars: The Rise of Skywalker", "$275,000,000", "$375,126,118"
-)
-table.add_row(
- "May 25, 2018",
- "[red]Solo[/red]: A Star Wars Story",
- "$275,000,000",
- "$393,151,347",
-)
-table.add_row(
- "Dec 15, 2017",
- "Star Wars Ep. VIII: The Last Jedi",
- "$262,000,000",
- "[bold]$1,332,539,889[/bold]",
-)
-
-console.print(table)
-# %%
-from time import sleep
-from rich.progress import track
-
-for step in track(range(10)):
- sleep(0.5)
- step
-# %%
-from rich.traceback import install as rich_traceback_install
-rich_traceback_install()
-1/0
-# %%
diff --git a/freemocap/dev_scratchpad/playAnimWithSlider.py b/freemocap/dev_scratchpad/playAnimWithSlider.py
deleted file mode 100644
index 7a3a34d2..00000000
--- a/freemocap/dev_scratchpad/playAnimWithSlider.py
+++ /dev/null
@@ -1,72 +0,0 @@
-#https://matplotlib.org/stable/api/animation_api.html
-from operator import is_
-import numpy as np
-import matplotlib.pyplot as plt
-from matplotlib.animation import FuncAnimation
-from mpl_toolkits.mplot3d import axes3d
-from matplotlib.widgets import Slider
-
-fig = plt.figure()
-ax3d = fig.add_subplot(211,projection="3d")
-xdata, ydata , zdata = [], [], []
-ln, = plt.plot([], [], [], 'r-o')
-
-axControls = fig.add_subplot(212)
-
-numFrames = 128
-#slider
-animSlider = Slider(
- ax=axControls,
- label="FrameNum",
- valmin=0,
- valmax=100,
- valinit=0,
- orientation="horizontal"
-)
-# Animation controls
-is_manual = False # True if user has taken control of the animation
-interval = 0 # ms, time between animation frames
-loop_len = 0.1 # seconds per loop
-scale = interval / 1000 / loop_len
-
-def init():
- ax3d.set_xlim(0, 2*np.pi)
- ax3d.set_ylim(-1, 1)
- ax3d.set_zlim(-1, 1)
- return ln,
-
-def update_slider(frameNum):
- global is_manual
- is_manual = True
- update_figure(frameNum)
-
-def update_figure(frameNum):
- global is_manual
- if is_manual:
- return ln, #don't change in manual mode
-
- xdata.append(frameNum)
- ydata.append(np.sin(frameNum))
- zdata.append(np.sin(frameNum))
- ln.set_data_3d(xdata, ydata,zdata)
- is_manual = False # the above line called update_slider, so we need to reset this
- return ln,
-
-def on_click(event):
- # Check where the click happened
- (xm,ym),(xM,yM) = animSlider.label.clipbox.get_points()
- if xm < event.x < xM and ym < event.y < yM:
- # Event happened within the slider, ignore since it is handled in update_slider
- return
- else:
- # user clicked somewhere else on canvas = unpause
- global is_manual
- is_manual=False
-
-# call update function on slider value change
-animSlider.on_changed(update_slider)
-fig.canvas.mpl_connect('button_press_event', on_click)
-
-ani = FuncAnimation(fig, update_figure, frames=np.linspace(0, 2*np.pi, numFrames),
- init_func=init, blit=True)
-plt.show()
\ No newline at end of file
diff --git a/freemocap/dev_scratchpad/playSkeletonAnimation.py b/freemocap/dev_scratchpad/playSkeletonAnimation.py
deleted file mode 100644
index 002e71de..00000000
--- a/freemocap/dev_scratchpad/playSkeletonAnimation.py
+++ /dev/null
@@ -1,72 +0,0 @@
-#https://matplotlib.org/stable/api/animation_api.html
-from operator import is_
-import numpy as np
-import matplotlib.pyplot as plt
-from matplotlib.animation import FuncAnimation
-from mpl_toolkits.mplot3d import axes3d
-from matplotlib.widgets import Slider
-
-fig = plt.figure()
-ax3d = fig.add_subplot(211,projection="3d")
-xdata, ydata , zdata = [], [], []
-ln, = plt.plot([], [], [], 'r-o')
-
-axControls = fig.add_subplot(212)
-
-numFrames = 128
-#slider
-animSlider = Slider(
- ax=axControls,
- label="FrameNum",
- valmin=0,
- valmax=100,
- valinit=0,
- orientation="horizontal"
-)
-# Animation controls
-is_manual = False # True if user has taken control of the animation
-interval = 0 # ms, time between animation frames
-loop_len = 0.1 # seconds per loop
-scale = interval / 1000 / loop_len
-
-def init():
- ax3d.set_xlim(0, 2*np.pi)
- ax3d.set_ylim(-1, 1)
- ax3d.set_zlim(-1, 1)
- return ln,
-
-def update_slider(frameNum):
- global is_manual
- is_manual = True
- update_figure(frameNum)
-
-def update_figure(frameNum):
- global is_manual
- if is_manual:
- return ln, #don't change in manual mode
-
- xdata.append(frameNum)
- ydata.append(np.sin(frameNum))
- zdata.append(np.sin(frameNum))
- ln.set_data_3d(xdata, ydata,zdata)
- is_manual = False # the above line called update_slider, so we need to reset this
- return ln,
-
-def on_click(event):
- # Check where the click happened
- (xm,ym),(xM,yM) = animSlider.label.clipbox.get_points()
- if xm < event.x < xM and ym < event.y < yM:
- # Event happened within the slider, ignore since it is handled in update_slider
- return
- else:
- # user clicked somewhere else on canvas = unpause
- global is_manual
- is_manual=False
-
-# call update function on slider value change
-animSlider.on_changed(update_slider)
-fig.canvas.mpl_connect('button_press_event', on_click)
-
-ani = FuncAnimation(fig, update_figure, frames=np.linspace(0, 2*np.pi, numFrames),
- init_func=init, blit=True)
-plt.show()
\ No newline at end of file
diff --git a/freemocap/dev_scratchpad/simple_camera.py b/freemocap/dev_scratchpad/simple_camera.py
deleted file mode 100644
index db2127b5..00000000
--- a/freemocap/dev_scratchpad/simple_camera.py
+++ /dev/null
@@ -1,22 +0,0 @@
-import cv2
-
-cap = cv2.VideoCapture(0, cv2.CAP_DSHOW)
-# cap = cv2.VideoCapture(2, cv2.CAP_ANY)
-
-cap.set(cv2.CAP_PROP_EXPOSURE, -7)
-
-cap.set(cv2.CAP_PROP_FRAME_WIDTH, 1920)
-cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 10800)
-
-cap.set(cv2.CAP_PROP_FOURCC, cv2.VideoWriter_fourcc('M', 'J', 'P', 'G'))
-
-while True:
- success, image = cap.read()
- cv2.imshow('blah', image)
- exit_key = cv2.waitKey(1)
- if exit_key ==27:
- break
-
-cap.release()
-cv2.destroyAllWindows()
-
diff --git a/freemocap/dev_scratchpad/time_sync_v2.ipynb b/freemocap/dev_scratchpad/time_sync_v2.ipynb
deleted file mode 100644
index 031196cb..00000000
--- a/freemocap/dev_scratchpad/time_sync_v2.ipynb
+++ /dev/null
@@ -1,266 +0,0 @@
-{
- "cells": [
- {
- "cell_type": "code",
- "execution_count": 1,
- "metadata": {},
- "outputs": [],
- "source": [
- "import numpy as np\n",
- "import pandas as pd\n",
- "import matplotlib.pyplot as plt\n",
- "from pathlib import Path"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 2,
- "metadata": {},
- "outputs": [
- {
- "data": {
- "text/html": [
- "<div>\n",
- "<style scoped>\n",
- " .dataframe tbody tr th:only-of-type {\n",
- " vertical-align: middle;\n",
- " }\n",
- "\n",
- " .dataframe tbody tr th {\n",
- " vertical-align: top;\n",
- " }\n",
- "\n",
- " .dataframe thead th {\n",
- " text-align: right;\n",
- " }\n",
- "</style>\n",
- "<table border=\"1\" class=\"dataframe\">\n",
- " <thead>\n",
- " <tr style=\"text-align: right;\">\n",
- " <th></th>\n",
- " <th>Unnamed: 0</th>\n",
- " <th>Cam1</th>\n",
- " <th>Cam2</th>\n",
- " <th>Cam3</th>\n",
- " <th>Cam4</th>\n",
- " <th>Cam5</th>\n",
- " </tr>\n",
- " </thead>\n",
- " <tbody>\n",
- " <tr>\n",
- " <th>0</th>\n",
- " <td>0</td>\n",
- " <td>1.750172</td>\n",
- " <td>2.068959</td>\n",
- " <td>1.934951</td>\n",
- " <td>1.801427</td>\n",
- " <td>2.112885</td>\n",
- " </tr>\n",
- " <tr>\n",
- " <th>1</th>\n",
- " <td>1</td>\n",
- " <td>1.781451</td>\n",
- " <td>2.110887</td>\n",
- " <td>1.985400</td>\n",
- " <td>1.849017</td>\n",
- " <td>2.163501</td>\n",
- " </tr>\n",
- " <tr>\n",
- " <th>2</th>\n",
- " <td>2</td>\n",
- " <td>1.812396</td>\n",
- " <td>2.144079</td>\n",
- " <td>2.016474</td>\n",
- " <td>1.880987</td>\n",
- " <td>2.192944</td>\n",
- " </tr>\n",
- " <tr>\n",
- " <th>3</th>\n",
- " <td>3</td>\n",
- " <td>1.861013</td>\n",
- " <td>2.190948</td>\n",
- " <td>2.063975</td>\n",
- " <td>1.934951</td>\n",
- " <td>2.244276</td>\n",
- " </tr>\n",
- " <tr>\n",
- " <th>4</th>\n",
- " <td>4</td>\n",
- " <td>1.893983</td>\n",
- " <td>2.225858</td>\n",
- " <td>2.088962</td>\n",
- " <td>1.968411</td>\n",
- " <td>2.272026</td>\n",
- " </tr>\n",
- " <tr>\n",
- " <th>...</th>\n",
- " <td>...</td>\n",
- " <td>...</td>\n",
- " <td>...</td>\n",
- " <td>...</td>\n",
- " <td>...</td>\n",
- " <td>...</td>\n",
- " </tr>\n",
- " <tr>\n",
- " <th>461</th>\n",
- " <td>461</td>\n",
- " <td>20.178664</td>\n",
- " <td>NaN</td>\n",
- " <td>NaN</td>\n",
- " <td>20.328335</td>\n",
- " <td>NaN</td>\n",
- " </tr>\n",
- " <tr>\n",
- " <th>462</th>\n",
- " <td>462</td>\n",
- " <td>20.212092</td>\n",
- " <td>NaN</td>\n",
- " <td>NaN</td>\n",
- " <td>NaN</td>\n",
- " <td>NaN</td>\n",
- " </tr>\n",
- " <tr>\n",
- " <th>463</th>\n",
- " <td>463</td>\n",
- " <td>20.259496</td>\n",
- " <td>NaN</td>\n",
- " <td>NaN</td>\n",
- " <td>NaN</td>\n",
- " <td>NaN</td>\n",
- " </tr>\n",
- " <tr>\n",
- " <th>464</th>\n",
- " <td>464</td>\n",
- " <td>20.292942</td>\n",
- " <td>NaN</td>\n",
- " <td>NaN</td>\n",
- " <td>NaN</td>\n",
- " <td>NaN</td>\n",
- " </tr>\n",
- " <tr>\n",
- " <th>465</th>\n",
- " <td>465</td>\n",
- " <td>20.340535</td>\n",
- " <td>NaN</td>\n",
- " <td>NaN</td>\n",
- " <td>NaN</td>\n",
- " <td>NaN</td>\n",
- " </tr>\n",
- " </tbody>\n",
- "</table>\n",
- "<p>466 rows Γ— 6 columns</p>\n",
- "</div>"
- ],
- "text/plain": [
- " Unnamed: 0 Cam1 Cam2 Cam3 Cam4 Cam5\n",
- "0 0 1.750172 2.068959 1.934951 1.801427 2.112885\n",
- "1 1 1.781451 2.110887 1.985400 1.849017 2.163501\n",
- "2 2 1.812396 2.144079 2.016474 1.880987 2.192944\n",
- "3 3 1.861013 2.190948 2.063975 1.934951 2.244276\n",
- "4 4 1.893983 2.225858 2.088962 1.968411 2.272026\n",
- ".. ... ... ... ... ... ...\n",
- "461 461 20.178664 NaN NaN 20.328335 NaN\n",
- "462 462 20.212092 NaN NaN NaN NaN\n",
- "463 463 20.259496 NaN NaN NaN NaN\n",
- "464 464 20.292942 NaN NaN NaN NaN\n",
- "465 465 20.340535 NaN NaN NaN NaN\n",
- "\n",
- "[466 rows x 6 columns]"
- ]
- },
- "execution_count": 2,
- "metadata": {},
- "output_type": "execute_result"
- }
- ],
- "source": [
- "timestamp_csv_path = Path(r\"C:\\Users\\jonma\\Dropbox\\FreeMoCapProject\\FreeMocap_Data\\sesh_2021-11-21_19_42_07\\RawVideos\\sesh_2021-11-21_19_42_07_timestamps.csv\")\n",
- "\n",
- "time_stamp_dataframe = pd.read_csv(timestamp_csv_path)\n",
- "\n",
- "time_stamp_dataframe"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 5,
- "metadata": {},
- "outputs": [],
- "source": [
- "cam1 = time_stamp_dataframe[\"Cam1\"].to_numpy()\n",
- "cam2 = time_stamp_dataframe[\"Cam2\"].to_numpy()\n",
- "cam3 = time_stamp_dataframe[\"Cam3\"].to_numpy()\n",
- "cam4 = time_stamp_dataframe[\"Cam4\"].to_numpy()\n",
- "cam5 = time_stamp_dataframe[\"Cam5\"].to_numpy()"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 6,
- "metadata": {},
- "outputs": [
- {
- "data": {
- "text/plain": [
- "[<matplotlib.lines.Line2D at 0x2ed92858548>]"
- ]
- },
- "execution_count": 6,
- "metadata": {},
- "output_type": "execute_result"
- },
- {
- "data": {
- "image/png": "iVBORw0KGgoAAAANSUhEUgAAAXoAAAD4CAYAAADiry33AAAABHNCSVQICAgIfAhkiAAAAAlwSFlzAAALEgAACxIB0t1+/AAAADh0RVh0U29mdHdhcmUAbWF0cGxvdGxpYiB2ZXJzaW9uMy4xLjMsIGh0dHA6Ly9tYXRwbG90bGliLm9yZy+AADFEAAAgAElEQVR4nO3dd3xVVb738c9KD+m9hwRCCxBaABGRjvTeLMjY0HnG63XGuTM6M+qMM95xmqMz6igiAkqx0aVDQugp9BACoaf33s9Zzx85c5883KCYwklOfu/XK6+z99r7nP07S/my2Nl7baW1RgghhOWyMncBQggh2pYEvRBCWDgJeiGEsHAS9EIIYeEk6IUQwsLZmLuApnh7e+uwsDBzlyGEEB1GUlJSvtbap6lt7TLow8LCSExMNHcZQgjRYSilbtxpm5y6EUIICydBL4QQFk6CXgghLJwEvRBCWDgJeiGEsHAS9EIIYeEk6IUQwsJJ0AshxD2UdaUEY+IauLSHK0VXuLRpDdpo5Fp+BZtPZbTJMdvlDVNCCGFpqivqSNh8gbOHCrjPdQdHumbhviuPoZc1268ZeKUkEAdbayZG+uFk37rR/L0jeqVUiFIqRimVopRKVkr9p6ndUym1Vyl12fTqcYf3T1ZKpSql0pRSL7dq9UII0QHcTM7nq98d4NyhPPxd9vNt3RVGfJzLwBtW7Bw1kxdyvBkU6s7mn9zf6iEPdzeirwde0lqfVEq5AElKqb3Aj4D9Wuu3TAH+MvDLxm9USlkD7wMTgXQgQSm1VWt9oTW/hBBCtEfVFXUc+uwUl06X42KdR0XIZmz2J7MgE7IiuvFS90UUe/jx31P7sHhoCEqpNqnje4Nea50FZJmWy5RSKUAQMAsYY9ptNRDLbUEPDAPStNZXAZRSG0zvk6AXQlgsrTXXTuUS+9kZaqrA2203V8vimLauHKODPRsenM1qj2imDwjk5Sm9Cfbo0qb1/KB/IyilwoBBwAnAz/SXAFrrLKWUbxNvCQJuNVpPB4bf4bOXAcsAQkNDf0hZQgjRblSU1BC7MpHrqTW4294kK2g74XtSmZ0HN/r149Xg2dR5+vDh3Cge6uvXZqP4xu466JVSzsA3wIta69K7LK6pnZp8GrnWejmwHCA6OlqeWC6E6FC01qQeTSdu/UUM9RpPry3cyD3G7HVV1Dnas3LS43zl2JMF0SH8elof3LvY3bPa7irolVK2NIT8Wq31RlNzjlIqwDSaDwBym3hrOhDSaD0YyGxJwUII0d4UZVdw+PNT3EyrxdM2jbTArYTvvc7APEgbEM0rwbNw8/Fkxcy+TIj0u+f1fW/Qq4ah+ydAitb67UabtgJLgbdMr1uaeHsC0EMpFQ5kAIuBR1patBBCtAfaqDl74DonNl9GGWpw891BzrXDzNlXT427C++Of4Tdrj1Ycl9Xfjm5d5tcUXM37uaoI4ElwDml1GlT269oCPgvlVJPATeBBQBKqUBghdZ6qta6Xin1PLAbsAZWaq2TW/tLCCHEvVaUXcH+jxPJyTDgZZ9Mqte3jN2ZwZBSODnoft4MnEpgkDfrZvVjRHcvs9aqtG5/p8Ojo6O1PGFKCNEeGQxGTm5LJXF3BnaUoX23YUg+wYPnjZQGePF+30Ucd4vgP8ZF8OQD4fdsFK+UStJaRze1Te6MFUKIu5R3q4x9H8ZTWKDw63KMs44HmbY1A5dqOHb/ZP7i8QAhwd5sXjSIyEBXc5f7PyTohRDie9RW15O07SIn9+fgoEqxCvyGotOnePiCkeIAb37RfylpbkH8x7gePDOqG3Y27WsaMQl6IYT4DumpRcStSqSoyBpv50Ok6r1M2lyIc60VB0ZM5m2fsdzX05c9c6II9WrbG5+aS4JeCCGaUFtdz9EN50k+XoCzdQG1IZvQh86x4Lomr1soL/VYTJZHIK9O7MnjI8Kwsmr7G5+aS4JeCCFuc/1sHrGrT1NZofBz2UtqTSxTN5RiZW3Dtgdn8S+P4Yzq5cfyWX3p6uVk7nK/lwS9EEKYVFfUEbc6ictnK/GwuUVB8E6sY5OZm67JiOzN74LnUOzhx59mRDJ/cHC7HsU3JkEvhOj0tNakJWRzcO05amus8PDYzo3io0xfV4bRzoYN4xayxmUgk/oF8IfZ/fFxsTd3yT+IBL0QolMrLaji8OenuZZShZtNOoX+m+kae5nZ2XC9TySvdF2Ava83H8zoy5T+AeYut1kk6IUQnVLDJGQZHN5wgfo6I+7eW8nKOMyUA3XUuXThowmPstm5F0vu68qvpvbB0c7a3CU3mwS9EKLTKcyqIPbTRLJuGvCwu8KVoK302HGdwUVwcdAwfhM0Ax8/Lz6d2ZexvZqagb1jkaAXQnQa2qg5u/cKR7dcx1ZX4OS3hcIrSczdU0ultyt/GvcIsa4RPP1AOC9M6IGrg625S24VEvRCiE6hMLOCfR+dIC8HfB2SSHbdxfid2XiXwunho3nTazw+gT5sXDiAwaFNPgK7w5KgF0JYtPo6A6d3XiZ+Zzp2VGDvv4mCC4ks2mWg1MedNyYtJdEllOdGd+cnYyNwsO245+LvRIJeCGGxMtOKObQ6kfw8K3y7nOCcwx4mfZuLe4Xi6P2TeMtrHL1Dvfh24QB6+rmYu9w2I0EvhLA4tVX1xG+6wNm4XBytiiBoK1XxSTx8WVMU5Muv7n+cy65BvDgugudGd8e6g9z41FwS9EIIi5J5qZB9HydRXqbwdY4lWR1g6jdF2But2XP/FN71HsWwCB+2ze5HhK/ljuIbk6AXQliE2up6Dn9+mpTEUpyt86gM/Qodm8rCm5rc7mH8ottCst0DeHNGJIuiQzrM9AWt4W6eGbsSmA7kaq37mdq+AHqZdnEHirXWA5t473WgDDAA9Xd6+okQQjSX1pob5/I58Olpqqqs8XX7lpSqo8xeW4yysmbL2PksdxnMqN7+rJ3bn0B3R3OXfM/dzYh+FfAesObfDVrrRf9eVkr9DSj5jveP1VrnN7dAIYS4k4riGo6sO8nls1W42GRTFbAJm0MpLEiH7F49+VW3hVR5+PDX6ZHMGRSEUp1nFN/Y9wa91jpOKRXW1DbV0GsLgXGtW5YQQtyZ1prUY5kc/TKZmmrw8txBakkcs7+sQjvYs2bsQta7RjGxrz9/nT8Aty6WceNTc7X0HP0oIEdrffkO2zWwRymlgY+01stbeDwhRCdXUVLDgRWJ3Lxcg4ftNbKDt9J911UW5sONXn35RbeFuPh58/HMvkyM9DN3ue1CS4P+YWD9d2wfqbXOVEr5AnuVUhe11nFN7aiUWgYsAwgNDW1hWUIIS6O1Jjn2Osc2XsZYZ8DNZyNZGfHMWFdLjZsT7098lG+de/Kj+8P4+aReONnLtSb/1uyeUErZAHOBIXfaR2udaXrNVUptAoYBTQa9abS/HCA6Olo3ty4hhOUpyasiZkU8GTcMeNsnc9V/Hz13XWVIMaQOHs6r/lNx8/Nm/YIB3NfNy9zltjst+StvAnBRa53e1EallBNgpbUuMy1PAt5owfGEEJ2MwWDk7N6rHN9yHStqcPTdRN7lE8zeXU+FuzNvPfQkcV1CeXJkOD+f1KtDTyXclu7m8sr1wBjAWymVDryutf4EWMxtp22UUoHACq31VMAP2GT6LbcNsE5rvat1yxdCWKr89HIOrownOxP8HJI477qXMXsy8C2BkyPG84bXOLoGebFlwQCigt3NXW67prRuf2dJoqOjdWJiornLEEKYgaHOSMKWFE4dyMRWV0LAZurPxjP6vJFSXw/+PmgpJ51DeebBcF6c0BNbaytzl9wuKKWS7nSvkvy2QgjRbuRcKyFmZSIFeQqfLse54LCPSVtyca1WHBkxkbd8xhMV5s3m2f2JDHQ1d7kdhgS9EMLsDHVGjn11lrOH8umiCtBB26iNP8miy5rC0EBe7rmYS+7B/HJSL54YGYaNjOJ/EAl6IYRZZaQWsu/jRMrLbfBzjuE8B5n1ZQG22op9D87iXff7GNLdl11z+9PNx9nc5XZIEvRCCLOoKq/lxFdnST5RirN1PoaAzdQfO8+i65q88K681vMR8tx8+d20Pjw8NLRTTULW2iTohRD33JWTucR9dprKKiu83fZwqTyG6V+XY21lw8bRc1jhPpSxffz5al4UPi725i63w5OgF0LcM5WltRz67CRp5ypxs8mgMmQLDvtTmZ8J6b378OtuC8HLm3enRzJzQKC5y7UYEvRCiHvi0vEMDm9IprbaiLfnTm7mH+KhdVXUOzny6Zj5fOk+gPlDgnllSm+8nGUU35ok6IUQbaqipIb9H8Vz62odXnZXSA/eQcSONKIK4erAwfwmYAZ2Pt6smN2fCTIJWZuQoBdCtAmjUZMcc50j36SBsR5n7y1kZRxn3p4aaly78P6Ex9ju1IOHh4fy8uQ+nX4q4bYkQS+EaHUFGeXErYon8xZ425/nquteeuy/xrBCOD94OL/zn4ZXgDdfzItiuExC1uYk6IUQrcZQb+TM3qvEb7uGta7G0X8LeanHmL3bSLmXK7+fsIREt+48PqIrv5jcGzsbufHpXpCgF0K0itwbpexbnkBRgcLb8RQXHXcweUsOzjUQP3Qsf/B/iF6hnny7cCA9/FzMXW6nIkEvhGgRg8FI/DcXOB2TjaMqxDp4ExVJZ1mYYqSwayD/1ftR0pwD+NnEnjz1QLiM4s1Agl4I0WzZV0vY+2ECpaVW+HeJ45xtLDO/zMO+XhE7chpve46iX7g3386LklG8GUnQCyF+sOqKOuI3pXDucD5OVgUYgrdSefwUi9I0BV2D+FXvR7nm4s9r0yN5eGiITEJmZhL0Qogf5Mb5fA6uOklZuQ1+Lnu4WHuQh74uxqHeil2j5/BPt+EMj/BlxYIogj26mLtcgQS9EOIuVZfXceyLM1xIaJiETId8g/FQCvOua7K7h/OLXo9Q6ObLm1N6s3hoCKany4l2QIJeCPG90hKyOLz+HFWV4OG+nxsle5m8oQplY8uXo2bzqecwHurnz+sz+hLo7mjucsVt7uaZsSuB6UCu1rqfqe23wDNAnmm3X2mtdzTx3snAu4A1Dc+SfauV6hZC3APV5XXEfprEleRKPG2vkxO6m5A9F5idDTf79+e1wJkYfPz5YFZfpvTzl1F8O3U3I/pVwHvAmtva/661/uud3qSUsgbeByYC6UCCUmqr1vpCM2sVQtwj2qi5dDyduPUp1NeBi+c2bhUcZdpnldR3sefTcY/wpUskc4cE85tpkXg62Zm7ZPEdvjfotdZxSqmwZnz2MCBNa30VQCm1AZgFSNAL0Y4VZVdw6LOT3LpSh6ftFa757iA8Jo2heZA2YCCvBczE3teX1fOjGN3Tx9zlirvQknP0zyulHgcSgZe01kW3bQ8CbjVaTweG3+nDlFLLgGUAoaGhLShLCNEcRqPm/IFrHNt0BW0w4Oazkbzr8czZW0OVuzP/nPgYO50jWDw0lNemR+JoZ23uksVdam7Q/wv4PaBNr38Dnrxtn6ZO1uk7faDWejmwHCA6OvqO+wkhWl9BZjlxq5LIvGnA0z6Zy17b6Lk3k0HFcH7I/fwmaAbBfu6sn9Of+2QSsg6nWUGvtc7597JS6mNgexO7pQMhjdaDgczmHE8I0Ta0UZOw5SKn9qZjo8ux999OUcoJ5u02UO7vxVvjFnHUrTtPjwrnxfE9ZRTfQTUr6JVSAVrrLNPqHOB8E7slAD2UUuFABrAYeKRZVQohWl1BRjl7PzxBQZ7Cz/E4Z5ximLotC7dKSBg+nv/2GUf3EB82zetPVLC7ucsVLXA3l1euB8YA3kqpdOB1YIxSaiANp2KuA8+a9g2k4TLKqVrreqXU88BuGi6vXKm1Tm6TbyGEuGt1tQYSNyVzKiYXB6tS7P03U3ImiUdSjJQE+PLq/Y9yxiWYlyb1kknILMTdXHXzcBPNn9xh30xgaqP1HcD/ur5eCGEety4WErcqieJia/xdDnFGxTBzUx6OdYrYB6bxtscoIsO82bNwAN18nM1drmglcmesEJ1ATVU9h9ee5WJiMV2siqkN+ZrS+HM8nKrJDQvhlcglZLv48utJPVl6f5jc+GRhJOiFsHDpKQXs/ySJinJFkPs2UiqOMXlDOTZY8+19U/jAdxRjIgNYObMvIZ4yCZklkqAXwkLVVNVzaM1JUk+V42KdQ1XXzRgPpDD7liY9sje/DZ1Hpacvf54WybzBQTKKt2AS9EJYGK01107lErvmDNXVCi/3HVwtP8r0z0vRdrZ8OXouq9yHMDUqiFenR+Lv5mDukkUbk6AXwoKUFlRx5POTXE2pwcPmJrmB2wk9kMqcbLjRpw+vdp1HvacP/5obxUN9/WQU30lI0AthAbTWnI+9xdGvUzEaNG7e28jIPMyM9dXUdbHnkwmP8rVTHx4eHsorU/vg6mBr7pLFPSRBL0QHV5hVQdyqRDJuGPB2OMclr51E7E9nSAGcHxjN74Jm4eXvxacz+jK2t6+5yxVmIEEvRAelteb07ivEb7uKtbEKx4Ad5KccYe4uAxV+HvxtzDxiPfvw9KhuvDA+gi528se9s5L/8kJ0QMU5lexffoLsDI2vw2kueOxjzI5b+JbA6RHj+a3XOMKCvNm4IEqmLxAS9EJ0JPV1Bs7sTiP+21vYUoGd3xbyL8azcJeBMh933hz/KEdcw/nJmAh+MjZCJiETgAS9EB1G7o1S9n0UT1GhFd6O8aTY72PS9izcK+HEiAn80Wss4cHefLtwIJGBruYuV7QjEvRCtHN1NQYSt6Zwan829lZl2AZ/TXnSaRalGCkK9OFXo5Zy0SWQF8b14LnR3bG2kksmxf9Pgl6Idiw9pZCDqxsmIfNxOkyq3s3EjcU41Vmxf8Q03vYdzbDu3myf3Z8IX5mETDRNgl6IdqiuxsDhdWdIOVGIi3UOxtDtqINnmX9DkxsRzmvd5pPlGcTvJvfm0WGhWMkoXnwHCXoh2pkb5/KI+fQUFZVWeLnuJa0ujmnri7FW1mwZPZeP3Icyurcfn8zqJ5OQibsiQS9EO1FRUsPR9ae5dLoCN5tMagK24xCXzLwMyIjoxuvhCyn18uftWX2ZNSBIRvHirknQC2FmWmvSErI5+Pk5amqt8PLYzo38Q0zfUEm9vS1rxz3MWpd+zI8O5TfTInHrItMXiB9Ggl4IMyrNr+Lw5ye5drEGD9sbZIdtJWR3GjOzIG3wUH4TOBMnLw8+nNmXh/r6m7tc0UHdzTNjVwLTgVytdT9T21+AGUAtcAV4Qmtd3MR7rwNlgAGo11pHt17pQnRcWmuSY29wfNMlDHV1uPjsJvtmLDMP1GF0cOCjMYvZ7N6PRdEh/GpaH9wcZRQvmu9uRvSrgPeANY3a9gKvmB4A/ifgFeCXd3j/WK11fouqFMKClBZUcWB5PBk3DHjZX+SK7y5G7LnG0CJIGXwfb/g+hFuQH5/P7s8DPbzNXa6wAHfzcPA4pVTYbW17Gq0eB+a3bllCWB6Dwcj5fVc4vvU6VsZq7H23kn3jBLN311Hu685fxi7kgFtPnn2wG8+Pi8BFphIWraQ1ztE/CXxxh20a2KOU0sBHWuvld/oQpdQyYBlAaGhoK5QlRPtRmFnB3g+Pk5+r8HU4Q7LLXsbtuolPKZyLfoBX/acQHuzN1vkyCZlofS0KeqXUr4F6YO0ddhmptc5USvkCe5VSF7XWcU3taPpLYDlAdHS0bkldQrQX9XUGTu9MI2HnLWyowj7wa/KSk1hkmoTsjYd+RKJzCM+M6sZ/TuiBvY1MQiZaX7ODXim1lIZf0o7XWjcZzFrrTNNrrlJqEzAMaDLohbA02VdLOPhpAvl5Vvh0iSfZbheTtubhVqk4Nnwcf/SdRJ+uXmydF0WfAJmETLSdZgW9UmoyDb98Ha21rrzDPk6Alda6zLQ8CXij2ZUK0UHU1xk48fUFzsbl4KCKUMFbqYpPYvElTWFoIC/f/zBX3IL5+YQePD2qm0xCJtrc3VxeuR4YA3grpdKB12m4ysaehtMxAMe11s8ppQKBFVrrqYAfsMm03QZYp7Xe1SbfQoh2IvNyEQdWJFJSYo2300EuWccw5asC7A1W7L1/Ou94P8DwCF+2ze4nk5CJe+Zurrp5uInmT+6wbyYw1bR8FRjQouqE6CBqKus4+sU5LpwoxsU6j+qgLdgcOsf8m5rcbl35ZfdFZLoH8N8zIlkQHSKjeHFPyZ2xQrSA1prrZ/KJWXWKqmobPN13klp9mJlfFWNtZcs3Y+ex0mUQo/v4s3ZuFP5uDuYuWXRCEvRCNFNFSQ1H1p7i8tlK3GyyKArehNP+VBZlQWZEN16LeIQabz/emRHJjKgATKcxhbjnJOiF+IG01lw6nsmRL85TW63x9trJ9bw4HtpQjdHRgTXjFrHepR+zBwXx+oy+eDjZmbtk0clJ0AvxA5QX1RCzIp6bV+pwt71Blt82uu9LI6oArvSL4tWQOTj6+vDhjL5M7ieTkIn2QYJeiLugjZrk2Osc3ZiGNtTi7L2dzOxjzP6yhkovV94fu4Dtbn14YmQYL4zrIaN40a5I0AvxPYpzKtm3PJ6cDCPe9ue55LmHMbuuM6wUzkdF81rIbLx8Pfhy4UCGhXuau1wh/hcJeiHuwGAwcnb3ZY5vu4UVNTj4byTvYjzzd9dT4enKHx96gqNOofzn+B4sG91Npi8Q7ZYEvRBNyLleyqHVieRkgY/jSS447WLsziy8yxSJ943jDZ9J9Aj25Ju5/RkQIpOQifZNgl6IRgz1RhK3pHByXyb2qhTbwK2UnElkUbKREn9vfjvsUU67hvLTiT159sHucuOT6BAk6IUwyb5SzIEVCRQVWePldJxLtvuYtDkX52rF4RGT+ZPPGAZ392XrzL4yCZnoUCToRadXX2vg2BdnOHukCGfrfAxB36KPnWTBVU1+WDC/iFjIVY9gfj25N0tHhGElo3jRwUjQi07t+tk8Dn12ktIyW3xd9pJqPNwwCZnRih1j5vGB61CGRfhyYOEAAt0dzV2uEM0iQS86paryWo5tOENKYhluNtlUBe7AePQc865rcsJC+Fmfxyly8+HNqX1YNDREpi8QHZoEveh0Lidkc3TDWSorwNt9DzeKY5jwdSXW1nZ89eAcVnpEM6mvP2/O6Y+Pi725yxWixSToRadRWVrLwU8TuJpSg7vtLQqDtxK69xIzcuBm37681nUeytuXf0zrw8wBgeYuV4hWI0EvLJ7WmgsHb3B80yXqaw14eO3iVu5BZq6roc65CyvHLOAr9/7MHRzEK1P6yCheWBwJemHRSguqOLjyBDevGPG2S+VawD7C91xiUD6kDYzmNf+p2Pr48Om8KMb29jV3uUK0ibt5lOBKGh4Cnqu17mdq8wS+AMKA68BCrXVRE++dDLwLWNPwiMG3Wq1yIb6D0WDkQtxNDn91GYz1dPHZQsbNo8zaU0eViyPvTXiMHc49eey+MF6e0hsnexnzCMt1N/93rwLeA9Y0ansZ2K+1fksp9bJp/ZeN36SUsgbeByYC6UCCUmqr1vpCaxQuxJ3kp5dzeE0iGTeNeNmnkOa2jRH70rmvEJKH3M+r/lMJCPDi6wUDGNLVw9zlCtHm7uaZsXFKqbDbmmfR8MBwgNVALLcFPTAMSDM9Oxal1AbT+yToRZswGoyc3JFGwo6b2FCJQ8BWCi4cY95uI2U+7rw5YQnHXcN48oFwXprUUyYhE51Gc/+96qe1zgLQWmcppZo6uRkE3Gq0ng4Mv9MHKqWWAcsAQkNDm1mW6KwKsyo4sPw4OVkKny7HSXHaz7hvs/EsgxPDx/Om7wT6dPVm4+x+RAXLJGSic2nLE5NN3WGi77Sz1no5sBwgOjr6jvsJ0Vh9nYGETcmcjsnFlgpUwCbKTiewMMVIUZAvr0cv4qxHOD+b2JMnHwiTUbzolJob9DlKqQDTaD4AyG1in3QgpNF6MJDZzOMJ8b9kpRWz/+MESkqs8XGKI1XFMWVjDo51itgHZvC2x/1Ehvmwe9FAwr2dzF2uEGbT3KDfCiwF3jK9bmlinwSgh1IqHMgAFgOPNPN4QvyPuhoDx786y9nDRThalVAb9BXWcWeZfwsKQgN5uc9jZLgG8NrU3jw6vKtMQiY6vbu5vHI9Db949VZKpQOv0xDwXyqlngJuAgtM+wbScBnlVK11vVLqeWA3DZdXrtRaJ7fN1xCdxdVTuRz6/DTlFTZ4uu3jUuU+pn9dho2y4csJi1nlFMWDvfz4bF5/AtxkEjIh4O6uunn4DpvGN7FvJjC10foOYEezqxPCpKayjrg1p7h0uhwPm3RqQnZhH3OOhemQ0asnv+22gGovP/48uTfzhwTLJGRCNCJ3iYh2Ly0hi7i156iuVnh4bONm0WGmrK9C29uxftRc1ngOYcbAIH49tQ/+bg7mLleIdkeCXrRbFSU1xKxI4MblWjxsr5ERtJOI3akMyocb/aN4LWA6Bh9/Pprbn0mRfjKKF+IOJOhFu6ONmotH04lbfxGjQePmvZkb2UeZu7aGOicHlo9/lE3OvZkfHcKr0yJx62Jr7pKFaNck6EW7UpxTSdzqRG5drcfL7jIXAr+l266rDMmDywOH8uugGXj6e7NqZl/G9JJJyIS4GxL0ol0wGjXn9l/jxJY0MNTh6reN7KtHWLCvnjrnLvx9wuPsc4ng8RFh/HJybxzt5MYnIe6WBL0wu4KMcmI+SSAnU+Nlf4E09+2M3J3BkBI4O2gEf/CfQnCoHxtm9WNYuKe5yxWiw5GgF2ZjNBg5s+sSx7+9hT1l2AVsozAlgXm7DZQEevOHwQs57taN/xjXg+dGd5dRvBDNJEEvzCLvZhn7PjpBYYEVXo5JXHDazdQt2bhWwYkRE3nTezwRwZ5sWxBF30A3c5crRIcmQS/uqdrqepK2pHAyJg8HqzKs/L+h/MxJHk7RFAf48MuRj3PZPYgXx/Xg6VHhMgmZEK1Agl7cM+mpRcSuTKCkxAZf51jOsY9ZG4uwN1oRc/9U/ub9IEMjfNg7fwAhnl3MXa4QFkOCXrS5mqp6jm44y4UTxThZF1Ibupn6Q2d5+JomJyKcn/Z8jBI3b16f1JPHZBIyIVqdBL1oU9fP5HJwzWkqKhQebvtIqzjAtA3l2FjZsHHkLDeZBBkAABRlSURBVFZ4D2d8ZABvzOpLoLtMQiZEW5CgF22iprKOg6uSuHy2Eg+bW9SG7MLxwHkWZEBmZB9+GzyLMu8A3pnZl5kDAmX6AiHakAS9aFVaa64kZhP72XlqaxVuHtu4VnSEWZ9XYLC3Yd2YxXzuFsWUqEB+N7MfPi725i5ZCIsnQS9aTVlhNYdWJ3AttQ4P2xvkB24j9MAlhmTD9X5R/CZ0DsrTi5XzBzC2t0xfIMS9IkEvWkxrzaXjmRxal0x9nRFX3+2kZxxm2oYa6p0c+GjCEra49GLe4GBenxGJi4NMQibEvSRBL1qkOLeSAx8nkHXLgLvtNa4FbqLbnhtE58PF/oN5NXQO3v5erJ7Vjwd7+pi7XCE6JQl60SzaqDm9K5WEHTexMlTh7L+VokvxzNlbT6W3K38ds4gDHr14ZlQ3/mNchIzihTCjZge9UqoX8EWjpm7Aa1rrdxrtM4aGB4dfMzVt1Fq/0dxjivahMKuCvf86QX4ueDucJtljH5O33cKjAk4NH8MfvMcTGOTDxvlRDAr1MHe5QnR6zQ56rXUqMBBAKWUNZACbmtj1kNZ6enOPI9qP+loDp3ZeImFnJnaqHFv/byhMTuLhc0ZKfT353cglJDiH8sK4Hjw7uhsOtjJ9gRDtQWuduhkPXNFa32ilzxPtTOalIuJWJ1JQYI1Xl+Ncst7DxG25uFYpjt4/mT95jaZXqDc7Fgygl7+LucsVQjTSWkG/GFh/h20jlFJngEzg51rr5KZ2UkotA5YBhIaGtlJZoqXqagyc2HiBMwdzcbQqRQVvpDLxFAsuaoqC/fnFg0u55uLPz8b34NkHu8mNT0K0Q0pr3bIPUMqOhhDvq7XOuW2bK2DUWpcrpaYC72qte3zfZ0ZHR+vExMQW1SVa7taFAuLWJFFcbIWv80EusI8p+4pxNFgRO3Qab/uM4v4ePvx+Vj+6+Tibu1whOjWlVJLWOrqpba0xop8CnLw95AG01qWNlncopT5QSnlrrfNb4biijdRW13P4s5OkJJXhYp1LZci3qIOnWXgTciK68XL4PHI8Avn91D48MixUJiETop1rjaB/mDuctlFK+QM5WmutlBoGWAEFrXBM0Qa01tw4m8eBVWeoqlJ4u+0itSqOWevKUNY2bBw9l0/coxkX6c/ns/rJJGRCdBAtCnqlVBdgIvBso7bnALTWHwLzgR8rpeqBKmCxbum5ItEmKkpqOPzZSdLOV+Fmk0lR4GYcYi+yIBMye/bk1fD5VHr58d6c/kzp5y/n4oXoQFoU9FrrSsDrtrYPGy2/B7zXkmOItqW15tKJLOLWnqeuTuHutY0bBUeY/kUlRjs7Vk94hA1OfZk5MIg35/STG5+E6IDkzthOrCSvisOfJXH9Ui2edmmcHribAVsvM+eq5mpkf34TvoAuPl4snxHJpL7+5i5XCNFMEvSdkNaa5JirHPnmKspYg6P/Lj7zPMKyr2vpla5ZM3wB6wOGs+S+rvx8Ui/cusgoXoiOTIK+kynNr2L3+8fJzdL42J/nYN89eJy8yZ+/1NTbOfD3QTNI7TeGDfOiuK+b1/d/oBCi3ZOg7yQMBiNndqdxYvtNbHQVLsEb+cLxLMvWVhOaYyQhdADv9ZnO/CnR/H1sBE728r+GEJZC/jR3AvnpZcSsiCc3W+HrmMS3vWMIS7zFG0eM1Nh14Q9D55MzcASfLBpE/2A3c5crhGhlEvQWzFBvJHHrRZL2ZmJHBYRv5KvaJH68RuNfYORo10G8HzWXZ6cP4ulR3bCWG5+EsEgS9BYqI7WQg6sSKSqywc8pjvX9DzFybw6vn4IiF09+M2IO1vfdz4bZ/ejpJ5OQCWHJJOgtTH2tgaMbzpB8rBAnq1wqe+3jv92SePqgA2OTNPvCh7N2yFyem9KfJSPCZBQvRCcgQW9BMlIL2bc8ifIKa3xcD7Cq71Hssgv45+dd8MwsZWv4SE7PfopNiwcS4CbTFwjRWUjQW4Cq8lqObThDSmLDJGRFfbaw2uECTxxxYUxcPcX2Rv408kmmPreI/xoSIpOQCdHJSNB3cFdP5hC75gxV1Ta4eu7k055HCbpexj8OOOGWW8yursO4NOdJ3l4yAk8nO3OXK4QwAwn6DqqiuIYja09x+VwlrjZZXBmwhVXWl3g+zoNhR+vI7uLCexNfYMFTM/npwCBzlyuEMCMJ+g4o9VgGRzacp7ZG4+a9m+W9jhKeVsm/9jriWFTA1vCR5D+6jPfnDpLpC4QQEvQdSUVxDQdWxHMzrQ5Pu6ucGbibeJ3GT7c70/9MPddcndnw0DM88dxsxvb2NXe5Qoh2QoK+AzAaNckx1zjyzRWUrsfRfzv/DI8nOqWOj3ZZY1VTxme9J+G4ZCn/nNofN0cZxQsh/h8J+nauMLOC2JUJZKUb8bE/z+6++7lSfZ1XtroSkVzOJfdg1k5Zyn89O5WhYZ7mLlcI0Q5J0LdThjojp3ZeJmHnLaypwTpkI28FJTI9yYoXD1phNJSzPGoWIU8t5bPxPbG3sTZ3yUKIdqqljxK8DpQBBqD+9ieQq4bnzb0LTAUqgR9prU+25JidQd6tMmJXxJObo/DtEs9XUQcoLMrmz1+7EpRWxAm/PsRO/hEvLRktk5AJIb5Xa4zox2qt8++wbQrQw/QzHPiX6VU0wWAwcuLrC5yOycbeqgyrbpv5o+9p5p20Z+ZBa6p1De8NWUjUM0tYMaobNtZW5i5ZCNEBtPWpm1nAGtMDwY8rpdyVUgFa66w2Pm6Hk321hL0fJVBaYoWPcwzr+x2nJj+Hf6x2xCurjGP+fTk+ZSkvLR1DL3+ZhEwIcfdaGvQa2KOU0sBHWuvlt20PAm41Wk83tf2voFdKLQOWAYSGhrawrI6jrsbAsS/OcO5oMc7W+ZRFbGOFxxkeT3DhoQNGym2N/GX4Eib8+FE+GBoio3ghxA/W0qAfqbXOVEr5AnuVUhe11nGNtjc1qYpu6oNMf0ksB4iOjm5yH0tz60IBMSuTKCu3wdd1L2sij2OXkcd7G1zxvFVETPAgEmc8we+XPkCQu0xCJoRonhYFvdY60/Saq5TaBAwDGgd9OhDSaD0YyGzJMS1BVVktx788y4WEUpyt8ymM3Mqnjud5+pATo44aKbGv568PPs2kZxbwSXQIDb/TFkKI5ml20CulnAArrXWZaXkS8MZtu20FnldKbaDhl7Alnf38/OX4LI5sOEtVpcLDYz/L+xwk5FolH3zpiFNBGXtCh3Jl4TP8cUE0vq4O5i5XCGEBWjKi9wM2mUabNsA6rfUupdRzAFrrD4EdNFxamUbD5ZVPtKzcjquytJaDnyZwNaUGD9sbpEXtZaVNCi/ucWVQUj23nDx4b/yPWLhsDj+NCjR3uUIIC9LsoNdaXwUGNNH+YaNlDfykucewBFprUo9lELfuAsZ6A04+O3k/4jiRl2tYvssWu/Jivo4YTfXDS3ln9mCZSlgI0erkztg2VJpfRcwn8aRfM+Bld5kjQ/ZxruoyP9/hRu8zZVx38eOzKUt4/iezuD/C29zlCiEslAR9GzAajJyPucGxTWlogwH7wE280zWJUefqeSfGFuuqElZFTsH+kcdYMTOKLnbyn0EI0XYkYVpZfnoZcasSyEoHT/sLHBiym0sVN/ntNy50vVTBRY9Qvpj+NC89MV4mIRNC3BMS9K3EaNSc3J5K4q5b2FKOXeh2/hyYyOgUK/6x1xZjbSX/GLyQXk88wpqxPbCzkRufhBD3hgR9K8hPL2ffhycoyFf4OiawMeoguSUZ/G29EwE3Skn2DGPTzCd55ZlJ9AuSSciEEPeWBH0L1NcaSNiczKmYXBxUMcbwbfzZ5zSzT9oxe7+myrqWfwxeSNTTj7Lywe4ylbAQwiwk6Jsp41IR+z9OpKzMGj/nQ6yJPIwxP4e/rXfG51YJx/z7EjdlKW88PZ5Qry7mLlcI0YlJ0P9ANZV1nPj6POeOFuJinUNVr295y/U8S050YcIhTblNPX8Z+QRjnlrAyvvCsLKS6QuEEOYlQf8DXDudy+G1pykrU3i5xbIy8iDut4r5x1YnPLJKiQkexPn5y3hj0TCCPWQUL4RoHyTo70JNZR1xq5O4dKYSN5tMCvruYLXdBZ7f48TgU5ocR1v+OnoZ059bwI8HBskkZEKIdkWC/jtorbl8IoND6y9QWwOunntYE3kCv7Ri3tvtgGNxOZu7PUDJ/CW8OTcafzeZhEwI0f5I0N9BeVE1Bz6O59bVerxsr5AStY8jKpUXdroyMKmedCd3/jr5OZ5+ZgYTI/3MXa4QQtyRBP1tjEbNhbibHPsmFWN9Pa7+W/mg22miUqp574A9DqXFrOs1AcPDS/l07kCZvkAI0e5JSjVSUVxDzIoT3Eirx8suldjBu7lQc50Xt7vS52wN11wDWD/7RZ57agojZRIyIUQHIUEPaKMmOeYaxzalYag34BK4hb+HJfDAec27MfaoqgrW9JmM44+e4uOpfXCwlRufhBAdR6cP+oKMcmI/iSc7s2ESskMDY7hYcYXXv3Ym/FIJ573C+XbKEn7y5EMyCZkQokPqtEFfX2sgcUsKpw5kY0cZdN3OOwEnmXjWmnf2W1FvrObjqNl0fXop/xrTA0c7GcULITqmThn0mWnFHPg4gZISa/ydDrGh32Eq8nN4a4Mz/tdLOOnTg11TnuLXT46lt7+rucsVQogWacnDwUOANYA/YASWa63fvW2fMcAW4JqpaaPW+vYHiN8ztdX1nNyeysn9WThb5VHbcyt/9EhhYZIDU2OgyrqOt+9bwn1PLWb1yHCZvkAIYRFaMqKvB17SWp9USrkASUqpvVrrC7ftd0hrPb0Fx2kV6RcLif00kZISG7ycj7Ku/wHIzudvG1zwvVHMMf++HJnzLK8/NlImIRNCWJSWPBw8C8gyLZcppVKAIOD2oDer2up6Dq89Q0pCMc7W+VT03s7Hrmf50RFHJh6BYlsD7478ESOfWcyK4aEyfYEQwuK0yjl6pVQYMAg40cTmEUqpM0Am8HOtdfIdPmMZsAwgNDS0Ncrixrl8YlclUVFhhZfbPlb3PYbTrUI++toB1/xy9oUM4cLsJ3hjyUh8XWX6AiGEZWpx0CulnIFvgBe11qW3bT4JdNValyulpgKbgR5NfY7WejmwHCA6Olq3pKaqslriVieSdr4aV5tM0vvuZo3teZbtd2bECQM5Xex4/8FHmfd/FvL8gEAZxQshLFqLgl4pZUtDyK/VWm+8fXvj4Nda71BKfaCU8tZa57fkuHfSMAlZJgfXJlNXZ4WH9zY+iDhBxPVqPthpj2NJCZu6j6Jg/lL+sWgo7l3s2qIMIYRoV1py1Y0CPgFStNZv32EffyBHa62VUsMAK6Cgucf8LnU1BvZ/eJQrKXW42d7g4uCdHDNc4v/EejDkeAkZzt58NPUn/OTZ6Yzp5dsWJQghRLvUkhH9SGAJcE4pddrU9isgFEBr/SEwH/ixUqoeqAIWa61bdFrmTlRNMeVXkrHxP8/fww4z9rSBfx20xrq6kI0RD1L66DI+ntVfRvFCiE6nJVfdHAa+8+S21vo94L3mHuOHqHSwZduDO7mSe4U/fuNCyOViTvr0IHbOY7zw5EP0D3a7F2UIIUS7YzF3xnax6cLQK/a8tMEGY20F7w2cS+jjj/LBQ72xtbYyd3lCCGE2FhP05XnFjFh3hVTnQDZPW8Ivn5tCVLC7ucsSQgizs5igd/P1YttTv6XnkL58OjwMOxsZxQshBFhQ0Cul+O0LM8xdhhBCtDsy7BVCCAsnQS+EEBZOgl4IISycBL0QQlg4CXohhLBwEvRCCGHhJOiFEMLCSdALIYSFU200mWSLKKXygBvNfLs30Cbz3Xcg0gcNpB+kD/6tM/RDV621T1Mb2mXQt4RSKlFrHW3uOsxJ+qCB9IP0wb919n6QUzdCCGHhJOiFEMLCWWLQLzd3Ae2A9EED6Qfpg3/r1P1gcefohRBC/P8scUQvhBCiEQl6IYSwcBYT9EqpyUqpVKVUmlLqZXPX05aUUiuVUrlKqfON2jyVUnuVUpdNrx6Ntr1i6pdUpdRD5qm6dSmlQpRSMUqpFKVUslLqP03tnaYflFIOSql4pdQZUx/8ztTeafrg35RS1kqpU0qp7ab1TtcH30lr3eF/AGvgCtANsAPOAJHmrqsNv++DwGDgfKO2PwMvm5ZfBv5kWo409Yc9EG7qJ2tzf4dW6IMAYLBp2QW4ZPqunaYfAAU4m5ZtgRPAfZ2pDxr1xc+AdcB203qn64Pv+rGUEf0wIE1rfVVrXQtsAGaZuaY2o7WOAwpva54FrDYtrwZmN2rfoLWu0VpfA9Jo6K8OTWudpbU+aVouA1KAIDpRP+gG5aZVW9OPphP1AYBSKhiYBqxo1Nyp+uD7WErQBwG3Gq2nm9o6Ez+tdRY0hCDga2q3+L5RSoUBg2gY0XaqfjCdsjgN5AJ7tdadrg+Ad4BfAMZGbZ2tD76TpQS9aqJNrhttYNF9o5RyBr4BXtRal37Xrk20dfh+0FobtNYDgWBgmFKq33fsbnF9oJSaDuRqrZPu9i1NtHXoPrgblhL06UBIo/VgINNMtZhLjlIqAMD0mmtqt9i+UUrZ0hDya7XWG03Nna4fALTWxUAsMJnO1QcjgZlKqes0nLIdp5T6nM7VB9/LUoI+AeihlApXStkBi4GtZq7pXtsKLDUtLwW2NGpfrJSyV0qFAz2AeDPU16qUUgr4BEjRWr/daFOn6QellI9Syt207AhMAC7SifpAa/2K1jpYax1Gw5/7A1rrx+hEfXBXzP3b4Nb6AabScOXFFeDX5q6njb/reiALqKNhhPIU4AXsBy6bXj0b7f9rU7+kAlPMXX8r9cEDNPyT+yxw2vQztTP1AxAFnDL1wXngNVN7p+mD2/pjDP/vqptO2Qd3+pEpEIQQwsJZyqkbIYQQdyBBL4QQFk6CXgghLJwEvRBCWDgJeiGEsHAS9EIIYeEk6IUQwsL9X7OgvlrzcGecAAAAAElFTkSuQmCC",
- "text/plain": [
- "<Figure size 432x288 with 1 Axes>"
- ]
- },
- "metadata": {
- "needs_background": "light"
- },
- "output_type": "display_data"
- }
- ],
- "source": [
- "plt.plot(cam1)\n",
- "plt.plot(cam2)\n",
- "plt.plot(cam3)\n",
- "plt.plot(cam4)\n",
- "plt.plot(cam5)"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": []
- }
- ],
- "metadata": {
- "interpreter": {
- "hash": "5f2daf2994cb107dacf5429ca85e18c6780d4b3f53e6372ad77e762db2af8054"
- },
- "kernelspec": {
- "display_name": "Python 3.7.11 64-bit ('fmc43rc': conda)",
- "language": "python",
- "name": "python3"
- },
- "language_info": {
- "codemirror_mode": {
- "name": "ipython",
- "version": 3
- },
- "file_extension": ".py",
- "mimetype": "text/x-python",
- "name": "python",
- "nbconvert_exporter": "python",
- "pygments_lexer": "ipython3",
- "version": "3.7.11"
- },
- "orig_nbformat": 4
- },
- "nbformat": 4,
- "nbformat_minor": 2
-}
diff --git a/freemocap/docs/version_history.md b/freemocap/docs/version_history.md
deleted file mode 100644
index 1db8ae11..00000000
--- a/freemocap/docs/version_history.md
+++ /dev/null
@@ -1,76 +0,0 @@
-# FreeMoCap Version History
-__________________________
-
-# Version - v0.0.43
- ```
- Date - 2021-11-28
- Status - Pre-Alpha
-```
-## Summary
-
-v0.0.43 is probably the last major update we'll make to the `pre-alpha` version of FreeMoCap. There will almost certainly be many bugfixes and usability tweaks, but no new major "deep level" development is intended on *this* iteration of this codebase.
-
-A notable exception to the previous statement is the [Blender](https://blender.org) related functionality introducted in this release! These features are all still experimental and will be getting a lot of attention and upgrades in the coming weeks/months. Keep an eye out for updates!
-
-The current `pre-alpha` version is a reasonably stable, reliable piece of code that performs it's intended purposes fairly wel. However, it still not particularly well-built for easy use by people outside of my lab (i.e. outside of the group that originally built it). We have learned a tremendous amount from this process of development, and will be taking those lessons into the next development phase.
-
-The next iteration (v0.1.0 - `freemocap-alpha`) will be a massive, near-complete overhaul that carries over very little of the current codebase.
-
-~βœ¨πŸ’€βœ¨~
-
-----
-## Significant Changes
-- Updated ReadMe!
-
-- Labels and print statements overhauled to make things prettier and (hopefully) more intuitive and user-friendly (with heavy use of the [Rich](https://github.com/willmcgugan/rich) Python package)
-
-
-
-
-- Setting Calibration default settings to use the first half of the recording rather than the full recording. We've found this makes AniPose more likely to complete successfully. We also added some tweaks and `try/except` block to make the Anipose calibration more reliable
-
-
-- Tweaks to make it easier to run freemocap on a folder of synced video from another source (e.g GoPros!)! Just place the synced videos (each of which has **exactly** the same number of frames) in a folder called `SyncedVideos`, place this folder in a folder called named whatever you want the `SessionID` to be, place THAT folder in the `FreeMoCap_Data` folder, and run freemocap on that session folder starting at stage 3 (so if the `sessionID` is `test-session`, run - `freemocap.RunMe(sessionID='test-session', stage=3)`)
-
-
-
-- Clean up unnecessary output folders (from MediaPipe, etc)
-
-- OpenPose no longer saves images for each frame of each camera, which makes session folders MUCH smaller and easier to move around - ()It still saves a one JSON per frame per camera though)
-
- - Option to plot a (MUCH LOWER ACCURACY) MediaPipe skeleton overlaid on SetUp video feed from each camera. Useful for helping set up cameras to provide good data.
-
- - Added 'frame number' to animation output
-
-
- - Animation output method will first attempt to use an `ffmpeg-enabled` exporter, and if that fails it will try a much slower `pillow based` method (and print instructions on how the user can install `ffmpeg`)
-
-- (EXPERIMENTAL, but exciting!) Output MediaPipe skeletonto `.blend`, `.fbx`, `.usd`, .`gltf` formats (requires [Blender](https://blender.org) installed). This will be getting a lot of attention in the coming weeks, so keep an eye out for future updates!
-
-- (EXPERIMENTAL) Minimally functional Blender addon added in `/freemocap_blender_addon`
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-## Major Changes
-
-- Full overhaul of labels and terminal output (including heavy use the the [Rich](https://github.com/willmcgugan/rich) python package)to improve usability and provide better feedback and support
-
-- Support reconstruction of externally recorded videos (e.g. GoPros)
-- (EXPERIMENTAL) Output data to `.blend`, `.fbx`, `.usd`, .`gltf` formats (requires [Blender](https://blender.org) installed)
-- (EXPERIMENTAL) Minimally functional Blender addon added in `/freemocap_blender_addon`
-
-
- - Multitudinous bug fixes
-
-____________________________
diff --git a/freemocap/dto/run_me_options.py b/freemocap/dto/run_me_options.py
deleted file mode 100644
index 8c0c9bed..00000000
--- a/freemocap/dto/run_me_options.py
+++ /dev/null
@@ -1,25 +0,0 @@
-from pydantic import BaseModel
-
-
-class RunMeOptions(BaseModel):
- sessionID: str
- stage: int
- useOpenPose: bool = False
- runOpenPose: bool = True
- useMediaPipe: bool = True
- runMediaPipe: bool = True
- useDLC: bool = False
- dlcConfigPath: str
- debug: bool = False
- setDataPath: bool = False
- userDataPath: str = None
- recordVid: bool = True
- showAnimation: bool = True
- reconstructionConfidenceThreshold: float = .7
- # mm -
- # the size of the squares when printed on 8.5x11" paper based on parameters in ReadMe.md
- charucoSquareSize: int = 36
- calVideoFrameLength: float = .5
- startFrame: int = 0
- useBlender: bool = False
- resetBlenderExe: bool = False
diff --git a/freemocap/fmc_anipose.py b/freemocap/fmc_anipose.py
deleted file mode 100644
index 1b956c05..00000000
--- a/freemocap/fmc_anipose.py
+++ /dev/null
@@ -1,1665 +0,0 @@
-import cv2
-import numpy as np
-from copy import copy
-from scipy.sparse import lil_matrix, dok_matrix
-from scipy import optimize
-from scipy import signal
-from numba import jit
-from collections import defaultdict, Counter
-import toml
-import itertools
-from tqdm import trange
-from pprint import pprint
-import time
-
-from aniposelib.boards import merge_rows, extract_points, \
- extract_rtvecs, get_video_params
-from aniposelib.utils import get_initial_extrinsics, make_M, get_rtvec, \
- get_connections
-
-
-@jit(nopython=True, parallel=True)
-def triangulate_simple(points, camera_mats):
- num_cams = len(camera_mats)
- A = np.zeros((num_cams * 2, 4))
- for i in range(num_cams):
- x, y = points[i]
- mat = camera_mats[i]
- A[(i * 2):(i * 2 + 1)] = x * mat[2] - mat[0]
- A[(i * 2 + 1):(i * 2 + 2)] = y * mat[2] - mat[1]
- u, s, vh = np.linalg.svd(A, full_matrices=True)
- p3d = vh[-1]
- p3d = p3d[:3] / p3d[3]
- return p3d
-
-
-def get_error_dict(errors_full, min_points=10):
- n_cams = errors_full.shape[0]
- errors_norm = np.linalg.norm(errors_full, axis=2)
-
- good = ~np.isnan(errors_full[:, :, 0])
-
- error_dict = dict()
-
- for i in range(n_cams):
- for j in range(i + 1, n_cams):
- subset = good[i] & good[j]
- err_subset = errors_norm[:, subset][[i, j]]
- err_subset_mean = np.mean(err_subset, axis=0)
- if np.sum(subset) > min_points:
- percents = np.percentile(err_subset_mean, [15, 75])
- # percents = np.percentile(err_subset, [25, 75])
- error_dict[(i, j)] = (err_subset.shape[1], percents)
- return error_dict
-
-
-def check_errors(cgroup, imgp):
- p3ds = cgroup.triangulate(imgp)
- errors_full = cgroup.reprojection_error(p3ds, imgp, mean=False)
- return get_error_dict(errors_full)
-
-
-def subset_extra(extra, ixs):
- if extra is None:
- return None
-
- new_extra = {
- 'objp': extra['objp'][ixs],
- 'ids': extra['ids'][ixs],
- 'rvecs': extra['rvecs'][:, ixs],
- 'tvecs': extra['tvecs'][:, ixs]
- }
- return new_extra
-
-
-def resample_points_extra(imgp, extra, n_samp=25):
- n_cams, n_points, _ = imgp.shape
- ids = remap_ids(extra['ids'])
- n_ids = np.max(ids) + 1
- good = ~np.isnan(imgp[:, :, 0])
- ixs = np.arange(n_points)
-
- cam_counts = np.zeros((n_ids, n_cams), dtype='int64')
- for idnum in range(n_ids):
- cam_counts[idnum] = np.sum(good[:, ids == idnum], axis=1)
- cam_counts_random = cam_counts + np.random.random(size=cam_counts.shape)
- best_boards = np.argsort(-cam_counts_random, axis=0)
-
- cam_totals = np.zeros(n_cams, dtype='int64')
-
- include = set()
- for cam_num in range(n_cams):
- for board_id in best_boards[:, cam_num]:
- include.update(ixs[ids == board_id])
- cam_totals += cam_counts[board_id]
- if cam_totals[cam_num] >= n_samp or \
- cam_counts_random[board_id, cam_num] < 1:
- break
-
- final_ixs = sorted(include)
- newp = imgp[:, final_ixs]
- extra = subset_extra(extra, final_ixs)
- return newp, extra
-
-
-def resample_points(imgp, extra=None, n_samp=25):
- # if extra is not None:
- # return resample_points_extra(imgp, extra, n_samp)
-
- n_cams = imgp.shape[0]
- good = ~np.isnan(imgp[:, :, 0])
- ixs = np.arange(imgp.shape[1])
-
- num_cams = np.sum(~np.isnan(imgp[:, :, 0]), axis=0)
-
- include = set()
-
- for i in range(n_cams):
- for j in range(i + 1, n_cams):
- subset = good[i] & good[j]
- n_good = np.sum(subset)
- if n_good > 0:
- ## pick points, prioritizing points seen by more cameras
- arr = np.copy(num_cams[subset]).astype('float64')
- arr += np.random.random(size=arr.shape)
- picked_ix = np.argsort(-arr)[:n_samp]
- picked = ixs[subset][picked_ix]
- include.update(picked)
-
- final_ixs = sorted(include)
- newp = imgp[:, final_ixs]
- extra = subset_extra(extra, final_ixs)
- return newp, extra
-
-
-def medfilt_data(values, size=15):
- padsize = size + 5
- vpad = np.pad(values, (padsize, padsize), mode='reflect')
- vpadf = signal.medfilt(vpad, kernel_size=size)
- return vpadf[padsize:-padsize]
-
-
-def nan_helper(y):
- return np.isnan(y), lambda z: z.nonzero()[0]
-
-
-def interpolate_data(vals):
- nans, ix = nan_helper(vals)
- out = np.copy(vals)
- try:
- out[nans] = np.interp(ix(nans), ix(~nans), vals[~nans])
- except ValueError:
- out[:] = 0
- return out
-
-
-def remap_ids(ids):
- unique_ids = np.unique(ids)
- ids_out = np.copy(ids)
- for i, num in enumerate(unique_ids):
- ids_out[ids == num] = i
- return ids_out
-
-
-def transform_points(points, rvecs, tvecs):
- """Rotate points by given rotation vectors and translate.
- Rodrigues' rotation formula is used.
- """
- theta = np.linalg.norm(rvecs, axis=1)[:, np.newaxis]
- with np.errstate(invalid='ignore'):
- v = rvecs / theta
- v = np.nan_to_num(v)
- dot = np.sum(points * v, axis=1)[:, np.newaxis]
- cos_theta = np.cos(theta)
- sin_theta = np.sin(theta)
-
- rotated = cos_theta * points + \
- sin_theta * np.cross(v, points) + \
- dot * (1 - cos_theta) * v
-
- return rotated + tvecs
-
-
-class Camera:
- def __init__(self,
- matrix=np.eye(3),
- dist=np.zeros(5),
- size=None,
- rvec=np.zeros(3),
- tvec=np.zeros(3),
- name=None,
- extra_dist=False):
-
- self.set_camera_matrix(matrix)
- self.set_distortions(dist)
- self.set_size(size)
- self.set_rotation(rvec)
- self.set_translation(tvec)
- self.set_name(name)
- self.extra_dist = extra_dist
-
- def get_dict(self):
- return {
- 'name': self.get_name(),
- 'size': list(self.get_size()),
- 'matrix': self.get_camera_matrix().tolist(),
- 'distortions': self.get_distortions().tolist(),
- 'rotation': self.get_rotation().tolist(),
- 'translation': self.get_translation().tolist(),
- }
-
- def load_dict(self, d):
- self.set_camera_matrix(d['matrix'])
- self.set_rotation(d['rotation'])
- self.set_translation(d['translation'])
- self.set_distortions(d['distortions'])
- self.set_name(d['name'])
- self.set_size(d['size'])
-
- def from_dict(d):
- cam = Camera()
- cam.load_dict(d)
- return cam
-
- def get_camera_matrix(self):
- return self.matrix
-
- def get_distortions(self):
- return self.dist
-
- def set_camera_matrix(self, matrix):
- self.matrix = np.array(matrix, dtype='float64')
-
- def set_focal_length(self, fx, fy=None):
- if fy is None:
- fy = fx
- self.matrix[0, 0] = fx
- self.matrix[1, 1] = fy
-
- def get_focal_length(self, both=False):
- fx = self.matrix[0, 0]
- fy = self.matrix[1, 1]
- if both:
- return (fx, fy)
- else:
- return (fx + fy) / 2.0
-
- def set_distortions(self, dist):
- self.dist = np.array(dist, dtype='float64').ravel()
-
- def set_rotation(self, rvec):
- self.rvec = np.array(rvec, dtype='float64').ravel()
-
- def get_rotation(self):
- return self.rvec
-
- def set_translation(self, tvec):
- self.tvec = np.array(tvec, dtype='float64').ravel()
-
- def get_translation(self):
- return self.tvec
-
- def get_extrinsics_mat(self):
- return make_M(self.rvec, self.tvec)
-
- def get_name(self):
- return self.name
-
- def set_name(self, name):
- self.name = str(name)
-
- def set_size(self, size):
- """set size as (width, height)"""
- self.size = size
-
- def get_size(self):
- """get size as (width, height)"""
- return self.size
-
- def resize_camera(self, scale):
- """resize the camera by scale factor, updating intrinsics to match"""
- size = self.get_size()
- new_size = size[0] * scale, size[1] * scale
- matrix = self.get_camera_matrix()
- new_matrix = matrix * scale
- new_matrix[2, 2] = 1
- self.set_size(new_size)
- self.set_camera_matrix(new_matrix)
-
- def get_params(self):
- params = np.zeros(8 + self.extra_dist, dtype='float64')
- params[0:3] = self.get_rotation()
- params[3:6] = self.get_translation()
- params[6] = self.get_focal_length()
- dist = self.get_distortions()
- params[7] = dist[0]
- if self.extra_dist:
- params[8] = dist[1]
- return params
-
- def set_params(self, params):
- self.set_rotation(params[0:3])
- self.set_translation(params[3:6])
- self.set_focal_length(params[6])
-
- dist = np.zeros(5, dtype='float64')
- dist[0] = params[7]
- if self.extra_dist:
- dist[1] = params[8]
- self.set_distortions(dist)
-
- def distort_points(self, points):
- shape = points.shape
- points = points.reshape(-1, 1, 2)
- new_points = np.dstack([points, np.ones((points.shape[0], 1, 1))])
- out, _ = cv2.projectPoints(new_points, np.zeros(3), np.zeros(3),
- self.matrix.astype('float64'),
- self.dist.astype('float64'))
- return out.reshape(shape)
-
- def undistort_points(self, points):
- shape = points.shape
- points = points.reshape(-1, 1, 2)
- out = cv2.undistortPoints(points,
- self.matrix.astype('float64'),
- self.dist.astype('float64'))
- return out.reshape(shape)
-
- def project(self, points):
- points = points.reshape(-1, 1, 3)
- out, _ = cv2.projectPoints(points, self.rvec, self.tvec,
- self.matrix.astype('float64'),
- self.dist.astype('float64'))
- return out
-
- def reprojection_error(self, p3d, p2d):
- proj = self.project(p3d).reshape(p2d.shape)
- return p2d - proj
-
- def copy(self):
- return \
- Camera(matrix=self.get_camera_matrix().copy(),
- dist=self.get_distortions().copy(),
- size=self.get_size(),
- rvec=self.get_rotation().copy(),
- tvec=self.get_translation().copy(),
- name=self.get_name(),
- extra_dist=self.extra_dist)
-
-
-class FisheyeCamera(Camera):
- def __init__(self,
- matrix=np.eye(3),
- dist=np.zeros(4),
- size=None,
- rvec=np.zeros(3),
- tvec=np.zeros(3),
- name=None,
- extra_dist=False):
- self.set_camera_matrix(matrix)
- self.set_distortions(dist)
- self.set_size(size)
- self.set_rotation(rvec)
- self.set_translation(tvec)
- self.set_name(name)
- self.extra_dist = extra_dist
-
- def from_dict(d):
- cam = FisheyeCamera()
- cam.load_dict(d)
- return cam
-
- def get_dict(self):
- d = super().get_dict()
- d['fisheye'] = True
- return d
-
- def distort_points(self, points):
- shape = points.shape
- points = points.reshape(-1, 1, 2)
- new_points = np.dstack([points, np.ones((points.shape[0], 1, 1))])
- out, _ = cv2.fisheye.projectPoints(new_points,
- np.zeros(3), np.zeros(3),
- self.matrix.astype('float64'),
- self.dist.astype('float64'))
- return out.reshape(shape)
-
- def undistort_points(self, points):
- shape = points.shape
- points = points.reshape(-1, 1, 2)
- out = cv2.fisheye.undistortPoints(points.astype('float64'),
- self.matrix.astype('float64'),
- self.dist.astype('float64'))
- return out.reshape(shape)
-
- def project(self, points):
- points = points.reshape(-1, 1, 3)
- out, _ = cv2.fisheye.projectPoints(points,
- self.rvec, self.tvec,
- self.matrix.astype('float64'),
- self.dist.astype('float64'))
- return out
-
- def set_params(self, params):
- self.set_rotation(params[0:3])
- self.set_translation(params[3:6])
- self.set_focal_length(params[6])
-
- dist = np.zeros(4, dtype='float64')
- dist[0] = params[7]
- if self.extra_dist:
- dist[1] = params[8]
- # dist[2] = params[9]
- # dist[3] = params[10]
- self.set_distortions(dist)
-
- def get_params(self):
- params = np.zeros(8 + self.extra_dist, dtype='float64')
- params[0:3] = self.get_rotation()
- params[3:6] = self.get_translation()
- params[6] = self.get_focal_length()
- dist = self.get_distortions()
- params[7] = dist[0]
- if self.extra_dist:
- params[8] = dist[1]
- # params[9] = dist[2]
- # params[10] = dist[3]
- return params
-
- def copy(self):
- return FisheyeCamera(
- matrix=self.get_camera_matrix().copy(),
- dist=self.get_distortions().copy(),
- size=self.get_size(),
- rvec=self.get_rotation().copy(),
- tvec=self.get_translation().copy(),
- name=self.get_name(),
- extra_dist=self.extra_dist)
-
-
-class CameraGroup:
- def __init__(self, cameras, metadata={}):
- self.cameras = cameras
- self.metadata = metadata
-
- def subset_cameras(self, indices):
- cams = [self.cameras[ix].copy() for ix in indices]
- return CameraGroup(cams, self.metadata)
-
- def subset_cameras_names(self, names):
- cur_names = self.get_names()
- cur_names_dict = dict(zip(cur_names, range(len(cur_names))))
- indices = []
- for name in names:
- if name not in cur_names_dict:
- raise IndexError(
- "name {} not part of camera names: {}".format(
- name, cur_names
- ))
- indices.append(cur_names_dict[name])
- return self.subset_cameras(indices)
-
- def project(self, points):
- """Given an Nx3 array of points, this returns an CxNx2 array of 2D points,
- where C is the number of cameras"""
- points = points.reshape(-1, 1, 3)
- n_points = points.shape[0]
- n_cams = len(self.cameras)
-
- out = np.empty((n_cams, n_points, 2), dtype='float64')
- for cnum, cam in enumerate(self.cameras):
- out[cnum] = cam.project(points).reshape(n_points, 2)
-
- return out
-
- def triangulate(self, points, undistort=True, progress=False):
- """Given an CxNx2 array, this returns an Nx3 array of points,
- where N is the number of points and C is the number of cameras"""
-
- assert points.shape[0] == len(self.cameras), \
- "Invalid points shape, first dim should be equal to" \
- " number of cameras ({}), but shape is {}".format(
- len(self.cameras), points.shape
- )
-
- one_point = False
- if len(points.shape) == 2:
- points = points.reshape(-1, 1, 2)
- one_point = True
-
- if undistort:
- new_points = np.empty(points.shape)
- for cnum, cam in enumerate(self.cameras):
- # must copy in order to satisfy opencv underneath
- sub = np.copy(points[cnum])
- new_points[cnum] = cam.undistort_points(sub)
- points = new_points
-
- n_cams, n_points, _ = points.shape
-
- out = np.empty((n_points, 3))
- out[:] = np.nan
-
- cam_mats = np.array([cam.get_extrinsics_mat() for cam in self.cameras])
-
- if progress:
- iterator = trange(n_points, ncols=70)
- else:
- iterator = range(n_points)
-
- for ip in iterator:
- subp = points[:, ip, :]
- good = ~np.isnan(subp[:, 0])
- if np.sum(good) >= 2:
- out[ip] = triangulate_simple(subp[good], cam_mats[good])
-
- if one_point:
- out = out[0]
-
- return out
-
- def triangulate_possible(self, points, undistort=True,
- min_cams=2, progress=False, threshold=0.5):
- """Given an CxNxPx2 array, this returns an Nx3 array of points
- by triangulating all possible points and picking the ones with
- best reprojection error
- where:
- C: number of cameras
- N: number of points
- P: number of possible options per point
- """
-
- assert points.shape[0] == len(self.cameras), \
- "Invalid points shape, first dim should be equal to" \
- " number of cameras ({}), but shape is {}".format(
- len(self.cameras), points.shape
- )
-
- n_cams, n_points, n_possible, _ = points.shape
-
- cam_nums, point_nums, possible_nums = np.where(
- ~np.isnan(points[:, :, :, 0]))
-
- all_iters = defaultdict(dict)
-
- for cam_num, point_num, possible_num in zip(cam_nums, point_nums,
- possible_nums):
- if cam_num not in all_iters[point_num]:
- all_iters[point_num][cam_num] = []
- all_iters[point_num][cam_num].append((cam_num, possible_num))
-
- for point_num in all_iters.keys():
- for cam_num in all_iters[point_num].keys():
- all_iters[point_num][cam_num].append(None)
-
- out = np.full((n_points, 3), np.nan, dtype='float64')
- picked_vals = np.zeros((n_cams, n_points, n_possible), dtype='bool')
- errors = np.zeros(n_points, dtype='float64')
- points_2d = np.full((n_cams, n_points, 2), np.nan, dtype='float64')
-
- if progress:
- iterator = trange(n_points, ncols=70)
- else:
- iterator = range(n_points)
-
- for point_ix in iterator:
- best_point = None
- best_error = 200
-
- n_cams_max = len(all_iters[point_ix])
-
- for picked in itertools.product(*all_iters[point_ix].values()):
- picked = [p for p in picked if p is not None]
- if len(picked) < min_cams and len(picked) != n_cams_max:
- continue
-
- cnums = [p[0] for p in picked]
- xnums = [p[1] for p in picked]
-
- pts = points[cnums, point_ix, xnums]
- cc = self.subset_cameras(cnums)
-
- p3d = cc.triangulate(pts, undistort=undistort)
- err = cc.reprojection_error(p3d, pts, mean=True)
-
- if err < best_error:
- best_point = {
- 'error': err,
- 'point': p3d[:3],
- 'points': pts,
- 'picked': picked,
- 'joint_ix': point_ix
- }
- best_error = err
- if best_error < threshold:
- break
-
- if best_point is not None:
- out[point_ix] = best_point['point']
- picked = best_point['picked']
- cnums = [p[0] for p in picked]
- xnums = [p[1] for p in picked]
- picked_vals[cnums, point_ix, xnums] = True
- errors[point_ix] = best_point['error']
- points_2d[cnums, point_ix] = best_point['points']
-
- return out, picked_vals, points_2d, errors
-
- def triangulate_ransac(self, points, undistort=True, min_cams=2, progress=False):
- """Given an CxNx2 array, this returns an Nx3 array of points,
- where N is the number of points and C is the number of cameras"""
-
- assert points.shape[0] == len(self.cameras), \
- "Invalid points shape, first dim should be equal to" \
- " number of cameras ({}), but shape is {}".format(
- len(self.cameras), points.shape
- )
-
- n_cams, n_points, _ = points.shape
-
- points_ransac = points.reshape(n_cams, n_points, 1, 2)
-
- return self.triangulate_possible(points_ransac,
- undistort=undistort,
- min_cams=min_cams,
- progress=progress)
-
- @jit(parallel=True, forceobj=True)
- def reprojection_error(self, p3ds, p2ds, mean=False):
- """Given an Nx3 array of 3D points and an CxNx2 array of 2D points,
- where N is the number of points and C is the number of cameras,
- this returns an CxNx2 array of errors.
- Optionally mean=True, this averages the errors and returns array of length N of errors"""
-
- one_point = False
- if len(p3ds.shape) == 1 and len(p2ds.shape) == 2:
- p3ds = p3ds.reshape(1, 3)
- p2ds = p2ds.reshape(-1, 1, 2)
- one_point = True
-
- n_cams, n_points, _ = p2ds.shape
- assert p3ds.shape == (n_points, 3), \
- "shapes of 2D and 3D points are not consistent: " \
- "2D={}, 3D={}".format(p2ds.shape, p3ds.shape)
-
- errors = np.empty((n_cams, n_points, 2))
-
- for cnum, cam in enumerate(self.cameras):
- errors[cnum] = cam.reprojection_error(p3ds, p2ds[cnum])
-
- if mean:
- errors_norm = np.linalg.norm(errors, axis=2)
- good = ~np.isnan(errors_norm)
- errors_norm[~good] = 0
- denom = np.sum(good, axis=0).astype('float64')
- denom[denom < 1.5] = np.nan
- errors = np.sum(errors_norm, axis=0) / denom
-
- if one_point:
- if mean:
- errors = float(errors[0])
- else:
- errors = errors.reshape(-1, 2)
-
- return errors
-
- def bundle_adjust_iter(self, p2ds, extra=None,
- n_iters=10, start_mu=15, end_mu=1,
- max_nfev=200, ftol=1e-4,
- n_samp_iter=100, n_samp_full=1000,
- error_threshold=0.3,
- verbose=False):
- """Given an CxNx2 array of 2D points,
- where N is the number of points and C is the number of cameras,
- this performs iterative bundle adjustsment to fine-tune the parameters of the cameras.
- That is, it performs bundle adjustment multiple times, adjusting the weights given to points
- to reduce the influence of outliers.
- This is inspired by the algorithm for Fast Global Registration by Zhou, Park, and Koltun
- """
- error_list = []
-
- assert p2ds.shape[0] == len(self.cameras), \
- "Invalid points shape, first dim should be equal to" \
- " number of cameras ({}), but shape is {}".format(
- len(self.cameras), p2ds.shape
- )
-
- p2ds_full = p2ds
- extra_full = extra
-
- p2ds, extra = resample_points(p2ds_full, extra_full,
- n_samp=n_samp_full)
- error = self.average_error(p2ds, median=True)
-
- if verbose:
- print('error: ', error)
-
- mus = np.exp(np.linspace(np.log(start_mu), np.log(end_mu), num=n_iters))
-
- if verbose:
- print('n_samples: {}'.format(n_samp_iter))
-
- for i in range(n_iters):
- p2ds, extra = resample_points(p2ds_full, extra_full,
- n_samp=n_samp_full)
- p3ds = self.triangulate(p2ds)
- errors_full = self.reprojection_error(p3ds, p2ds, mean=False)
- errors_norm = self.reprojection_error(p3ds, p2ds, mean=True)
-
- error_dict = get_error_dict(errors_full)
- max_error = 0
- min_error = 0
- for k, v in error_dict.items():
- num, percents = v
- max_error = max(percents[-1], max_error)
- min_error = max(percents[0], min_error)
- mu = max(min(max_error, mus[i]), min_error)
-
- good = errors_norm < mu
- extra_good = subset_extra(extra, good)
- p2ds_samp, extra_samp = resample_points(
- p2ds[:, good], extra_good, n_samp=n_samp_iter)
-
- error = np.median(errors_norm)
- error_list.append(error)
-
- if error < error_threshold:
- break
-
- if verbose:
- pprint(error_dict)
- print('error: {:.2f}, mu: {:.1f}, ratio: {:.3f}'.format(error, mu, np.mean(good)))
- print(f'previous error scores: {error_list}')
-
- self.bundle_adjust(p2ds_samp, extra_samp,
- loss='linear', ftol=ftol,
- max_nfev=max_nfev,
- verbose=verbose)
-
- p2ds, extra = resample_points(p2ds_full, extra_full,
- n_samp=n_samp_full)
- p3ds = self.triangulate(p2ds)
- errors_full = self.reprojection_error(p3ds, p2ds, mean=False)
- errors_norm = self.reprojection_error(p3ds, p2ds, mean=True)
- error_dict = get_error_dict(errors_full)
- if verbose:
- pprint(error_dict)
-
- max_error = 0
- min_error = 0
- for k, v in error_dict.items():
- num, percents = v
- max_error = max(percents[-1], max_error)
- min_error = max(percents[0], min_error)
- mu = max(max(max_error, end_mu), min_error)
-
- good = errors_norm < mu
- extra_good = subset_extra(extra, good)
- self.bundle_adjust(p2ds[:, good], extra_good,
- loss='linear',
- ftol=ftol, max_nfev=max(200, max_nfev),
- verbose=verbose)
-
- error = self.average_error(p2ds, median=True)
-
- p3ds = self.triangulate(p2ds)
- errors_full = self.reprojection_error(p3ds, p2ds, mean=False)
- error_dict = get_error_dict(errors_full)
- if verbose:
- pprint(error_dict)
-
- if verbose:
- print('error: ', error)
-
- return error
-
- def bundle_adjust(self, p2ds, extra=None,
- loss='linear',
- threshold=50,
- ftol=1e-4,
- max_nfev=1000,
- weights=None,
- start_params=None,
- verbose=True):
- """Given an CxNx2 array of 2D points,
- where N is the number of points and C is the number of cameras,
- this performs bundle adjustsment to fine-tune the parameters of the cameras"""
-
- assert p2ds.shape[0] == len(self.cameras), \
- "Invalid points shape, first dim should be equal to" \
- " number of cameras ({}), but shape is {}".format(
- len(self.cameras), p2ds.shape
- )
-
- if extra is not None:
- extra['ids_map'] = remap_ids(extra['ids'])
-
- x0, n_cam_params = self._initialize_params_bundle(p2ds, extra)
-
- if start_params is not None:
- x0 = start_params
- n_cam_params = len(self.cameras[0].get_params())
-
- error_fun = self._error_fun_bundle
-
- jac_sparse = self._jac_sparsity_bundle(p2ds, n_cam_params, extra)
-
- f_scale = threshold
- opt = optimize.least_squares(error_fun,
- x0,
- jac_sparsity=jac_sparse,
- f_scale=f_scale,
- x_scale='jac',
- loss=loss,
- ftol=ftol,
- method='trf',
- tr_solver='lsmr',
- verbose=2 * verbose,
- max_nfev=max_nfev,
- args=(p2ds, n_cam_params, extra))
- best_params = opt.x
-
- for i, cam in enumerate(self.cameras):
- a = i * n_cam_params
- b = (i + 1) * n_cam_params
- cam.set_params(best_params[a:b])
-
- error = self.average_error(p2ds)
- return error
-
- @jit(parallel=True, forceobj=True)
- def _error_fun_bundle(self, params, p2ds, n_cam_params, extra):
- """Error function for bundle adjustment"""
- good = ~np.isnan(p2ds)
- n_cams = len(self.cameras)
-
- for i in range(n_cams):
- cam = self.cameras[i]
- a = i * n_cam_params
- b = (i + 1) * n_cam_params
- cam.set_params(params[a:b])
-
- n_cams = len(self.cameras)
- sub = n_cam_params * n_cams
- n3d = p2ds.shape[1] * 3
- p3ds_test = params[sub:sub + n3d].reshape(-1, 3)
- errors = self.reprojection_error(p3ds_test, p2ds)
- errors_reproj = errors[good]
-
- if extra is not None:
- ids = extra['ids_map']
- objp = extra['objp']
- min_scale = np.min(objp[objp > 0])
- n_boards = int(np.max(ids)) + 1
- a = sub + n3d
- rvecs = params[a:a + n_boards * 3].reshape(-1, 3)
- tvecs = params[a + n_boards * 3:a + n_boards * 6].reshape(-1, 3)
- expected = transform_points(objp, rvecs[ids], tvecs[ids])
- errors_obj = 2 * (p3ds_test - expected).ravel() / min_scale
- else:
- errors_obj = np.array([])
-
- return np.hstack([errors_reproj, errors_obj])
-
- def _jac_sparsity_bundle(self, p2ds, n_cam_params, extra):
- """Given an CxNx2 array of 2D points,
- where N is the number of points and C is the number of cameras,
- compute the sparsity structure of the jacobian for bundle adjustment"""
-
- point_indices = np.zeros(p2ds.shape, dtype='int32')
- cam_indices = np.zeros(p2ds.shape, dtype='int32')
-
- for i in range(p2ds.shape[1]):
- point_indices[:, i] = i
-
- for j in range(p2ds.shape[0]):
- cam_indices[j] = j
-
- good = ~np.isnan(p2ds)
-
- if extra is not None:
- ids = extra['ids_map']
- n_boards = int(np.max(ids)) + 1
- total_board_params = n_boards * (3 + 3) # rvecs + tvecs
- else:
- n_boards = 0
- total_board_params = 0
-
- n_cams = p2ds.shape[0]
- n_points = p2ds.shape[1]
- total_params_reproj = n_cams * n_cam_params + n_points * 3
- n_params = total_params_reproj + total_board_params
-
- n_good_values = np.sum(good)
- if extra is not None:
- n_errors = n_good_values + n_points * 3
- else:
- n_errors = n_good_values
-
- A_sparse = dok_matrix((n_errors, n_params), dtype='int16')
-
- cam_indices_good = cam_indices[good]
- point_indices_good = point_indices[good]
-
- # -- reprojection error --
- ix = np.arange(n_good_values)
-
- ## update camera params based on point error
- for i in range(n_cam_params):
- A_sparse[ix, cam_indices_good * n_cam_params + i] = 1
-
- ## update point position based on point error
- for i in range(3):
- A_sparse[ix, n_cams * n_cam_params + point_indices_good * 3 + i] = 1
-
- # -- match for the object points--
- if extra is not None:
- point_ix = np.arange(n_points)
-
- ## update all the camera parameters
- # A_sparse[n_good_values:n_good_values+n_points*3,
- # 0:n_cams*n_cam_params] = 1
-
- ## update board rotation and translation based on error from expected
- for i in range(3):
- for j in range(3):
- A_sparse[n_good_values + point_ix * 3 + i,
- total_params_reproj + ids * 3 + j] = 1
- A_sparse[n_good_values + point_ix * 3 + i,
- total_params_reproj + n_boards * 3 + ids * 3 + j] = 1
-
- ## update point position based on error from expected
- for i in range(3):
- A_sparse[n_good_values + point_ix * 3 + i,
- n_cams * n_cam_params + point_ix * 3 + i] = 1
-
- return A_sparse
-
- def _initialize_params_bundle(self, p2ds, extra):
- """Given an CxNx2 array of 2D points,
- where N is the number of points and C is the number of cameras,
- initializes the parameters for bundle adjustment"""
-
- cam_params = np.hstack([cam.get_params() for cam in self.cameras])
- n_cam_params = len(cam_params) // len(self.cameras)
-
- total_cam_params = len(cam_params)
-
- n_cams, n_points, _ = p2ds.shape
- assert n_cams == len(self.cameras), \
- "number of cameras in CameraGroup does not " \
- "match number of cameras in 2D points given"
-
- p3ds = self.triangulate(p2ds)
-
- if extra is not None:
- ids = extra['ids_map']
- n_boards = int(np.max(ids[~np.isnan(ids)])) + 1
- total_board_params = n_boards * (3 + 3) # rvecs + tvecs
-
- # initialize to 0
- rvecs = np.zeros((n_boards, 3), dtype='float64')
- tvecs = np.zeros((n_boards, 3), dtype='float64')
-
- if 'rvecs' in extra and 'tvecs' in extra:
- rvecs_all = extra['rvecs']
- tvecs_all = extra['tvecs']
- for board_num in range(n_boards):
- point_id = np.where(ids == board_num)[0][0]
- cam_ids_possible = np.where(~np.isnan(p2ds[:, point_id, 0]))[0]
- cam_id = np.random.choice(cam_ids_possible)
- M_cam = self.cameras[cam_id].get_extrinsics_mat()
- M_board_cam = make_M(rvecs_all[cam_id, point_id],
- tvecs_all[cam_id, point_id])
- M_board = np.matmul(np.linalg.inv(M_cam), M_board_cam)
- rvec, tvec = get_rtvec(M_board)
- rvecs[board_num] = rvec
- tvecs[board_num] = tvec
-
-
- else:
- total_board_params = 0
-
- x0 = np.zeros(total_cam_params + p3ds.size + total_board_params)
- x0[:total_cam_params] = cam_params
- x0[total_cam_params:total_cam_params + p3ds.size] = p3ds.ravel()
-
- if extra is not None:
- start_board = total_cam_params + p3ds.size
- x0[start_board:start_board + n_boards * 3] = rvecs.ravel()
- x0[start_board + n_boards * 3:start_board + n_boards * 6] = \
- tvecs.ravel()
-
- return x0, n_cam_params
-
- def optim_points(self, points, p3ds,
- constraints=[],
- constraints_weak=[],
- scale_smooth=4,
- scale_length=2, scale_length_weak=0.5,
- reproj_error_threshold=15, reproj_loss='soft_l1',
- n_deriv_smooth=1, scores=None, verbose=False):
- """
- Take in an array of 2D points of shape CxNxJx2,
- an array of 3D points of shape NxJx3,
- and an array of constraints of shape Kx2, where
- C: number of camera
- N: number of frames
- J: number of joints
- K: number of constraints
-
- This function creates an optimized array of 3D points of shape NxJx3.
-
- Example constraints:
- constraints = [[0, 1], [1, 2], [2, 3]]
- (meaning that lengths of segments 0->1, 1->2, 2->3 are all constant)
-
- """
- assert points.shape[0] == len(self.cameras), \
- "Invalid points shape, first dim should be equal to" \
- " number of cameras ({}), but shape is {}".format(
- len(self.cameras), points.shape
- )
-
- n_cams, n_frames, n_joints, _ = points.shape
- constraints = np.array(constraints)
- constraints_weak = np.array(constraints_weak)
-
- p3ds_intp = np.apply_along_axis(interpolate_data, 0, p3ds)
-
- p3ds_med = np.apply_along_axis(medfilt_data, 0, p3ds_intp, size=7)
-
- default_smooth = 1.0 / np.mean(np.abs(np.diff(p3ds_med, axis=0)))
- scale_smooth_full = scale_smooth * default_smooth
-
- t1 = time.time()
-
- x0 = self._initialize_params_triangulation(
- p3ds_intp, constraints, constraints_weak)
-
- x0[~np.isfinite(x0)] = 0
-
- jac = self._jac_sparsity_triangulation(
- points, constraints, constraints_weak, n_deriv_smooth)
-
- opt2 = optimize.least_squares(self._error_fun_triangulation,
- x0=x0, jac_sparsity=jac,
- loss='linear',
- ftol=1e-3,
- verbose=2 * verbose,
- args=(points,
- constraints,
- constraints_weak,
- scores,
- scale_smooth_full,
- scale_length,
- scale_length_weak,
- reproj_error_threshold,
- reproj_loss,
- n_deriv_smooth))
-
- p3ds_new2 = opt2.x[:p3ds.size].reshape(p3ds.shape)
-
- t2 = time.time()
-
- if verbose:
- print('optimization took {:.2f} seconds'.format(t2 - t1))
-
- return p3ds_new2
-
- def optim_points_possible(self, points, p3ds,
- constraints=[],
- constraints_weak=[],
- scale_smooth=4,
- scale_length=2, scale_length_weak=0.5,
- reproj_error_threshold=15, reproj_loss='soft_l1',
- n_deriv_smooth=1, scores=None, verbose=False):
- """
- Take in an array of 2D points of shape CxNxJxPx2,
- an array of 3D points of shape NxJx3,
- and an array of constraints of shape Kx2, where
- C: number of camera
- N: number of frames
- J: number of joints
- P: number of possible options per point
- K: number of constraints
-
- This function creates an optimized array of 3D points of shape NxJx3.
-
- Example constraints:
- constraints = [[0, 1], [1, 2], [2, 3]]
- (meaning that lengths of segments 0->1, 1->2, 2->3 are all constant)
-
- """
- assert points.shape[0] == len(self.cameras), \
- "Invalid points shape, first dim should be equal to" \
- " number of cameras ({}), but shape is {}".format(
- len(self.cameras), points.shape
- )
-
- n_cams, n_frames, n_joints, n_possible, _ = points.shape
- constraints = np.array(constraints)
- constraints_weak = np.array(constraints_weak)
-
- p3ds_intp = np.apply_along_axis(interpolate_data, 0, p3ds)
-
- p3ds_med = np.apply_along_axis(medfilt_data, 0, p3ds_intp, size=7)
-
- default_smooth = 1.0 / np.mean(np.abs(np.diff(p3ds_med, axis=0)))
- scale_smooth_full = scale_smooth * default_smooth
-
- t1 = time.time()
-
- x0 = self._initialize_params_triangulation_possible(
- p3ds_intp, points, constraints=constraints, constraints_weak=constraints_weak)
-
- print('getting jacobian...')
- jac = self._jac_sparsity_triangulation_possible(
- points,
- constraints=constraints,
- constraints_weak=constraints_weak,
- n_deriv_smooth=n_deriv_smooth)
-
- beta = 5
-
- print('starting optimization...')
- opt2 = optimize.least_squares(self._error_fun_triangulation_possible,
- x0=x0, jac_sparsity=jac,
- loss='linear',
- ftol=1e-3,
- verbose=2 * verbose,
- args=(points,
- beta,
- constraints,
- constraints_weak,
- scores,
- scale_smooth_full,
- scale_length,
- scale_length_weak,
- reproj_error_threshold,
- reproj_loss,
- n_deriv_smooth))
- params = opt2.x
-
- p3ds_new2 = params[:p3ds.size].reshape(p3ds.shape)
-
- bad = np.isnan(points[:, :, :, :, 0])
- all_bad = np.all(bad, axis=3)
-
- n_params_norm = p3ds.size + len(constraints) + len(constraints_weak)
-
- alphas = np.zeros((n_cams, n_frames, n_joints, n_possible), dtype='float64')
- alphas[~bad] = params[n_params_norm:]
-
- alphas_exp = np.exp(beta * alphas)
- alphas_exp[bad] = 0
- alphas_sum = np.sum(alphas_exp, axis=3)
- alphas_sum[all_bad] = 1
- alphas_norm = alphas_exp / alphas_sum[:, :, :, None]
- alphas_norm[bad] = np.nan
-
- t2 = time.time()
-
- if verbose:
- print('optimization took {:.2f} seconds'.format(t2 - t1))
-
- return p3ds_new2, alphas_norm
-
- def triangulate_optim(self, points, init_ransac=False, init_progress=False,
- **kwargs):
- """
- Take in an array of 2D points of shape CxNxJx2, and an array of constraints of shape Kx2, where
- C: number of camera
- N: number of frames
- J: number of joints
- K: number of constraints
-
- This function creates an optimized array of 3D points of shape NxJx3.
-
- Example constraints:
- constraints = [[0, 1], [1, 2], [2, 3]]
- (meaning that lengths of segments 0->1, 1->2, 2->3 are all constant)
-
- """
-
- assert points.shape[0] == len(self.cameras), \
- "Invalid points shape, first dim should be equal to" \
- " number of cameras ({}), but shape is {}".format(
- len(self.cameras), points.shape
- )
-
- n_cams, n_frames, n_joints, _ = points.shape
- # constraints = np.array(constraints)
- # constraints_weak = np.array(constraints_weak)
-
- points_shaped = points.reshape(n_cams, n_frames * n_joints, 2)
- if init_ransac:
- p3ds, picked, p2ds, errors = self.triangulate_ransac(points_shaped, progress=init_progress)
- points = p2ds.reshape(points.shape)
- else:
- p3ds = self.triangulate(points_shaped, progress=init_progress)
- p3ds = p3ds.reshape((n_frames, n_joints, 3))
-
- c = np.isfinite(p3ds[:, :, 0])
- if np.sum(c) < 20:
- print("warning: not enough 3D points to run optimization")
- return p3ds
-
- return self.optim_points(points, p3ds, **kwargs)
-
- @jit(forceobj=True, parallel=True)
- def _error_fun_triangulation(self, params, p2ds,
- constraints=[],
- constraints_weak=[],
- scores=None,
- scale_smooth=10000,
- scale_length=1,
- scale_length_weak=0.2,
- reproj_error_threshold=100,
- reproj_loss='soft_l1',
- n_deriv_smooth=1):
- n_cams, n_frames, n_joints, _ = p2ds.shape
-
- n_3d = n_frames * n_joints * 3
- n_constraints = len(constraints)
- n_constraints_weak = len(constraints_weak)
-
- # load params
- p3ds = params[:n_3d].reshape((n_frames, n_joints, 3))
- joint_lengths = np.array(params[n_3d:n_3d + n_constraints])
- joint_lengths_weak = np.array(params[n_3d + n_constraints:])
-
- # reprojection errors
- p3ds_flat = p3ds.reshape(-1, 3)
- p2ds_flat = p2ds.reshape((n_cams, -1, 2))
- errors = self.reprojection_error(p3ds_flat, p2ds_flat)
- if scores is not None:
- scores_flat = scores.reshape((n_cams, -1))
- errors = errors * scores_flat[:, :, None]
- errors_reproj = errors[~np.isnan(p2ds_flat)]
-
- rp = reproj_error_threshold
- errors_reproj = np.abs(errors_reproj)
- if reproj_loss == 'huber':
- bad = errors_reproj > rp
- errors_reproj[bad] = rp * (2 * np.sqrt(errors_reproj[bad] / rp) - 1)
- elif reproj_loss == 'linear':
- pass
- elif reproj_loss == 'soft_l1':
- errors_reproj = rp * 2 * (np.sqrt(1 + errors_reproj / rp) - 1)
-
- # temporal constraint
- errors_smooth = np.diff(p3ds, n=n_deriv_smooth, axis=0).ravel() * scale_smooth
-
- # joint length constraint
- errors_lengths = np.empty((n_constraints, n_frames), dtype='float64')
- for cix, (a, b) in enumerate(constraints):
- lengths = np.linalg.norm(p3ds[:, a] - p3ds[:, b], axis=1)
- expected = joint_lengths[cix]
- errors_lengths[cix] = 100 * (lengths - expected) / expected
- errors_lengths = errors_lengths.ravel() * scale_l0ength
-
- errors_lengths_weak = np.empty((n_constraints_weak, n_frames), dtype='float64')
- for cix, (a, b) in enumerate(constraints_weak):
- lengths = np.linalg.norm(p3ds[:, a] - p3ds[:, b], axis=1)
- expected = joint_lengths_weak[cix]
- errors_lengths_weak[cix] = 100 * (lengths - expected) / expected
- errors_lengths_weak = errors_lengths_weak.ravel() * scale_length_weak
-
- return np.hstack([errors_reproj, errors_smooth,
- errors_lengths, errors_lengths_weak])
-
- def _error_fun_triangulation_possible(self, params, p2ds,
- beta=2,
- constraints=[],
- constraints_weak=[],
- *args):
- # extract alphas from end of params
- # soft argmax for picking the appropriate points from p2ds
- # pass the points to error_fun_triangulate_possible for residuals
- # add errors to keep the alphas in check
- # return all the errors
-
- n_cams, n_frames, n_joints, n_possible, _ = p2ds.shape
-
- n_3d = n_frames * n_joints * 3
- n_constraints = len(constraints)
- n_constraints_weak = len(constraints_weak)
- n_params_norm = n_3d + n_constraints + n_constraints_weak
-
- # load params
- bad = np.isnan(p2ds[:, :, :, :, 0])
- all_bad = np.all(bad, axis=3)
-
- alphas = np.zeros((n_cams, n_frames, n_joints, n_possible), dtype='float64')
- alphas[~bad] = params[n_params_norm:]
- params_rest = np.array(params[:n_params_norm])
-
- # get normalized alphas
- alphas_exp = np.exp(beta * alphas)
- alphas_exp[bad] = 0
- alphas_sum = np.sum(alphas_exp, axis=3)
- alphas_sum[all_bad] = 1
- alphas_norm = alphas_exp / alphas_sum[:, :, :, None]
-
- # extract the 2D points using soft argmax
- p2ds_test = np.copy(p2ds)
- p2ds_test[bad] = 0
- p2ds_adj = np.sum(alphas_norm[:, :, :, :, None] * p2ds_test, axis=3)
- p2ds_adj[all_bad] = np.nan
-
- errors = self._error_fun_triangulation(params_rest, p2ds_adj,
- constraints, constraints_weak, *args)
-
- alphas_test = alphas_norm[~all_bad]
- errors_alphas = (1 - np.std(alphas_test, axis=1)) * 10
-
- return np.hstack([errors, errors_alphas])
-
- def _initialize_params_triangulation(self, p3ds,
- constraints=[],
- constraints_weak=[]):
- joint_lengths = np.empty(len(constraints), dtype='float64')
- joint_lengths_weak = np.empty(len(constraints_weak), dtype='float64')
-
- for cix, (a, b) in enumerate(constraints):
- lengths = np.linalg.norm(p3ds[:, a] - p3ds[:, b], axis=1)
- joint_lengths[cix] = np.median(lengths)
-
- for cix, (a, b) in enumerate(constraints_weak):
- lengths = np.linalg.norm(p3ds[:, a] - p3ds[:, b], axis=1)
- joint_lengths_weak[cix] = np.median(lengths)
-
- all_lengths = np.hstack([joint_lengths, joint_lengths_weak])
- med = np.median(all_lengths)
- if med == 0:
- med = 1e-3
-
- mad = np.median(np.abs(all_lengths - med))
-
- joint_lengths[joint_lengths == 0] = med
- joint_lengths_weak[joint_lengths_weak == 0] = med
- joint_lengths[joint_lengths > med + mad * 5] = med
- joint_lengths_weak[joint_lengths_weak > med + mad * 5] = med
-
- return np.hstack([p3ds.ravel(), joint_lengths, joint_lengths_weak])
-
- def _initialize_params_triangulation_possible(self, p3ds, p2ds, **kwargs):
- # initialize params using above function
- # initialize alphas to 1 for first one and 0 for other possible
-
- n_cams, n_frames, n_joints, n_possible, _ = p2ds.shape
- good = ~np.isnan(p2ds[:, :, :, :, 0])
-
- alphas = np.zeros((n_cams, n_frames, n_joints, n_possible), dtype='float64')
- alphas[:, :, :, 0] = 0
-
- params = self._initialize_params_triangulation(p3ds, **kwargs)
- params_full = np.hstack([params, alphas[good]])
-
- return params_full
-
- def _jac_sparsity_triangulation(self, p2ds,
- constraints=[],
- constraints_weak=[],
- n_deriv_smooth=1):
- n_cams, n_frames, n_joints, _ = p2ds.shape
- n_constraints = len(constraints)
- n_constraints_weak = len(constraints_weak)
-
- p2ds_flat = p2ds.reshape((n_cams, -1, 2))
-
- point_indices = np.zeros(p2ds_flat.shape, dtype='int32')
- for i in range(p2ds_flat.shape[1]):
- point_indices[:, i] = i
-
- point_indices_3d = np.arange(n_frames * n_joints) \
- .reshape((n_frames, n_joints))
-
- good = ~np.isnan(p2ds_flat)
- n_errors_reproj = np.sum(good)
- n_errors_smooth = (n_frames - n_deriv_smooth) * n_joints * 3
- n_errors_lengths = n_constraints * n_frames
- n_errors_lengths_weak = n_constraints_weak * n_frames
-
- n_errors = n_errors_reproj + n_errors_smooth + \
- n_errors_lengths + n_errors_lengths_weak
-
- n_3d = n_frames * n_joints * 3
- n_params = n_3d + n_constraints + n_constraints_weak
-
- point_indices_good = point_indices[good]
-
- A_sparse = dok_matrix((n_errors, n_params), dtype='int16')
-
- # constraints for reprojection errors
- ix_reproj = np.arange(n_errors_reproj)
- for k in range(3):
- A_sparse[ix_reproj, point_indices_good * 3 + k] = 1
-
- # sparse constraints for smoothness in time
- frames = np.arange(n_frames - n_deriv_smooth)
- for j in range(n_joints):
- for n in range(n_deriv_smooth + 1):
- pa = point_indices_3d[frames, j]
- pb = point_indices_3d[frames + n, j]
- for k in range(3):
- A_sparse[n_errors_reproj + pa * 3 + k, pb * 3 + k] = 1
-
- ## -- strong constraints --
- # joint lengths should change with joint lengths errors
- start = n_errors_reproj + n_errors_smooth
- frames = np.arange(n_frames)
- for cix, (a, b) in enumerate(constraints):
- A_sparse[start + cix * n_frames + frames, n_3d + cix] = 1
-
- # points should change accordingly to match joint lengths too
- frames = np.arange(n_frames)
- for cix, (a, b) in enumerate(constraints):
- pa = point_indices_3d[frames, a]
- pb = point_indices_3d[frames, b]
- for k in range(3):
- A_sparse[start + cix * n_frames + frames, pa * 3 + k] = 1
- A_sparse[start + cix * n_frames + frames, pb * 3 + k] = 1
-
- ## -- weak constraints --
- # joint lengths should change with joint lengths errors
- start = n_errors_reproj + n_errors_smooth + n_errors_lengths
- frames = np.arange(n_frames)
- for cix, (a, b) in enumerate(constraints_weak):
- A_sparse[start + cix * n_frames + frames, n_3d + n_constraints + cix] = 1
-
- # points should change accordingly to match joint lengths too
- frames = np.arange(n_frames)
- for cix, (a, b) in enumerate(constraints_weak):
- pa = point_indices_3d[frames, a]
- pb = point_indices_3d[frames, b]
- for k in range(3):
- A_sparse[start + cix * n_frames + frames, pa * 3 + k] = 1
- A_sparse[start + cix * n_frames + frames, pb * 3 + k] = 1
-
- return A_sparse
-
- def _jac_sparsity_triangulation_possible(self, p2ds_full, **kwargs):
- # initialize sparse jacobian using above function
- # extend to include alphas from parameters
- ## TODO: this initialization is really slow for some reason
-
- n_cams, n_frames, n_joints, n_possible, _ = p2ds_full.shape
- good_full = ~np.isnan(p2ds_full[:, :, :, :, 0])
- any_good = np.any(good_full, axis=3)
-
- n_alphas = np.sum(good_full)
- n_errors_alphas = np.sum(any_good)
-
- p2ds = p2ds_full[:, :, :, 0]
- A_sparse = self._jac_sparsity_triangulation(p2ds, **kwargs)
-
- n_errors, n_params = A_sparse.shape
-
- B_sparse = dok_matrix((n_errors + n_errors_alphas, n_params + n_alphas), dtype='int16')
- for r, c in zip(*A_sparse.nonzero()):
- B_sparse[r, c] = A_sparse[r, c]
-
- point_indices_2d = np.arange(n_cams * n_frames * n_joints) \
- .reshape(n_cams, n_frames, n_joints)
- point_indices_2d_rep = np.repeat(point_indices_2d[:, :, :, None], 2, axis=3)
- point_indices_2d_good = point_indices_2d_rep[~np.isnan(p2ds)]
- point_indices_good = point_indices_2d[any_good]
-
- alpha_indices = np.zeros((n_cams, n_frames, n_joints, n_possible), dtype='int64')
- for pnum in range(n_possible):
- alpha_indices[:, :, :, pnum] = point_indices_2d
-
- alpha_indices_good = alpha_indices[good_full]
-
- # alphas should change according to the reprojection error for each corresponding point
- point_indices_2d_good_find = defaultdict(list)
- for ix, p in enumerate(point_indices_2d_good):
- point_indices_2d_good_find[p].append(ix)
-
- for ix, alpha_index in enumerate(alpha_indices_good):
- B_sparse[point_indices_2d_good_find[alpha_index],
- n_params + ix] = 1
-
- # alphas should change according to the alpha errors
- point_indices_good_find = dict()
- for ix, p in enumerate(point_indices_good):
- point_indices_good_find[p] = ix
-
- for ix, alpha_index in enumerate(alpha_indices_good):
- if alpha_index in point_indices_good_find:
- err_ix = n_errors + point_indices_good_find[alpha_index]
- B_sparse[err_ix, n_params + ix] = 1
-
- return B_sparse
-
- def copy(self):
- cameras = [cam.copy() for cam in self.cameras]
- metadata = copy(self.metadata)
- return CameraGroup(cameras, metadata)
-
- def set_rotations(self, rvecs):
- for cam, rvec in zip(self.cameras, rvecs):
- cam.set_rotation(rvec)
-
- def set_translations(self, tvecs):
- for cam, tvec in zip(self.cameras, tvecs):
- cam.set_translation(tvec)
-
- def get_rotations(self):
- rvecs = []
- for cam in self.cameras:
- rvec = cam.get_rotation()
- rvecs.append(rvec)
- return np.array(rvecs)
-
- def get_translations(self):
- tvecs = []
- for cam in self.cameras:
- tvec = cam.get_translation()
- tvecs.append(tvec)
- return np.array(tvecs)
-
- def get_names(self):
- return [cam.get_name() for cam in self.cameras]
-
- def set_names(self, names):
- for cam, name in zip(self.cameras, names):
- cam.set_name(name)
-
- def average_error(self, p2ds, median=False):
- p3ds = self.triangulate(p2ds)
- errors = self.reprojection_error(p3ds, p2ds, mean=True)
- if median:
- return np.median(errors)
- else:
- return np.mean(errors)
-
- def calibrate_rows(self, all_rows, board,
- init_intrinsics=True, init_extrinsics=True, verbose=True,
- **kwargs):
- assert len(all_rows) == len(self.cameras), \
- "Number of camera detections does not match number of cameras"
-
- for rows, camera in zip(all_rows, self.cameras):
- size = camera.get_size()
-
- assert size is not None, \
- "Camera with name {} has no specified frame size".format(camera.get_name())
-
- if init_intrinsics:
- objp, imgp = board.get_all_calibration_points(rows)
- mixed = [(o, i) for (o, i) in zip(objp, imgp) if len(o) >= 7]
- assert len(objp) != 0 and len(imgp) != 0, "No Charuco board points detected"
- objp, imgp = zip(*mixed)
- matrix = cv2.initCameraMatrix2D(objp, imgp, tuple(size))
- camera.set_camera_matrix(matrix)
-
- for i, (row, cam) in enumerate(zip(all_rows, self.cameras)):
- all_rows[i] = board.estimate_pose_rows(cam, row)
-
- charuco_frames = [f['framenum'][1] for f in all_rows[0]]
- merged = merge_rows(all_rows)
- imgp, extra = extract_points(merged, board, min_cameras=2)
-
- if init_extrinsics:
- rtvecs = extract_rtvecs(merged)
- if verbose:
- pprint(get_connections(rtvecs, self.get_names()))
- rvecs, tvecs = get_initial_extrinsics(rtvecs)
- self.set_rotations(rvecs)
- self.set_translations(tvecs)
-
- error = self.bundle_adjust_iter(imgp, extra, verbose=verbose, error_threshold=1)
-
- return error, merged, charuco_frames
-
- def get_rows_videos(self, videos, board, verbose=True):
- all_rows = []
-
- for cix, (cam, cam_videos) in enumerate(zip(self.cameras, videos)):
- rows_cam = []
- for vnum, vidname in enumerate(cam_videos):
- if verbose: print(vidname)
- rows = board.detect_video(vidname, prefix=vnum, progress=verbose)
- if verbose: print("{} boards detected".format(len(rows)))
- rows_cam.extend(rows)
- all_rows.append(rows_cam)
-
- return all_rows
-
- def set_camera_sizes_videos(self, videos):
- for cix, (cam, cam_videos) in enumerate(zip(self.cameras, videos)):
- rows_cam = []
- for vnum, vidname in enumerate(cam_videos):
- params = get_video_params(vidname)
- size = (params['width'], params['height'])
- cam.set_size(size)
-
- def calibrate_videos(self, videos, board,
- init_intrinsics=True, init_extrinsics=True, verbose=True,
- **kwargs):
- """Takes as input a list of list of video filenames, one list of each camera.
- Also takes a board which specifies what should be detected in the videos"""
-
- all_rows = self.get_rows_videos(videos, board, verbose=verbose)
- if init_extrinsics:
- self.set_camera_sizes_videos(videos)
-
- error, merged, charuco_frames = self.calibrate_rows(all_rows, board,
- init_intrinsics=init_intrinsics,
- init_extrinsics=init_extrinsics,
- verbose=verbose, **kwargs)
- return error, merged, charuco_frames
-
- def get_dicts(self):
- out = []
- for cam in self.cameras:
- out.append(cam.get_dict())
- return out
-
- def from_dicts(arr):
- cameras = []
- for d in arr:
- if 'fisheye' in d and d['fisheye']:
- cam = FisheyeCamera.from_dict(d)
- else:
- cam = Camera.from_dict(d)
- cameras.append(cam)
- return CameraGroup(cameras)
-
- def from_names(self, names, fisheye=False):
- cameras = []
- for name in names:
- if fisheye:
- cam = FisheyeCamera(name=name)
- else:
- cam = Camera(name=name)
- cameras.append(cam)
- return CameraGroup(cameras)
-
- def load_dicts(self, arr):
- for cam, d in zip(self.cameras, arr):
- cam.load_dict(d)
-
- def dump(self, fname):
- dicts = self.get_dicts()
- names = ['cam_{}'.format(i) for i in range(len(dicts))]
- master_dict = dict(zip(names, dicts))
- master_dict['metadata'] = self.metadata
- with open(fname, 'w') as f:
- toml.dump(master_dict, f)
-
- def load(fname):
- master_dict = toml.load(fname)
- keys = sorted(master_dict.keys())
- items = [master_dict[k] for k in keys if k != 'metadata']
- cgroup = CameraGroup.from_dicts(items)
- if 'metadata' in master_dict:
- cgroup.metadata = master_dict['metadata']
- return cgroup
-
- def resize_cameras(self, scale):
- for cam in self.cameras:
- cam.resize_camera(scale)
diff --git a/freemocap/fmc_blender.py b/freemocap/fmc_blender.py
deleted file mode 100644
index af9fe522..00000000
--- a/freemocap/fmc_blender.py
+++ /dev/null
@@ -1,836 +0,0 @@
-import numpy as np
-import bpy
-from mathutils import Vector
-import math
-import sys
-from pathlib import Path
-import csv
-from math import degrees
-
-
-# get arguments
-argv = sys.argv
-argv = argv[argv.index("--") + 1:]
-
-# get npy session data
-input_frames_data_npy = argv[0]
-
-# get session path
-sesh_path = argv[1]
-
-#get session ID
-sesh_ID = argv[2]
-
-# A clean array of skeleton data where every marker was tracked that we can build off of
-clean_skeleton_position_arr = Path(__file__).parent.resolve() / "build_data.npy"
-
-#3D array holding [[[x, y, z], [x, y, z]], [[x, y, z], [x, y, z]]]
-mediapipe_frames_arr = np.load(input_frames_data_npy)
-
-# Saved clean frame where all points are visible and not NANs
-markers_list = np.load(clean_skeleton_position_arr)
-#a list containing empty objects
-order_of_markers = []
-
-#frame rate
-bpy.context.scene.render.fps = 30
-
-#dictionary corresponding to marker numbers and body parts
-mediapipe_tracked_point_names = {
- 0:"nose",
- 1:"left_eye_inner",
- 2:"left_eye",
- 3:"left_eye_outer",
- 4:"right_eye_inner",
- 5:"right_eye",
- 6:"right_eye_outer",
- 7:"left_ear",
- 8:"right_ear",
- 9:"mouth_left",
- 10:"mouth_right",
- 11:"shoulder_L",
- 12:"shoulder_R",
- 13:"elbow_L",
- 14:"elbow_R",
- 23:"hip_L",
- 24:"hip_R",
- 25:"knee_L",
- 26:"knee_R",
- 27:"ankle_L",
- 28:"ankle_R",
- 29:"heel_L",
- 30:"heel_R",
- 31:"toe_L",
- 32:"toe_R" }
-
-#-----------------------------------------------------------------------------------
-
-# set project unit
-bpy.context.scene.unit_settings.length_unit = 'METERS'
-
-#create sub-collection of empties
-cname = "mediapipe_empty_objects"
-empty_collection = bpy.data.collections.new(cname)
-bpy.data.collections.get("Collection").children.link(empty_collection)
-master_collection = bpy.data.collections.get("Collection")
-
-
-#iterate through arr and create an empty object at that location for each element
-for index, col in enumerate(markers_list):
- # parse string float value into floats, create Vector, set position to Vector
-
- if math.isnan(col[0]):
- col[0] = np.nan
- if math.isnan(col[1]):
- col[1] = np.nan
- if math.isnan(col[2]):
- col[2] = np.nan
- coord = Vector(((float(col[0])*0.001), (float(col[1])*0.001), (float(col[2]))* 0.001))
-
-
- #empties
- bpy.ops.object.add(type='EMPTY', location=coord)
- this_empty = bpy.context.active_object
- this_empty.name = "empty_" + str(index)
-
- if index in mediapipe_tracked_point_names.keys():
- this_empty.name += "_" + str(mediapipe_tracked_point_names[index])
- else:
- if index > 32 and index < 54:
- this_empty.name += "_" + str("right_hand")
- elif index >= 54 and index < 76:
- this_empty.name += "_" + str("left_hand")
- else:
- this_empty.name += "_" + str("face")
-
- order_of_markers.append(this_empty)
-
- #link this empty to the scene's Empty collection
- empty_collection.objects.link( this_empty )
- #unlink empty from master collection
- master_collection.objects.unlink(this_empty)
- #set location
- this_empty.location = coord
- #set the display size of the empty
- this_empty.empty_display_size = 0.02
-
-#--------------------------------------------------------------
-#Virtual Markers!
-
-# marker relationships:
-
-# - "weight": the weighted average of multiple markers. the virtual_markers[x] contains the
-#list of markers that affect this virtual one. the weights[x] contains their corresponding weights in order.
-
-bpy.ops.object.mode_set(mode='OBJECT', toggle=False)
-
-#Create virtual marker where parameters are the name of the marker, the markers that affect its position, and each of their weights.
-def create_marker_weight(name, markers, weighted):
- center = Vector((0, 0, 0))
- weight_iter = 0
- for x in markers:
- center += x.location*weighted[weight_iter]
- weight_iter += 1
- coord = Vector((float(center[0]), float(center[1]), float(center[2])))
- bpy.ops.object.add(type='EMPTY', location=coord)
- this_empty = bpy.context.active_object
- this_empty.name = name
- #link this empty to the scene's Empty collection
- empty_collection.objects.link( this_empty )
- #unlink empty from master collection
- master_collection.objects.unlink(this_empty)
- this_empty.location = coord
- this_empty.empty_display_size = 0.02
- virtual_markers.append(this_empty)
-
-#Keeping track of virtual marker info using arrays, where each marker is an index in each array
-v_relationship = []
-virtual_markers = []
-surrounding_markers = []
-weights = []
-
-#updates data and creates virtual marker
-def update_virtual_data(relationship, surrounding, vweights, vname):
- v_relationship.append(relationship)
- surrounding_markers.append(surrounding)
- weights.append(vweights)
- create_marker_weight(vname, surrounding, vweights)
-
-#-----------------------------------------------------------------
-#Define relationships and create virtual markers
-
-#Neck Base: Halfway between order_of_markers[12] shoulder_L and order_of_markers[12] shoulder_R
-l0 = [order_of_markers[12], order_of_markers[11]]
-w0 = [0.5, 0.5]
-update_virtual_data("weight", l0, w0, "empty_neck")
-
-#Waist Base: Halfway between order_of_markers[24] and order_of_markers[23]
-l0 = [order_of_markers[24], order_of_markers[23]]
-w0 = [0.5, 0.5]
-update_virtual_data("weight", l0, w0, "empty_waist")
-
-#Update the location of virtual markers on each frame
-def update_virtual_marker(index):
- if(v_relationship[index] == "weight"):
- center = Vector((0, 0, 0))
- weight_iter = 0
- for x in surrounding_markers[index]:
- center += x.location*weights[index][weight_iter]
- weight_iter += 1
- coord = Vector((float(center[0]), float(center[1]), float(center[2])))
- virtual_markers[index].location = coord
-
-#-----------------------------------------------------------------------------------
-# Bones!
-
-#adds child bone given corresponding parent and empty
-#bone tail will appear at the location of empty
-def add_child_bone(bone_name, empty_child, empty_parent):
- #Set armature selected
- armature_data.select_set(state=True)
- #Set edit mode
- bpy.ops.object.mode_set(mode='EDIT', toggle=False)
- #Create a new bone
- new_bone = armature_data.data.edit_bones.new(bone_name)
- #Set bone's size
-
- new_bone.head = (np.nan,np.nan,np.nan)
- new_bone.tail = (np.nan,np.nan,np.nan)
- #Set bone's location to wheel
- new_bone.matrix = empty_parent.matrix_world
-
- #set location of bone head
- new_bone.head = empty_child.location
- #set location of bone tail
- new_bone.tail = empty_parent.location
- return new_bone
-
-#Create armature object
-armature = bpy.data.armatures.new('Armature')
-armature.name = "Armature_MediaPipe"
-armature_object = bpy.data.objects.new('Armature', armature)
-#set name of armature to specify data type (media pipe)
-armature_object.name = "Armature_MediaPipe_Object"
-#Link armature object to our scene
-bpy.context.collection.objects.link(armature_object)
-#Make armature variable
-armature_data = bpy.data.objects[armature_object.name]
-#Set armature active
-bpy.context.view_layer.objects.active = armature_data
-#Set armature selected
-armature_data.select_set(state=True)
-#Set edit mode
-bpy.ops.object.mode_set(mode='EDIT', toggle=False)
-#Set bones in front and show axis
-armature_data.show_in_front = True
-#True to show axis orientation of bones and false to hide it
-armature_data.data.show_axes = False
-
-#get armature object
-def get_armature():
- for ob in bpy.data.objects:
- if ob.name == 'Armature_MediaPipe_Object':
- armature = ob
- break
- return armature
-
-armature = get_armature()
-
-#a list of tuples where each element represents the info for one bone, and
-#the tuple contains the bone name, the marker of the head, and the marker of the tail
-list_of_bones_order = [('upper_arm_L', order_of_markers[11], order_of_markers[13]),
- ('upper_arm_R', order_of_markers[12], order_of_markers[14]),
- ('lower_arm_L', order_of_markers[13], order_of_markers[15]),
- ('lower_arm_R', order_of_markers[14], order_of_markers[16]),
- ('upper_leg_L', order_of_markers[23], order_of_markers[25]),
- ('upper_leg_R', order_of_markers[24], order_of_markers[26]),
- ('lower_leg_L', order_of_markers[25], order_of_markers[27]),
- ('lower_leg_R', order_of_markers[26], order_of_markers[28]),
- ('heel_L', order_of_markers[27], order_of_markers[29]),
- ('heel_R', order_of_markers[28], order_of_markers[30]),
- ('foot_L', order_of_markers[29], order_of_markers[31]),
- ('foot_R', order_of_markers[30], order_of_markers[32]),
- ('neck', order_of_markers[0], virtual_markers[0]),
- ('eye_L', order_of_markers[0], order_of_markers[2]),
- ('ear_L', order_of_markers[2], order_of_markers[7]),
- ('eye_R', order_of_markers[0], order_of_markers[5]),
- ('ear_R', order_of_markers[5], order_of_markers[8]),
- ('shoulder_L', virtual_markers[0], order_of_markers[11]),
- ('shoulder_R', virtual_markers[0], order_of_markers[12]),
- ('root', virtual_markers[1], virtual_markers[0]),
- ('hip_L', virtual_markers[1], order_of_markers[23]),
- ('hip_R', virtual_markers[1], order_of_markers[24]),
- ]
-
-#based on marker # from order_of_markers array add bones for hands:
-left_hand_offset = 54
-
-left_hand = [('handL0', order_of_markers[0+left_hand_offset], order_of_markers[1+left_hand_offset]),
- ('handL1', order_of_markers[1+left_hand_offset], order_of_markers[2+left_hand_offset]),
- ('handL2', order_of_markers[2+left_hand_offset], order_of_markers[3+left_hand_offset]),
- ('handL3', order_of_markers[3+left_hand_offset], order_of_markers[4+left_hand_offset]),
- ('handL5', order_of_markers[0+left_hand_offset], order_of_markers[5+left_hand_offset]),
- ('handL6', order_of_markers[5+left_hand_offset], order_of_markers[6+left_hand_offset]),
- ('handL7', order_of_markers[6+left_hand_offset], order_of_markers[7+left_hand_offset]),
- ('handL8', order_of_markers[7+left_hand_offset], order_of_markers[8+left_hand_offset]),
- ('handL9', order_of_markers[0+left_hand_offset], order_of_markers[9+left_hand_offset]),
- ('handL10', order_of_markers[9+left_hand_offset], order_of_markers[10+left_hand_offset]),
- ('handL11', order_of_markers[10+left_hand_offset], order_of_markers[11+left_hand_offset]),
- ('handL12', order_of_markers[11+left_hand_offset], order_of_markers[12+left_hand_offset]),
- ('handL13', order_of_markers[0+left_hand_offset], order_of_markers[13+left_hand_offset]),
- ('handL14', order_of_markers[13+left_hand_offset], order_of_markers[14+left_hand_offset]),
- ('handL15', order_of_markers[14+left_hand_offset], order_of_markers[15+left_hand_offset]),
- ('handL16', order_of_markers[15+left_hand_offset], order_of_markers[16+left_hand_offset]),
- ('handL18', order_of_markers[0+left_hand_offset], order_of_markers[17+left_hand_offset]),
- ('handL19', order_of_markers[17+left_hand_offset], order_of_markers[18+left_hand_offset]),
- ('handL20', order_of_markers[18+left_hand_offset], order_of_markers[19+left_hand_offset]),
- ('wristL', order_of_markers[15], order_of_markers[0+left_hand_offset]),
- ('handL21', order_of_markers[19+left_hand_offset], order_of_markers[20+left_hand_offset]),]
-
-
-right_hand_offset = 33
-
-right_hand = [('handR0', order_of_markers[18], order_of_markers[1+right_hand_offset]),
- ('handR1', order_of_markers[1+right_hand_offset], order_of_markers[2+right_hand_offset]),
- ('handR2', order_of_markers[2+right_hand_offset], order_of_markers[3+right_hand_offset]),
- ('handR3', order_of_markers[3+right_hand_offset], order_of_markers[4+right_hand_offset]),
- ('handR5', order_of_markers[18], order_of_markers[5+right_hand_offset]),
- ('handR6', order_of_markers[5+right_hand_offset], order_of_markers[6+right_hand_offset]),
- ('handR7', order_of_markers[6+right_hand_offset], order_of_markers[7+right_hand_offset]),
- ('handR8', order_of_markers[7+right_hand_offset], order_of_markers[8+right_hand_offset]),
- ('handR9', order_of_markers[18], order_of_markers[9+right_hand_offset]),
- ('handR10', order_of_markers[9+right_hand_offset], order_of_markers[10+right_hand_offset]),
- ('handR11', order_of_markers[10+right_hand_offset], order_of_markers[11+right_hand_offset]),
- ('handR12', order_of_markers[11+right_hand_offset], order_of_markers[12+right_hand_offset]),
- ('handR13', order_of_markers[18], order_of_markers[13+right_hand_offset]),
- ('handR14', order_of_markers[13+right_hand_offset], order_of_markers[14+right_hand_offset]),
- ('handR15', order_of_markers[14+right_hand_offset], order_of_markers[15+right_hand_offset]),
- ('handR16', order_of_markers[15+right_hand_offset], order_of_markers[16+right_hand_offset]),
- ('handR18', order_of_markers[18], order_of_markers[17+right_hand_offset]),
- ('handR19', order_of_markers[17+right_hand_offset], order_of_markers[18+right_hand_offset]),
- ('handR20', order_of_markers[18+right_hand_offset], order_of_markers[19+right_hand_offset]),
- ('wristR', order_of_markers[16], order_of_markers[18]),
- ('handR21', order_of_markers[19+right_hand_offset], order_of_markers[20+right_hand_offset]),]
-
-#helper to create armature from list of tuples
-def tuple_to_armature(bones):
- for bone_name, bone_head, bone_tail in bones:
- add_child_bone(bone_name, bone_head, bone_tail)
-
-#Set armature selected
-armature_data.select_set(state=True)
-#Set edit mode
-bpy.ops.object.mode_set(mode='EDIT', toggle=False)
-
-#create all bones for skeleton body and hands
-tuple_to_armature(list_of_bones_order)
-tuple_to_armature(right_hand)
-tuple_to_armature(left_hand)
-
-#parent heads and tails to empties
-#use bone constraints
-def parent_to_empties(bone_name, head, tail):
- #enter pose mode
- bpy.ops.object.posemode_toggle()
- marker = armature.data.bones[bone_name]
- #Set marker selected
- marker.select = True
- #Set marker active
- bpy.context.object.data.bones.active = marker
- bone = bpy.context.object.pose.bones[bone_name]
- #Copy Location Pose constraint: makes the bone's head follow the given empty
- bpy.ops.pose.constraint_add(type='COPY_LOCATION')
- bone.constraints["Copy Location"].target = head
- #Stretch To Pose constraint: makes the bone's tail follow the given empty
- #stretches the bones to reach the tail to that empty so head location is not affected
- bpy.ops.pose.constraint_add(type='STRETCH_TO')
- bone.constraints["Stretch To"].target = tail
- #exit pose mode
- bpy.ops.object.posemode_toggle()
-
-#set parents of heads and tails for each bone
-def tuple_to_parented(bones):
- for bone_name, bone_head, bone_tail in bones:
- parent_to_empties(bone_name, bone_head, bone_tail)
-
-tuple_to_parented(list_of_bones_order)
-tuple_to_parented(right_hand)
-tuple_to_parented(left_hand)
-
-#-----------------------------------------------------------------------------------
-# Animate!
-#find number of frames in animation
-num_frames = len(mediapipe_frames_arr)
-
-#change start frame of animation
-bpy.context.scene.frame_start = 1
-#change end frame of animation
-bpy.context.scene.frame_end = num_frames - 1
-
-#create a new handler to change empty positions every frame
-def my_handler(scene):
- bpy.ops.object.mode_set(mode='OBJECT')
- #keep track of current_marker
- current_marker = 0
- #find the current frame number
- frame = scene.frame_current
- #get the list of marker points from the current frame
- markers_list = mediapipe_frames_arr[frame]
- #iterate through list of markers in this frame
- for col in markers_list:
- frame = scene.frame_current
-
- if math.isnan(col[0]) and math.isnan(col[1]) and math.isnan(col[2]):
- #marker was not tracked, pass
- nan_frame = True
- pass
- else:
- #Flip y and z coordinates, and negate y to account for different coordinate system
- nan_frame = False
- coord = Vector(((float(col[0])*0.001), (float(col[1])*0.001), (float(col[2]))* 0.001))
- if len(order_of_markers) > 0:
- empty = order_of_markers[current_marker]
- empty.location = coord
- for index in range(len(virtual_markers)):
- update_virtual_marker(index)
- current_marker += 1
-
-
- #keyframe bones
- #Goes through each bone
- if not nan_frame:
- for editBone in get_armature().data.edit_bones:
- boneName = editBone.name
- poseBone = arm.pose.bones[boneName]
- poseBone.keyframe_insert('rotation_euler', frame=scene.frame_current)
- poseBone.keyframe_insert('location', frame=scene.frame_current)
- poseBone.keyframe_insert('scale', frame=scene.frame_current)
-
-#-----------------------------------------------------------------------------------
-#script to create a mesh of the armature
-def CreateMesh():
- obj = get_armature()
-
- if obj == None:
- print( "No selection" )
- elif obj.type != 'ARMATURE':
- print( "Armature expected" )
- else:
- return processArmature( bpy.context, obj )
-
-#Use armature to create base object
-def armToMesh( arm ):
- name = arm.name + "_mesh"
- dataMesh = bpy.data.meshes.new( name + "Data" )
- mesh = bpy.data.objects.new( name, dataMesh )
- mesh.matrix_world = arm.matrix_world.copy()
- return mesh
-
-#Make vertices and faces
-def boneGeometry( l1, l2, x, z, baseSize, l1Size, l2Size, base ):
- x1 = x * baseSize * l1Size * 0.8
- z1 = z * baseSize * l2Size * 0.8
-
- x2 = Vector( (np.nan, np.nan, np.nan) )
- z2 = Vector( (np.nan, np.nan, np.nan) )
-
- verts = [
- l1 - x1 + z1,
- l1 + x1 + z1,
- l1 - x1 - z1,
- l1 + x1 - z1,
- l2 - x2 + z2,
- l2 + x2 + z2,
- l2 - x2 - z2,
- l2 + x2 - z2
- ]
-
- faces = [
- (base+3, base+1, base+0, base+2),
- (base+6, base+4, base+5, base+7),
- (base+4, base+0, base+1, base+5),
- (base+7, base+3, base+2, base+6),
- (base+5, base+1, base+3, base+7),
- (base+6, base+2, base+0, base+4)
- ]
-
- return verts, faces
-
-#Process the armature, goes through its bones and creates the mesh
-def processArmature(context, arm, genVertexGroups = True):
- print("processing armature {0}".format(arm.name))
-
- #Creates the mesh object
- meshObj = armToMesh( arm )
- context.collection.objects.link( meshObj )
-
- verts = []
- edges = []
- faces = []
- vertexGroups = {}
-
- bpy.ops.object.mode_set(mode='EDIT')
-
- try:
- #Goes through each bone
- for editBone in get_armature().data.edit_bones:
- boneName = editBone.name
- if boneName == "":
- editBone.name = "bone"
- boneName = "bone"
- poseBone = arm.pose.bones[boneName]
-
- #Gets edit bone informations
- editBoneHead = editBone.head
- editBoneTail = editBone.tail
- editBoneVector = editBoneTail - editBoneHead
- editBoneSize = editBoneVector.dot( editBoneVector )
- editBoneRoll = editBone.roll
- editBoneX = editBone.x_axis
- editBoneZ = editBone.z_axis
- editBoneHeadRadius = editBone.head_radius
- editBoneTailRadius = editBone.tail_radius
-
- #Creates the mesh data for the bone
- baseIndex = len(verts)
- baseSize = math.sqrt( editBoneSize )
- newVerts, newFaces = boneGeometry( editBoneHead, editBoneTail, editBoneX, editBoneZ, baseSize, editBoneHeadRadius, editBoneTailRadius, baseIndex )
- verts.extend( newVerts )
- faces.extend( newFaces )
-
- #Creates the weights for the vertex groups
- vertexGroups[boneName] = [(x, 1.0) for x in range(baseIndex, len(verts))]
- #Assigns the geometry to the mesh
- meshObj.data.from_pydata(verts, edges, faces)
-
- except:
- bpy.ops.object.mode_set(mode='OBJECT')
- else:
- bpy.ops.object.mode_set(mode='OBJECT')
- #Assigns the vertex groups
- if genVertexGroups:
- for name1, vertexGroup in vertexGroups.items():
- groupObject = meshObj.vertex_groups.new(name = name1)
- for (index, weight) in vertexGroup:
- groupObject.add([index], weight, 'REPLACE')
-
- #Creates the armature modifier
- modifier = meshObj.modifiers.new('ArmatureMod', 'ARMATURE')
- modifier.object = arm
- modifier.use_bone_envelopes = False
- modifier.use_vertex_groups = True
-
- meshObj.data.update()
-
- return meshObj
-
-mesh_obob = CreateMesh()
-
-#-----------------------------------------------------------------------------------
-# Clean up the mesh by removing duplicate vertices, make sure all faces are quads, etc
-
-checked = set()
-for selected_object in bpy.data.objects:
- if selected_object.type != 'MESH':
- continue
- meshdata = selected_object.data
- if meshdata in checked:
- continue
- else:
- checked.add(meshdata)
- bpy.context.view_layer.objects.active = selected_object
- bpy.ops.object.editmode_toggle()
- bpy.ops.mesh.select_all(action='SELECT')
- bpy.ops.mesh.remove_doubles()
- bpy.ops.mesh.tris_convert_to_quads()
- bpy.ops.mesh.normals_make_consistent()
- bpy.ops.object.editmode_toggle()
-#Set armature active
-bpy.context.view_layer.objects.active = armature_data
-#Set armature selected
-armature_data.select_set(state=True)
-#-----------------------------------------------------------------------------------
-#function to register custom handler
-bpy.app.handlers.frame_change_post.clear()
-def register():
- bpy.app.handlers.frame_change_post.append(my_handler)
-
-def unregister():
- bpy.app.handlers.frame_change_post.remove(my_handler)
-
-register()
-
-scene = bpy.context.scene
-
-bpy.ops.object.mode_set(mode='OBJECT')
-
-bpy.ops.object.mode_set(mode='EDIT')
-
-arm = get_armature()
-
-#Connected according to: https://google.github.io/mediapipe/solutions/hands.html#hand-landmark-model
-
-arm.data.edit_bones['shoulder_L'].parent = arm.data.edit_bones['root']
-arm.data.edit_bones['shoulder_R'].parent = arm.data.edit_bones['root']
-
-arm.data.edit_bones['upper_arm_L'].parent = arm.data.edit_bones['shoulder_L']
-arm.data.edit_bones['upper_arm_R'].parent = arm.data.edit_bones['shoulder_R']
-arm.data.edit_bones['lower_arm_L'].parent = arm.data.edit_bones['upper_arm_L']
-arm.data.edit_bones['lower_arm_R'].parent = arm.data.edit_bones['upper_arm_R']
-
-arm.data.edit_bones['hip_L'].parent = arm.data.edit_bones['root']
-arm.data.edit_bones['hip_R'].parent = arm.data.edit_bones['root']
-arm.data.edit_bones['upper_leg_L'].parent = arm.data.edit_bones['hip_L']
-arm.data.edit_bones['upper_leg_R'].parent = arm.data.edit_bones['hip_R']
-arm.data.edit_bones['lower_leg_L'].parent = arm.data.edit_bones['upper_leg_L']
-arm.data.edit_bones['lower_leg_R'].parent = arm.data.edit_bones['upper_leg_R']
-arm.data.edit_bones['heel_L'].parent = arm.data.edit_bones['lower_leg_L']
-arm.data.edit_bones['heel_R'].parent = arm.data.edit_bones['lower_leg_R']
-arm.data.edit_bones['foot_L'].parent = arm.data.edit_bones['heel_L']
-arm.data.edit_bones['foot_R'].parent = arm.data.edit_bones['heel_R']
-
-
-arm.data.edit_bones['neck'].parent = arm.data.edit_bones['root']
-arm.data.edit_bones['eye_L'].parent = arm.data.edit_bones['neck']
-arm.data.edit_bones['eye_R'].parent = arm.data.edit_bones['neck']
-arm.data.edit_bones['ear_L'].parent = arm.data.edit_bones['eye_L']
-arm.data.edit_bones['ear_R'].parent = arm.data.edit_bones['eye_R']
-
-
-arm.data.edit_bones['wristL'].parent = arm.data.edit_bones['lower_arm_L']
-arm.data.edit_bones['wristR'].parent = arm.data.edit_bones['lower_arm_R']
-
-#------------------------------------------------------------------------
-
-arm.data.edit_bones['handR0'].parent = arm.data.edit_bones['wristR']
-arm.data.edit_bones['handR1'].parent = arm.data.edit_bones['handR0']
-arm.data.edit_bones['handR2'].parent = arm.data.edit_bones['handR1']
-arm.data.edit_bones['handR3'].parent = arm.data.edit_bones['handR2']
-
-arm.data.edit_bones['handR5'].parent = arm.data.edit_bones['wristR']
-arm.data.edit_bones['handR6'].parent = arm.data.edit_bones['handR5']
-arm.data.edit_bones['handR7'].parent = arm.data.edit_bones['handR6']
-arm.data.edit_bones['handR8'].parent = arm.data.edit_bones['handR7']
-
-arm.data.edit_bones['handR9'].parent = arm.data.edit_bones['wristR']
-arm.data.edit_bones['handR10'].parent = arm.data.edit_bones['handR9']
-arm.data.edit_bones['handR11'].parent = arm.data.edit_bones['handR10']
-arm.data.edit_bones['handR12'].parent = arm.data.edit_bones['handR11']
-
-arm.data.edit_bones['handR13'].parent = arm.data.edit_bones['wristR']
-arm.data.edit_bones['handR14'].parent = arm.data.edit_bones['handR13']
-arm.data.edit_bones['handR15'].parent = arm.data.edit_bones['handR14']
-arm.data.edit_bones['handR16'].parent = arm.data.edit_bones['handR15']
-
-arm.data.edit_bones['handR18'].parent = arm.data.edit_bones['wristR']
-arm.data.edit_bones['handR19'].parent = arm.data.edit_bones['handR18']
-arm.data.edit_bones['handR20'].parent = arm.data.edit_bones['handR19']
-arm.data.edit_bones['handR21'].parent = arm.data.edit_bones['handR20']
-
-##------------------------------------------------------------------------
-
-
-arm.data.edit_bones['handL0'].parent = arm.data.edit_bones['wristL']
-arm.data.edit_bones['handL1'].parent = arm.data.edit_bones['handL0']
-arm.data.edit_bones['handL2'].parent = arm.data.edit_bones['handL1']
-arm.data.edit_bones['handL3'].parent = arm.data.edit_bones['handL2']
-
-arm.data.edit_bones['handL5'].parent = arm.data.edit_bones['wristL']
-arm.data.edit_bones['handL6'].parent = arm.data.edit_bones['handL5']
-arm.data.edit_bones['handL7'].parent = arm.data.edit_bones['handL6']
-arm.data.edit_bones['handL8'].parent = arm.data.edit_bones['handL7']
-
-arm.data.edit_bones['handL9'].parent = arm.data.edit_bones['wristL']
-arm.data.edit_bones['handL10'].parent = arm.data.edit_bones['handL9']
-arm.data.edit_bones['handL11'].parent = arm.data.edit_bones['handL10']
-arm.data.edit_bones['handL12'].parent = arm.data.edit_bones['handL11']
-
-arm.data.edit_bones['handL13'].parent = arm.data.edit_bones['wristL']
-arm.data.edit_bones['handL14'].parent = arm.data.edit_bones['handL13']
-arm.data.edit_bones['handL15'].parent = arm.data.edit_bones['handL14']
-arm.data.edit_bones['handL16'].parent = arm.data.edit_bones['handL15']
-
-arm.data.edit_bones['handL18'].parent = arm.data.edit_bones['wristL']
-arm.data.edit_bones['handL19'].parent = arm.data.edit_bones['handL18']
-arm.data.edit_bones['handL20'].parent = arm.data.edit_bones['handL19']
-arm.data.edit_bones['handL21'].parent = arm.data.edit_bones['handL20']
-
-for editBone in get_armature().data.edit_bones:
- # this line is important, when inheriting scale and using the stretch to constraint the bones freak out
- editBone.inherit_scale = 'NONE'
-
-
-##------------------------------------------------------------------------
-
-#Select objects to export
-col = bpy.data.collections.get("Collection")
-
-bpy.ops.object.mode_set(mode='OBJECT')
-
-#Run thorugh frames, export a csv file with local bone rotations
-# open the file in the write mode
-f = open(sesh_path + sesh_ID + '_local_bone_rotations.csv', 'w')
-
-# create the csv writer
-writer = csv.writer(f)
-writer.writerow(["Frame_number", "Bone name", "X", "Y", "Z"])
-for frame in range(scene.frame_start, scene.frame_end):
- scene.frame_set(frame)
- arm = get_armature()
- coords_per_frame = [frame]
- for bone in arm.pose.bones:
- if bone.parent:
- Original_rot = bone.matrix_basis.copy()
-
- a = bone.matrix.copy()
- b = bone.parent.matrix.copy()
-
- q1 = a.to_quaternion()
-
- q2 = b.to_quaternion()
-
- difQuat = q1.rotation_difference(q2)
-
- difEuler = difQuat.to_euler()
- mat = difEuler
- else:
- a = bone.matrix.copy()
- q1 = a.to_quaternion()
- mat = q1.to_euler()
- x = degrees(mat.x)
- y = degrees(mat.y)
- z = degrees(mat.z)
-
- if x < 0.0001:
- x = 0.0
- if y < 0.0001:
- y = 0.0
- if z < 0.0001:
- z = 0.0
- coords_per_frame.append(bone.name)
- coords_per_frame.append(x)
- coords_per_frame.append(y)
- coords_per_frame.append(z)
- writer.writerow(coords_per_frame)
-
-
-bpy.ops.object.mode_set(mode='OBJECT')
-
-
-#set keyframes for whole animation
-for frame in range(scene.frame_start, scene.frame_end):
- scene.frame_set(frame)
-
-#Select objects to export
-col = bpy.data.collections.get("Collection")
-if col:
- for obj in col.objects:
- if "Armature_MediaPipe_Object" == obj.name:
- obj.select_set(True)
-
-
-#Bake the skeletal animation
-# ensure that only the armature is selected in Object mode
-bpy.ops.object.mode_set(mode='OBJECT')
-bpy.ops.object.select_all(action='DESELECT')
-
-empties = [e for e in bpy.data.objects
- if e.type.startswith('EMPTY')]
-for e in empties:
- e.select_set(True)
-
-
-#Set armature active
-bpy.context.view_layer.objects.active = bpy.data.objects[get_armature().name]
-#Set armature selected
-bpy.data.objects[get_armature().name].select_set(state=True)
-
-#Change to pose mode
-bpy.ops.object.mode_set(mode='POSE')
-
-#Bake the animation
-bpy.ops.nla.bake(frame_start=scene.frame_start, frame_end=scene.frame_end, only_selected=False, visual_keying=True, clear_constraints=True, use_current_action=False, bake_types={'POSE', 'OBJECT'})
-
-bpy.ops.object.mode_set(mode='OBJECT')
-
-#Select objects to export
-col = bpy.data.collections.get("Collection")
-if col:
- for obj in col.objects:
- if "Armature" in obj.name:
- obj.select_set(True)
- if obj.name == "Cube" or obj.name == "Light" or obj.name == "Camera":
- bpy.data.objects.remove(obj)
-
-for e in empties:
- e.select_set(True)
-
-#save blender file
-bpy.ops.wm.save_as_mainfile(filepath= sesh_path + sesh_ID + '.blend')
-
-
-#export FBX
-bpy.ops.export_scene.fbx(filepath= sesh_path + sesh_ID + '.fbx', path_mode='RELATIVE', bake_anim=True, use_selection=True, object_types={'MESH', 'ARMATURE', 'EMPTY'}, use_mesh_modifiers = False, add_leaf_bones = False, axis_forward = '-X', axis_up = 'Z', bake_anim_use_all_bones = False, bake_anim_use_nla_strips = False, bake_anim_use_all_actions = False, bake_anim_force_startend_keying = False)
-
-#export GLTF
-bpy.ops.export_scene.gltf(filepath=sesh_path + sesh_ID + '.gltf', export_format='GLTF_EMBEDDED', use_selection=True, ui_tab='ANIMATION')
-
-#export USD
-bpy.ops.wm.usd_export(filepath=sesh_path + sesh_ID + '.usdc', selected_objects_only=True, export_animation=True)
-
-
-#--------------------------------------------------------------------------------------------
-#Create a panel to display local bone angles in relation to parent bone
-class LOCAL_PT_BoneAnglesPanel(bpy.types.Panel):
- bl_label = "Bone Angles Local"
- bl_space_type = 'VIEW_3D'
- bl_region_type = 'UI'
-
- def draw(self, context):
- arm = get_armature()
-
- row = self.layout.row()
- row.label(text='Bone name')
- row.label(text='Degrees X')
- row.label(text='Degrees Y')
- row.label(text='Degrees Z')
-
- for bone in arm.pose.bones:
- row = self.layout.row()
- row.label(text=bone.name)
- if bone.parent:
- Original_rot = bone.matrix_basis.copy()
-
- a = bone.matrix.copy()
- b = bone.parent.matrix.copy()
-
- q1 = a.to_quaternion()
-
- q2 = b.to_quaternion()
-
- difQuat = q1.rotation_difference(q2)
-
- difEuler = difQuat.to_euler()
- mat = difEuler
-
- else:
- a = bone.matrix.copy()
- q1 = a.to_quaternion()
- mat = q1.to_euler()
-
- x = mat.x
- y = mat.y
- z = mat.z
-
- if x < 0.0001:
- x = 0.0
- if y < 0.0001:
- y = 0.0
- if z < 0.0001:
- z = 0.0
- row.label(text='X: {:.3}'.format(degrees(x)))
- row.label(text='Y: {:.3}'.format(degrees(y)))
- row.label(text='Z: {:.3}'.format(degrees(z)))
-
-
-bpy.utils.register_class(LOCAL_PT_BoneAnglesPanel)
\ No newline at end of file
diff --git a/freemocap/fmc_deeplabcut.py b/freemocap/fmc_deeplabcut.py
deleted file mode 100644
index 00487739..00000000
--- a/freemocap/fmc_deeplabcut.py
+++ /dev/null
@@ -1,103 +0,0 @@
-# -*- coding: utf-8 -*-
-"""
-Created on Fri Feb 26 12:42:08 2021
-
-@author: Rontc
-"""
-import glob
-import numpy as np
-import pandas as pd
-import matplotlib.pyplot as plt
-from ruamel.yaml import YAML
-
-from pathlib import Path
-import h5py
-
-
-def parseDeepLabCut(
- session,
- config_path
-): # NOTE this is assuming both the dlc config file and dlc data h5 foles are in the same folder specified in the session.dlcDataPath, if that is not the case either dlcconfig or h5files variable need to be changed
-
- dlcConfig = config_path # File path for dlcConfig file
- yaml=YAML()
-
- with open(dlcConfig) as configFile:
- # Open the config file
- configList = yaml.load(configFile, Loader=yaml.FullLoader)
- for item, doc in configList.items(): # For each item in the config file
- if item == "bodyparts": # If the item is bodyparts
- bodypartList = doc # Set that list to a variable
- if item == "skeleton": # If the item is skeleton
- skeletonList = doc # Set that list to a variable
-
- h5files = session.dlcDataPath.glob("*.h5") # Take all h5 files from folder
-
- numCams = int(session.numCams) # Get num of cams
- numFrames = session.numFrames + 10 # Get num of frames
-
- numImgPoints = len(bodypartList) # Get amount of points tracked
- dlcData_nCams_nFrames_nImgPts_XYC = np.ndarray([numCams, numFrames, numImgPoints, 3]) # Create empty array for dlc points
-
- nn = 0 # counter for each camera
- for data in h5files: # Loop throuxgh each camera
-
- with h5py.File(data) as f: # Open each h5 file
- fullDataGroup = f.get("df_with_missing") # Open main h5 group
- dataTable = fullDataGroup.get("table") # Open datatable with all DLC tracked points
-
- for ii in range(len(dataTable)): # Loop through each frame
- dataFromOneFrame = dataTable[ii] # Assign frame to varible
- idx = len(dataFromOneFrame[1]) / 3 # index for reshaping data
- sortedFrame = np.array(dataFromOneFrame[1]) # Put data in numpy array
- try:
- dlcData_nCams_nFrames_nImgPts_XYC[nn, ii, :, :] = sortedFrame.reshape(
- int(idx), 3
- ) # Reshape the data into the correct form
- except:
- print('If you get an out-of-bounds error here, you may have too many DLC files in the DLCData folder - empty it out and re-run DLC to fix')
- #NOTE - we should fix this , i.e. by moving old DLC data to an 'oldDLCData' folder within DLCData if the user tries to run DLC when there are already files in the DLCData folder
- nn += 1
-
- if session.debug:
- fig = plt.figure()
-
- ax1 = fig.add_subplot(221)
- ax2 = fig.add_subplot(222)
- ax3 = fig.add_subplot(223)
- ax4 = fig.add_subplot(224)
-
- cam1im = session.firstImage_nCams_list[0]
- cam2im = session.firstImage_nCams_list[1]
- cam3im = session.firstImage_nCams_list[2]
- cam4im = session.firstImage_nCams_list[3]
-
- ax1.imshow(cam1im)
- ax1.plot(
- dlcData_nCams_nFrames_nImgPts_XYC[0, 0, :, 0],
- dlcData_nCams_nFrames_nImgPts_XYC[0, 0, :, 1],
- )
-
- ax2.imshow(cam2im)
- ax2.plot(
- dlcData_nCams_nFrames_nImgPts_XYC[1, 0, :, 0],
- dlcData_nCams_nFrames_nImgPts_XYC[1, 0, :, 1],
- )
-
- ax3.imshow(cam3im)
- ax3.plot(
- dlcData_nCams_nFrames_nImgPts_XYC[2, 0, :, 0],
- dlcData_nCams_nFrames_nImgPts_XYC[2, 0, :, 1],
- )
-
- ax4.imshow(cam4im)
- ax4.plot(
- dlcData_nCams_nFrames_nImgPts_XYC[3, 0, :, 0],
- dlcData_nCams_nFrames_nImgPts_XYC[3, 0, :, 1],
- )
-
- plt.show()
-
-
-
- return dlcData_nCams_nFrames_nImgPts_XYC
diff --git a/freemocap/fmc_demo.py b/freemocap/fmc_demo.py
deleted file mode 100644
index efef7648..00000000
--- a/freemocap/fmc_demo.py
+++ /dev/null
@@ -1,153 +0,0 @@
-from freemocap import fmc_runme,recordingconfig
-
-import zipfile
-from pathlib import Path
-import tkinter as tk
-from tkinter import Tk, Label, Button, Frame, Listbox, Entry, filedialog
-import requests
-import io
-
-def DemoSetup():
-
-
- download_data = runDataDownloadGUI() #ask for user input on downloading
- zip_file_url = 'https://figshare.com/ndownloader/files/30913897'
- sample_session_name = 'sesh_21-07-20_165209'
- sample_session_zip = sample_session_name + '.zip'
-
- if download_data: #if they want to download
- download_it = True
- #code to download stuff from online will go here
- destinationPath = runDemoGUI()
-
- if destinationPath == None:
- print('Please choose where to save your sample data')
- download_it = False
- extractToPath = None
- #error seems to expect the sample session to still be a zip file even though it is unzipped below
- if download_it == True:
- currentPath = Path(destinationPath)/sample_session_name
-
- if 'FreeMocap_Data' in str(destinationPath):
- if currentPath.exists():
- extractToPath = None
- print('There is already a sample data folder at: ' + str(currentPath))
- download_it = False
- #extractToPath = destinationPath/sample_session_zip
- extractToPath = destinationPath
- else:
- extractToFolder = Path(destinationPath)/recordingconfig.dataFolder #append the name of the data folder to the destination path
- extractToFolder.mkdir(exist_ok=True) #make the data folder if it doesn't current exist
- extractToPath = extractToFolder
-
- checkPath = extractToFolder/sample_session_name
- if checkPath.exists():
- print('There is already a sample data folder at: ' + str(checkPath))
- extractToPath = None
- download_it = False
- #extractToPath = extractToFolder/sample_session_name
-
-
- #run the GUI to get the directory locations of the zipped folder, and where to extract it to
- #locationPath, destinationPath = runDemoGUI()
- #zipPath = Path(locationPath)/'sesh_21-07-18_170130.zip' #append the name of the zipped sample file to the path to find it
-
- if download_it:
- print('Starting demo session download')
- r = requests.get(zip_file_url)
- z = zipfile.ZipFile(io.BytesIO(r.content))
- z.extractall(extractToPath)
- extractedPath = Path(extractToPath)/sample_session_name
- print('Demo session downloaded to: ' + str(extractedPath))
- print('You can find the animation in the sample data folder as {}_outvid.mp4'.format(sample_session_name))
- #with zipfile.ZipFile(zipPath,'r') as zip_ref:
- # zip_ref.extractall(extractToPath) #extract stuff to the data folder
- # else:
- # root = tk.Tk() #bring up a window to select the data folder directory
- # root.withdraw()
- # destinationPath = filedialog.askdirectory( title='Select the directory where the Freemocap_data folder with the sample data is located',
- # initialdir= Path.cwd())
-
-
- return extractToPath, sample_session_name #take the path to the directory where the data folder is located
-
-class DemoGUI(): #GUI to pick the location and the destination directories for the sample data
- def __init__(self, master):
- self.master = master
-
- self.destinationPath = None
-
- sampleDestinationText = "Select your {} folder to save the sample data into. \n If you don't have a {} folder, choose where you'd like to create one. Your sample data will be saved into it.".format(recordingconfig.dataFolder,recordingconfig.dataFolder)
- sampleDestinationLabel = Label(master, text=sampleDestinationText)
- sampleDestinationLabel.pack()
-
- self.destinationPathVar = tk.StringVar()
- savedDestinationLabel = Label(master,textvariable=self.destinationPathVar)
- savedDestinationLabel.pack()
-
- sampleDestinationButton = Button(master,text = 'Select the sample data destination',command = self.openDestinationDialog)
- sampleDestinationButton.pack()
-
- submitButton = Button(master,text = 'Submit',command = self.submit)
- submitButton.pack()
-
-
- def openDestinationDialog(self):
-
- self.destinationPath = filedialog.askdirectory(
- title='Select the directory where the freemocap data is located or should be created',
- initialdir= Path.cwd())
- f = 2
-
- self.destinationPathVar.set(self.destinationPath)
-
- def submit(self):
- self.master.destroy()
-
-
- def getLocationPath(self):
- return self.locationPath
-
- def getDestinationPath(self):
- return self.destinationPath
-
-class dataDownloadGUI(): #GUI to ask whether users want to download data
- def __init__(self, master):
- self.master = master
-
- dataText = "Would you like to download sample data?"
- dataLable = Label(master, text=dataText)
- dataLable.pack(side="top")
-
- yesButton = Button(master,text = 'Yes',command = self.yes)
- yesButton.pack()
-
- noButton = Button(master,text = 'No',command = self.no)
- noButton.pack()
-
- def yes(self):
- self.download_sample_data = True
- self.master.destroy()
-
-
- def no(self):
- self.download_sample_data = False
- self.master.destroy()
-
-
-def runDemoGUI():
- root = tk.Tk()
- pathchoices = DemoGUI(root)
- root.mainloop()
- destinationPath = pathchoices.destinationPath
-
- return destinationPath
-
-def runDataDownloadGUI():
- root = tk.Tk()
- download_options = dataDownloadGUI(root)
- root.mainloop()
-
- return download_options.download_sample_data
-
-
diff --git a/freemocap/fmc_good_frame_finder.py b/freemocap/fmc_good_frame_finder.py
deleted file mode 100644
index efbf603b..00000000
--- a/freemocap/fmc_good_frame_finder.py
+++ /dev/null
@@ -1,103 +0,0 @@
-
-import numpy as np
-import matplotlib.pyplot as plt
-
-
-
-
-def find_velocity_values_within_limit(skeleton_velocity_data, velocity_limit):
- """
- This function takes in a skeleton velocity data array and a limit and returns the indices of the values that are within the limit
- """
- indices = []
- for i in range(len(skeleton_velocity_data)):
- if abs(skeleton_velocity_data[i]) <= velocity_limit:
- indices.append(i+1) #add 1 to account for the difference in indices between the position and velocity data
- return indices
-
-def find_matching_indices_in_lists(list_1,list_2,list_3,list_4):
- """
- This function takes in four lists and returns the indices of the values that are in all four lists
- """
- matching_values = [x for x in list_1 if x in list_2 and x in list_3 and x in list_4]
-
- return matching_values
-
-def find_best_velocity_guess(skeleton_velocity_data, velocity_guess, iteration_range):
- """
- This function iterates over velocity data and tries to pare down to a single frame that has the closest velocity to 0 for all foot markers
- """
-
- right_heel_index = 30
- right_toe_index = 32
- left_heel_index = 29
- left_toe_index = 31
-
- skeleton_data_velocity_x_right_heel = skeleton_velocity_data[:,right_heel_index,0]
- skeleton_data_velocity_x_right_toe = skeleton_velocity_data[:,right_toe_index,0]
- skeleton_data_velocity_x_left_heel = skeleton_velocity_data[:,left_heel_index,0]
- skeleton_data_velocity_x_left_toe = skeleton_velocity_data[:,left_toe_index,0]
-
- #get a list of the frames where the velocity for that marker is within the velocity limit
- right_heel_x_velocity_limits = find_velocity_values_within_limit(skeleton_data_velocity_x_right_heel, velocity_guess)
- right_toe_x_velocity_limits = find_velocity_values_within_limit(skeleton_data_velocity_x_right_toe, velocity_guess)
- left_heel_x_velocity_limits = find_velocity_values_within_limit(skeleton_data_velocity_x_left_heel, velocity_guess)
- left_toe_x_velocity_limits = find_velocity_values_within_limit(skeleton_data_velocity_x_left_toe, velocity_guess)
-
- #return a list of matching frame indices from the four lists generated above
- matching_values = find_matching_indices_in_lists(right_heel_x_velocity_limits, right_toe_x_velocity_limits, left_heel_x_velocity_limits, left_toe_x_velocity_limits)
- matching_values = [x for x in matching_values if x>75]
- if len(matching_values) < 10:
- print(matching_values)
- if len(matching_values) > 1 and velocity_guess > 0:
- #if there are multiple matching values, decrease the guess a little bit and run the function again
- #
- velocity_guess = velocity_guess - iteration_range
-
-
- print('Current Velocity Guess: ',velocity_guess, '\n','Number of Matching Frames: ', len(matching_values))
- matching_values, velocity_guess = find_best_velocity_guess(skeleton_velocity_data, velocity_guess, iteration_range)
-
- f = 2
- elif len(matching_values) == 0:
- #if there are no matching values (we decreased our guess too far), reset the guess to be a bit smaller and run the function again with smaller intervals between the guesses
- iteration_range = iteration_range/2
- matching_values, velocity_guess = find_best_velocity_guess(skeleton_velocity_data, velocity_guess + iteration_range*2, iteration_range)
-
- f = 2
- elif len(matching_values) == 1:
- print('Final Velocity Value: ',velocity_guess, '\n','Good Frame: ', matching_values)
-
- return matching_values, velocity_guess
-
-def set_axes_ranges(plot_ax,skeleton_data,ax_range):
-
- mx = np.nanmean(skeleton_data[:,0])
- my = np.nanmean(skeleton_data[:,1])
- mz = np.nanmean(skeleton_data[:,2])
-
- plot_ax.set_xlim(mx-ax_range,mx+ax_range)
- plot_ax.set_ylim(my-ax_range,my+ax_range)
- plot_ax.set_zlim(mz-ax_range,mz+ax_range)
-
-def find_good_frame(skeleton_data, initial_velocity_guess, debug = False):
-
- print('Finding Good Frame')
- skeleton_velocity_data = np.diff(skeleton_data, axis=0)
-
- matching_values, velocity_guess = find_best_velocity_guess(skeleton_velocity_data, initial_velocity_guess, iteration_range=.1)
-
- good_frame = matching_values[0]
-
- if debug:
-
- figure = plt.figure()
- ax = figure.add_subplot(111, projection = '3d')
-
- ax.scatter(skeleton_data[good_frame,:,0], skeleton_data[good_frame,:,1], skeleton_data[good_frame,:,2], c='r', marker='o')
-
- set_axes_ranges(ax, skeleton_data[good_frame,:,:], 1000)
-
- plt.show()
-
- return good_frame
diff --git a/freemocap/fmc_maya_tools.py b/freemocap/fmc_maya_tools.py
deleted file mode 100644
index b72e9c75..00000000
--- a/freemocap/fmc_maya_tools.py
+++ /dev/null
@@ -1,125 +0,0 @@
-"""
-# Example code for creating a data_handler
-# populating it by importing a npy dataset
-# setting mapping and parents
-# and writing the data to Maya
-
-import fmc_trackdata_handler as df
-import fmc_maya_tools as mt
-import openpose_data_mappings as data_mapping
-
-### Make empty data structure
-data_handler = df.FmcTracDataHandler()
-
-### Set mapping
-data_handler.set_parent_mapping(data_mapping.parent_mapping)
-data_handler.set_point_name_mapping(data_mapping.point_name_mapping)
-
-### Load openpose npy data into variable
-import numpy as np
-datafile_path = r"G:\Shared drives\000_projects\cl005_northeasternMarkerlessMocap\incoming\datasets\sesh_21-05-31_111833\DataArrays\openPoseSkel_3d.npy"
-data = np.load(datafile_path)
-
-### Import data into data handler as an actor. Handler can contain multiple actors
-# This step can be repeated for multiple datasets, adding each as an individual actor
-actor_name = "tester"
-data_handler.import_actor_raw_data(actor_name, data)
-
-### Write content of data_handler to Maya
-mt.write_to_maya(data_handler, slice=False)
-"""
-
-import maya.cmds as cmds
-import math
-
-
-def write_to_maya(fmcDataObj, slice=False, sample_by = 5):
- """
- Takes a trackdata handler object and creates animated maya objects accordingly
-
- input:
- fmcDataObj: object og type FmcTracDataHandler
- slice: if not false should be an int tuple of len=2 defining start and end frame to write to Maya
- sample_by: only write every n'th frame to Maya
- """
- for actor_name in fmcDataObj.list_actors():
- ### Creating point_names
- sample_length = fmcDataObj.get_actor_sample_count(actor_name)
- tracking_points = fmcDataObj.get_actor_tracking_points(actor_name)
- point_names = tracking_points.keys()
-
- # Create point locators
- pnt_locs = {}
- for pnt_name in point_names:
- pnt_locs[pnt_name] = cmds.spaceLocator(n=pnt_name+ "_loc")[0]
-
- #cmds.scale(0.2, 0.2, 0.2, list(pnt_locs.values()))
-
-
- # Make line connector between point locators according to "parents"
- connect_lines = []
- for pnt_name in point_names:
- parents = fmcDataObj.get_point_parents(actor_name, pnt_name)
- for parent_name in parents:
- line = make_line_between(pnt_locs[pnt_name], pnt_locs[parent_name], "connectorLine_" + pnt_name + "_" + parent_name)
- connect_lines.append(line)
-
- # group everything under the same transform
- grp = cmds.group(list(pnt_locs.values()) + connect_lines, name="mmcap_" + actor_name + "_grp")
-
- # Adding position data to point locators
- if not slice == False and len(slice)==2:
- print("Slice active: using samples in range: %s:%s" % (slice[0], slice[1]))
- sample_range = range(slice[0], slice[1], sample_by)
- else:
- sample_range = range(0, sample_length, sample_by)
-
- progress_step = 100./len(sample_range)
- progress = 0
- last_progress = 0
- for sample_i in sample_range:
- for pnt_name in point_names:
- loc_name = pnt_locs[pnt_name]
- pos = tracking_points[pnt_name]["samples"][sample_i]
- if not math.isnan(pos[0]):
- cmds.setKeyframe(loc_name, v=pos[0], at='translateX', time=sample_i )
- cmds.setKeyframe(loc_name, v=pos[1], at='translateY', time=sample_i )
- cmds.setKeyframe(loc_name, v=pos[2], at='translateZ', time=sample_i )
- progress += progress_step
- if int(progress) > int(last_progress):
- print(str(int(progress)).zfill(2) + "%")
- last_progress = progress
-
-
- # Reorienting base group to align with grid
- for attr in reorient_transform:
- cmds.setAttr(grp+"." + attr, reorient_transform[attr])
-
- cmds.playbackOptions(minTime= sample_range[0], maxTime = sample_range[-1])
-
-
-
-
-def make_line_between(obj1, obj2, line_name):
- """
- creates a curve segment and attaches each end to obj1 and obj2 accordingly
- """
- line = cmds.curve(name=line_name, d=1, p=[(0,0,0),(0,0,0)])
- cmds.connectAttr(obj1+".t", line + ".cv[0]")
- cmds.connectAttr(obj2+".t", line + ".cv[1]")
- return line
-
-
-
-# Imperically derived orientation to place actor on grid in Maya
-reorient_transform = {
- "translateX": 6.976,
- "translateY": -21.502,
- "translateZ": 47.516,
- "rotateX": -114.918,
- "rotateY": 4.391,
- "rotateZ":0,
- "scaleX": 0.031,
- "scaleY": 0.031,
- "scaleZ": 0.031,
- }
diff --git a/freemocap/fmc_mediapipe.py b/freemocap/fmc_mediapipe.py
deleted file mode 100644
index 4c79804e..00000000
--- a/freemocap/fmc_mediapipe.py
+++ /dev/null
@@ -1,334 +0,0 @@
-from pathlib import Path
-
-
-import numpy as np
-from rich.progress import Progress
-import cv2
-import mediapipe as mp
-
-# from numba import jit
-
-mp_drawing = mp.solutions.drawing_utils
-mp_drawing_styles = mp.solutions.drawing_styles
-mp_holistic = mp.solutions.holistic
-
-mediapipe_indices = [
- 'nose',
- 'left_eye_inner',
- 'left_eye',
- 'left_eye_outer',
- 'right_eye_inner',
- 'right_eye',
- 'right_eye_outer',
- 'left_ear',
- 'right_ear',
- 'mouth_left',
- 'mouth_right',
- 'left_shoulder',
- 'right_shoulder',
- 'left_elbow',
- 'right_elbow',
- 'left_wrist',
- 'right_wrist',
- 'left_pinky',
- 'right_pinky',
- 'left_index',
- 'right_index',
- 'left_thumb',
- 'right_thumb',
- 'left_hip',
- 'right_hip',
- 'left_knee',
- 'right_knee',
- 'left_ankle',
- 'right_ankle',
- 'left_heel',
- 'right_heel',
- 'left_foot_index',
- 'right_foot_index'
- ]
-
-def runMediaPipe(session, dummyRun=False):
- """
- Run MediaPipe on synced videos, and save body tracking data to be parsed
- """
-
-
-
- with mp_holistic.Holistic(
- static_image_mode = False, #use 'static image mode' to avoid system getting 'stuck' on ghost skeletons?
- model_complexity = 2, #in this house, we turn the Speed/Accuracy dial all the way towards accuracy \o/)
- ) as holistic:
-
- eachCamerasData = [] # Create an empty list that holds each cameras data
- eachCameraResolution = {'Height':[],'Width':[]}
- for ( thisVidPath ) in ( session.syncedVidPath.iterdir() ): # Run MediaPipe 'Holistic' (body, hands, face) tracker on each video in the raw video folder
- if ( thisVidPath.suffix.lower() == ".mp4" ): # NOTE - at some point we should build some list of 'synced video names' and check against that
-
-
- mediaPipe_dataList = [] # Create an empty list for mediapipes data
- if not dummyRun:
- cap = cv2.VideoCapture(str(thisVidPath))
-
- frameNum = -1
- numFrames = cap.get(cv2.CAP_PROP_FRAME_COUNT)
- success, image = cap.read() # load first image from video
-
- with Progress() as progress:
- progressBar = progress.add_task(
- "[magenta]MediaPiping: {}".format(thisVidPath.name),
- total=numFrames,
- ) # make progressbar
-
- while success:
-
- if frameNum % 5 == 0:
- progress.update(
- progressBar, advance=5
- ) # increment progress bar everyh 5th frame
-
- frameNum += 1
-
- image_height, image_width, _ = image.shape
-
- results = holistic.process(
- cv2.cvtColor(image, cv2.COLOR_BGR2RGB), #Convert the BGR image to RGB before processing
- ) # NOTE: THIS IS WHERE THE MAGIC HAPENS
-
- mediaPipe_dataList.append(
- results
- ) # Append data to mediapipe data list
-
- # load the next image (will break `while-loop` on the last frame)
- success, image = cap.read() # load next image from video
-
- eachCameraResolution["Height"].append(image_height)
- eachCameraResolution["Width"].append(image_width)
-
- eachCamerasData.append(
- mediaPipe_dataList
- ) # Append that cameras data for every frame to the camera datalist
-
- session.image_height = image_height
- session.image_width = image_width
- session.mediaPipeData = eachCamerasData
- session.eachCameraResolution = eachCameraResolution
-
-
-
-def parseMediaPipe(session):
- """
- Parse through saved MediaPipe data, and save out a numpy array of 2D points
- """
- numCams = len(session.mediaPipeData) # Get number of cameras
- numFrames = len(session.mediaPipeData[0]) # Get number of frames
- # numBodyPoints = len(np.max(session.mediaPipeData[0][:].pose_landmarks.landmark[:]))#Get number of body points
- # numFacePoints = len(np.max(session.mediaPipeData[0][:].face_landmarks.landmark[:]))#Get number of face points
- # numLeftHandPoints = len(np.max(session.mediaPipeData[0][:].left_hand_landmarks.landmark[:]))#Get number of right hand points
- # numRightHandPoints = len(np.max(session.mediaPipeData[0][:].right_hand_landmarks.landmark[:]))#Get number of left hand points
- numBodyPoints = 33
- numFacePoints = 468
- numHandPoints = 21
-
- numTrackedPoints = (
- numBodyPoints + numHandPoints * 2 + numFacePoints
- ) # Get total points
-
- # Create array of nans the size of number of cams, frame, points, XYC
- mediaPipeData_nCams_nFrames_nImgPts_XYC = np.empty(
- (int(numCams), int(numFrames), int(numTrackedPoints), 3)
- ) # create empty array
- mediaPipeData_nCams_nFrames_nImgPts_XYC[:] = np.NaN # Fill it with NaNs!
-
- for camNum in range(numCams): # Loop through each camera
- for frNum in range(numFrames): # Loop through each frame
- # make empty arrays for thisFrame's data
- # thisFrame_X = np.empty(numTrackedPoints)
- # thisFrame_X[:] = np.nan
- # thisFrame_Y = thisFrame_X.copy()
- # thisFrame_C = thisFrame_X.copy()
-
- thisFrame_X_body = np.empty(numBodyPoints)
- thisFrame_X_body[:] = np.nan
- thisFrame_Y_body = thisFrame_X_body.copy()
- thisFrame_C_body = thisFrame_X_body.copy()
-
- thisFrame_X_face = np.empty(numFacePoints)
- thisFrame_X_face[:] = np.nan
- thisFrame_Y_face = thisFrame_X_face.copy()
- thisFrame_C_face = thisFrame_X_face.copy()
-
- thisFrame_hands = np.empty(numHandPoints)
- thisFrame_hands[:]= np.nan
-
- thisFrame_X_lefthand = thisFrame_hands.copy()
- thisFrame_Y_lefthand = thisFrame_hands.copy()
- thisFrame_C_lefthand = thisFrame_hands.copy()
-
- thisFrame_X_righthand = thisFrame_hands.copy()
- thisFrame_Y_righthand = thisFrame_hands.copy()
- thisFrame_C_righthand = thisFrame_hands.copy()
-
- fullFrame = True
- if frNum == 107:
- f = 9
- try:
- # pull out ThisFrame's mediapipe data (`mpData.pose_landmarks.landmark` returns something iterable Β―\_(ツ)_/Β―)
- thisFrame_poseDataLandMarks = session.mediaPipeData[camNum][
- frNum
- ].pose_landmarks.landmark # body ('pose') data
- # stuff body data into pre-allocated nan array
- thisFrame_X_body[:numBodyPoints] = [
- pp.x for pp in thisFrame_poseDataLandMarks
- ] # PoseX data - Normalized screen coords (in range [0, 1]) - need multiply by image resultion for pixels
- thisFrame_Y_body[:numBodyPoints] = [
- pp.y for pp in thisFrame_poseDataLandMarks
- ] # PoseY data
- thisFrame_C_body[:numBodyPoints] = [
- pp.visibility for pp in thisFrame_poseDataLandMarks
- ] #'visibility' is MediaPose's 'confidence' measure in range [0,1]
- except:
- fullFrame = False
-
- # Right hand data
- try:
- thisFrame_rHandDataLandMarks = session.mediaPipeData[camNum][
- frNum
- ].right_hand_landmarks.landmark # right hand data
- thisFrame_X_righthand[:numHandPoints] = [
- pp.x for pp in thisFrame_rHandDataLandMarks
- ] # PoseX data - Normalized screen coords (in range [0, 1]) - need multiply by image resultion for pixels
- thisFrame_Y_righthand[:numHandPoints] = [
- pp.y for pp in thisFrame_rHandDataLandMarks
- ] # PoseY data
- thisFrame_C_righthand[:numHandPoints] = [
- pp.visibility for pp in thisFrame_rHandDataLandMarks
- ] #'visibility' is MediaPose's 'confidence' measure in range [0,1]
- except:
- fullFrame = False
-
- # Left hand data
- try:
- thisFrame_lHandDataLandMarks = session.mediaPipeData[camNum][
- frNum
- ].left_hand_landmarks.landmark # left hand data
- thisFrame_X_lefthand[:numHandPoints ] = [
- pp.x for pp in thisFrame_lHandDataLandMarks
- ] # PoseX data - Normalized screen coords (in range [0, 1]) - need multiply by image resultion for pixels
- thisFrame_Y_lefthand[:numHandPoints] = [
- pp.y for pp in thisFrame_lHandDataLandMarks
- ] # PoseY data
- thisFrame_C_lefthand[:numHandPoints] = [
- pp.visibility for pp in thisFrame_lHandDataLandMarks
- ] #'visibility' is MediaPose's 'confidence' measure in range [0,1]
- except:
- fullFrame = False
-
- # FaceMeshData
- try:
- thisFrame_faceDataLandMarks = session.mediaPipeData[camNum][
- frNum
- ].face_landmarks.landmark # face (mesh) data
- thisFrame_X_face[:numFacePoints] = [
- pp.x for pp in thisFrame_faceDataLandMarks
- ] # PoseX data - Normalized screen coords (in range [0, 1]) - need multiply by image resultion for pixels
- thisFrame_Y_face[:numFacePoints] = [
- pp.y for pp in thisFrame_faceDataLandMarks
- ] # PoseY data
- # NOTE - There's also Z data in here
- thisFrame_C_face[:numFacePoints] = [
- pp.visibility for pp in thisFrame_faceDataLandMarks
- ] #'visibility' is MediaPose's 'confidence' measure in range [0,1]
- except:
- fullFrame = False
-
- if fullFrame:
- f = 9
-
- thisFrame_X = np.concatenate((thisFrame_X_body,thisFrame_X_righthand,thisFrame_X_lefthand,thisFrame_X_face))
- thisFrame_Y = np.concatenate((thisFrame_Y_body,thisFrame_Y_righthand,thisFrame_Y_lefthand,thisFrame_Y_face))
- thisFrame_C = np.concatenate((thisFrame_C_body,thisFrame_C_righthand,thisFrame_C_lefthand,thisFrame_C_face))
- # stuff this frame's data into pre-allocated mediaPipeData_.... array
- mediaPipeData_nCams_nFrames_nImgPts_XYC[camNum, frNum, :, 0] = thisFrame_X
- mediaPipeData_nCams_nFrames_nImgPts_XYC[camNum, frNum, :, 1] = thisFrame_Y
- mediaPipeData_nCams_nFrames_nImgPts_XYC[camNum, frNum, :, 2] = thisFrame_C
-
-
- # convert from normalized screen coordinates to pixel coordinates
- for camera in range(numCams):
- mediaPipeData_nCams_nFrames_nImgPts_XYC[camera, :, :, 0] *= session.eachCameraResolution['Width'][camera]
- mediaPipeData_nCams_nFrames_nImgPts_XYC[camera, :, :, 1] *= session.eachCameraResolution['Height'][camera]
-
-
-
- mediaPipeData_nCams_nFrames_nImgPts_XYC[:, :, 34:, 2] = 1
-
- np.save(session.dataArrayPath / "mediaPipeData_2d.npy", mediaPipeData_nCams_nFrames_nImgPts_XYC,)
-
- return mediaPipeData_nCams_nFrames_nImgPts_XYC
-
-# #def parseMediaPipe2(session):
-
-# #numCams = len(session.mediaPipeData) #Get number of cameras
-# #numFrames = len(session.mediaPipeData[0]) #Get number of frames
-# #numBodyPoints = len(np.max(session.mediaPipeData[0][:].pose_landmarks.landmark[:]))#Get number of body points
-# #numFacePoints = len(np.max(session.mediaPipeData[0][:].face_landmarks.landmark[:]))#Get number of face points
-# #numLeftHandPoints = len(np.max(session.mediaPipeData[0][:].left_hand_landmarks.landmark[:]))#Get number of right hand points
-# #numRightHandPoints = len(np.max(session.mediaPipeData[0][:].right_hand_landmarks.landmark[:]))#Get number of left hand points
-# numBodyPoints = 33
-# numFacePoints = 468
-# numLeftHandPoints = 21
-# numRightHandPoints = 21
-
-# numPoints = numBodyPoints+numFacePoints+numLeftHandPoints+numRightHandPoints #Get total points
-# mediaPipe_nCams_nFrames_nImgPts_XYC = np.ndarray((int(session.numCams),int(session.numFrames),int(numPoints),3)) #Create empty array the size of number of cams, frame, points, XYC
-# for nn in range(session.numCams):#Loop through each camera
-# for ii in range(session.numFrames): #Loop through each frame
-# for jj in range(numBodyPoints):
-# if session.mediaPipeData[0][ii].pose_landmarks is None: #If that point is not detected
-# mediaPipe_nCams_nFrames_nImgPts_XYC[nn,ii,jj,0] = np.nan #Add nan value to that index
-# mediaPipe_nCams_nFrames_nImgPts_XYC[nn,ii,jj,1] = np.nan #Add nan value to that index
-# mediaPipe_nCams_nFrames_nImgPts_XYC[nn,ii,jj,2] = np.nan #Add nan value to that index
-# else:
-# mediaPipe_nCams_nFrames_nImgPts_XYC[nn,ii,jj,0] = session.mediaPipeData[0][ii].pose_landmarks.landmark[jj].x#Take x pos of that point
-# mediaPipe_nCams_nFrames_nImgPts_XYC[nn,ii,jj,1] = session.mediaPipeData[0][ii].pose_landmarks.landmark[jj].y#Take y pos of that point
-# mediaPipe_nCams_nFrames_nImgPts_XYC[nn,ii,jj,2] = session.mediaPipeData[0][ii].pose_landmarks.landmark[jj].visibility#Take visibility(confidence) pos of that point
-# for jj in range(numFacePoints):
-# if session.mediaPipeData[0][ii].face_landmarks is None: #If that point is not detected
-# mediaPipe_nCams_nFrames_nImgPts_XYC[nn,ii,jj+numBodyPoints,0] = np.nan #Add nan value to that index
-# mediaPipe_nCams_nFrames_nImgPts_XYC[nn,ii,jj+numBodyPoints,1] = np.nan #Add nan value to that index
-# mediaPipe_nCams_nFrames_nImgPts_XYC[nn,ii,jj+numBodyPoints,2] = np.nan #Add nan value to that index
-# else:
-# mediaPipe_nCams_nFrames_nImgPts_XYC[nn,ii,jj+numBodyPoints,0] = session.mediaPipeData[0][ii].face_landmarks.landmark[jj].x#Take x pos of that point
-# mediaPipe_nCams_nFrames_nImgPts_XYC[nn,ii,jj+numBodyPoints,1] = session.mediaPipeData[0][ii].face_landmarks.landmark[jj].y#Take y pos of that point
-# mediaPipe_nCams_nFrames_nImgPts_XYC[nn,ii,jj+numBodyPoints,2] = session.mediaPipeData[0][ii].face_landmarks.landmark[jj].visibility#Take visibility(confidence) pos of that point
-# for jj in range(numRightHandPoints):
-# if session.mediaPipeData[0][ii].right_hand_landmarks is None: #If that point is not detected
-# mediaPipe_nCams_nFrames_nImgPts_XYC[nn,ii,jj+numBodyPoints+numFacePoints,0] = np.nan #Add nan value to that index
-# mediaPipe_nCams_nFrames_nImgPts_XYC[nn,ii,jj+numBodyPoints+numFacePoints,1] = np.nan #Add nan value to that index
-# mediaPipe_nCams_nFrames_nImgPts_XYC[nn,ii,jj+numBodyPoints+numFacePoints,2] = np.nan #Add nan value to that index
-# else:
-# mediaPipe_nCams_nFrames_nImgPts_XYC[nn,ii,jj+numBodyPoints+numFacePoints,0] = session.mediaPipeData[0][ii].right_hand_landmarks.landmark[jj].x#Take x pos of that point
-# mediaPipe_nCams_nFrames_nImgPts_XYC[nn,ii,jj+numBodyPoints+numFacePoints,1] = session.mediaPipeData[0][ii].right_hand_landmarks.landmark[jj].y#Take y pos of that point
-# mediaPipe_nCams_nFrames_nImgPts_XYC[nn,ii,jj+numBodyPoints+numFacePoints,2] = session.mediaPipeData[0][ii].right_hand_landmarks.landmark[jj].visibility#Take visibility(confidence) pos of that point
-# for jj in range(numLeftHandPoints):
-# if session.mediaPipeData[0][ii].left_hand_landmarks is None: #If that point is not detected
-# mediaPipe_nCams_nFrames_nImgPts_XYC[nn,ii,jj+numBodyPoints+numFacePoints+numRightHandPoints,0] = np.nan #Add nan value to that index
-# mediaPipe_nCams_nFrames_nImgPts_XYC[nn,ii,jj+numBodyPoints+numFacePoints+numRightHandPoints,1] = np.nan #Add nan value to that index
-# mediaPipe_nCams_nFrames_nImgPts_XYC[nn,ii,jj+numBodyPoints+numFacePoints+numRightHandPoints,2] = np.nan #Add nan value to that index
-# else:
-# mediaPipe_nCams_nFrames_nImgPts_XYC[nn,ii,jj+numBodyPoints+numFacePoints+numRightHandPoints,0] = session.mediaPipeData[0][ii].left_hand_landmarks.landmark[jj].x#Take x pos of that point
-# mediaPipe_nCams_nFrames_nImgPts_XYC[nn,ii,jj+numBodyPoints+numFacePoints+numRightHandPoints,1] = session.mediaPipeData[0][ii].left_hand_landmarks.landmark[jj].y#Take y pos of that point
-# mediaPipe_nCams_nFrames_nImgPts_XYC[nn,ii,jj+numBodyPoints+numFacePoints+numRightHandPoints,2] = session.mediaPipeData[0][ii].left_hand_landmarks.landmark[jj].visibility#Take visibility(confidence) pos of that point
-# #print(session.mediaPipe_datalist[0].pose_landmarks.landmark[0].x)
-
-# #path_to_mediapipe_2d = session.dataArrayPath/'mediaPipeData_nCams_nFrames_nImgPts_XY.npy'
-
-# mediaPipeData_nCams_nFrames_nImgPts_XY = mediaPipe_nCams_nFrames_nImgPts_XYC[:,:,:,0:2].copy()
-
-# #mediaPipe_nCams_nFrames_nImgPts_XYC[:, :, :, 0] *= 640
-# #mediaPipe_nCams_nFrames_nImgPts_XYC[:, :, :, 1] *= 480
-
-# np.save(session.dataArrayPath / "mediaPipe_2d.npy", mediaPipe_nCams_nFrames_nImgPts_XYC,)
-
-# return mediaPipe_nCams_nFrames_nImgPts_XYC
\ No newline at end of file
diff --git a/freemocap/fmc_mediapipe_annotation.py b/freemocap/fmc_mediapipe_annotation.py
deleted file mode 100644
index f09ed25f..00000000
--- a/freemocap/fmc_mediapipe_annotation.py
+++ /dev/null
@@ -1,99 +0,0 @@
-import cv2
-import mediapipe as mp
-from pathlib import Path
-
-
-### mediapipe stuff
-mp_drawing = mp.solutions.drawing_utils
-mp_drawing_styles = mp.solutions.drawing_styles
-mp_holistic = mp.solutions.holistic
-
-
-def annotate_session_videos_with_mediapipe(session):
-
- annotated_video_save_path = session.sessionPath/'Annotated_Videos'
- annotated_video_save_path.mkdir(exist_ok=True)
-
- vid_count = 0
- for this_video_path in session.syncedVidPath.iterdir(): # Run MediaPipe 'Holistic' (body, hands, face) tracker on each video in the raw video folder
- if (this_video_path.suffix.lower() == ".mp4"): # NOTE - at some point we should build some list of 'synced video names' and check against that
- vid_count += 1
- name_for_saved_video = session.sessionID + '_annotated_video_{}'.format(str(vid_count)) + '.mp4'
-
- print('Annotating video {} from synced videos folder'.format(str(vid_count)))
- generate_video_with_annotation(this_video_path,annotated_video_save_path, name_for_saved_video)
-
-
-def generate_video_with_annotation(synced_video_path,path_to_save_video,name_for_saved_video):
-
- body_drawing_spec = mp_drawing.DrawingSpec(thickness=1, circle_radius=.2)
- hand_drawing_spec = mp_drawing.DrawingSpec(thickness=1, circle_radius=.2)
- face_drawing_spec = mp_drawing.DrawingSpec(thickness=1, circle_radius=.2)
-
- def annotate_image_with_mediapipe_data(image, mediapipe_results):
- mp_drawing.draw_landmarks(image=image,
- landmark_list=mediapipe_results.face_landmarks,
- connections=mp_holistic.FACEMESH_CONTOURS,
- landmark_drawing_spec=None,
- connection_drawing_spec=mp_drawing_styles
- .get_default_face_mesh_contours_style())
- mp_drawing.draw_landmarks(image=image,
- landmark_list=mediapipe_results.face_landmarks,
- # connections=mp_holistic.FACEMESH_TESSELATION,
- connections=mp_holistic.FACEMESH_CONTOURS,
- landmark_drawing_spec=None,
- connection_drawing_spec=mp_drawing_styles
- .get_default_face_mesh_tesselation_style())
- mp_drawing.draw_landmarks(image=image,
- landmark_list=mediapipe_results.pose_landmarks,
- connections=mp_holistic.POSE_CONNECTIONS,
- landmark_drawing_spec=mp_drawing_styles
- .get_default_pose_landmarks_style())
- mp_drawing.draw_landmarks(
- image=image,
- landmark_list=mediapipe_results.left_hand_landmarks,
- connections=mp_holistic.HAND_CONNECTIONS,
- landmark_drawing_spec=None,
- connection_drawing_spec=mp_drawing_styles
- .get_default_hand_connections_style())
- mp_drawing.draw_landmarks(
- image=image,
- landmark_list=mediapipe_results.right_hand_landmarks,
- connections=mp_holistic.HAND_CONNECTIONS,
- landmark_drawing_spec = None,
- connection_drawing_spec=mp_drawing_styles
- .get_default_hand_connections_style())
- return image
-
- drawing_spec = mp_drawing.DrawingSpec(thickness=1, circle_radius=1)
-
- cap = cv2.VideoCapture(str(synced_video_path))
-
- video_frame_width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
- video_frame_height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
- framerate = cap.get(cv2.CAP_PROP_FPS)
-
- writer = cv2.VideoWriter(str(path_to_save_video/name_for_saved_video),
- cv2.VideoWriter_fourcc(*'mp4v'),
- framerate,
- (video_frame_width, video_frame_height))
-
- with mp_holistic.Holistic(
- min_detection_confidence=0.5,
- min_tracking_confidence=0.5,
- model_complexity=2) as holistic:
- success = True
- while success:
- success, raw_image = cap.read()
- if not success:
- break
-
- mediapipe_results = holistic.process(raw_image)
- annotated_image = annotate_image_with_mediapipe_data(raw_image, mediapipe_results)
-
- writer.write(annotated_image)
-
- writer.release()
- cap.release()
-
-
diff --git a/freemocap/fmc_openpose.py b/freemocap/fmc_openpose.py
deleted file mode 100644
index da2994b4..00000000
--- a/freemocap/fmc_openpose.py
+++ /dev/null
@@ -1,164 +0,0 @@
-import os
-import subprocess
-import json
-
-import numpy as np
-from rich.progress import track
-from ruamel.yaml import YAML
-from pathlib import Path
-
-# from numba import jit
-
-
-def runOpenPose(session, runOpenPose=False):
- """
- Run OpenPose on synced videos, and save bdoy tracking data to be parsed
- """
- if runOpenPose:
- os.chdir(session.openPoseExePath)
-
- openPose_jsonPathList = [] # list to hold the paths to the json files
- openPose_imgPathList = []
- openPose_imgPathList_yaml = []
- openPose_jsonPathList_yaml = []
-
- for (
- thisVidPath
- ) in (
- session.syncedVidPath.iterdir()
- ): # Run OpenPose ('Windows Portable Demo') on each video in the raw video folder
- if (
- thisVidPath.suffix == ".mp4" or thisVidPath.suffix == ".MP4"
- ): # NOTE - build some list of 'synced video names' and check against that
- print("OpenPosing: ", thisVidPath.name)
- vidPath = session.openPoseDataPath / thisVidPath.stem
- jsonPath = vidPath / "json"
- jsonPath.mkdir(
- parents=True, exist_ok=True
- ) # this camera's json files (with keypoints)
- imgPath = vidPath / "img"
- imgPath.mkdir(parents=True, exist_ok=True)
- openPose_jsonPathList.append(jsonPath)
- openPose_imgPathList.append(imgPath)
- openPose_imgPathList_yaml.append(str(imgPath))
- openPose_jsonPathList_yaml.append(str(jsonPath))
- if runOpenPose:
- subprocess.run(
- [
- "bin\OpenPoseDemo.exe",
- "--video",
- str(thisVidPath),
- "--write_json",
- str(jsonPath),
- "--net_resolution",
- "-1x320",
- "--hand",
- "--face",
- "--number_people_max",
- "1",
- ],
- shell=True,
- )
- else:
- print("Skipping: ", thisVidPath.name)
- session.openPose_jsonPathList = openPose_jsonPathList
- session.openPose_imgPathList = openPose_imgPathList
-
- session.session_settings['openPose_imgPathList'] = openPose_imgPathList_yaml
- session.session_settings['openPose_jsonPathList'] = openPose_jsonPathList_yaml
- # yaml = YAML()
- # data = yaml.load(session.session_yaml_path)
- # data['openPose_imgPathList'] = openPose_imgPathList_yaml
- # data['openPose_jsonPathList'] = openPose_jsonPathList_yaml
- # yaml.dump(data, session.session_yaml_path)
-
- os.chdir(session.sessionPath)
-
-
-# @jit(nopython=True)
-def parseOpenPose(session):
- """
- Parse through saved OpenPose data and create a 2D numpy array of tracked body points
- """
- thisCamNum = -1
-
- ## %%
- #build header for dataframe - NOTE - #openpose data comes in a line ordered 'pixel x location (px)', 'pixel y (py)', 'confidence (conf)' for each keypoint
-
- dataFrameHeader = []
- bodyCols = 75
- handCols = 63 #per hand
- faceCols = 210 #das alotta face!
- headerLength = bodyCols + 2*handCols + faceCols#should be 411 for whatever version of openpose i was using on 11 Jan 2021
- numImgPoints = headerLength
-
- for bb in range(0,int(bodyCols/3)): #loop through the number of body markers (i.e. #bodyCols/3)
- dataFrameHeader.append('body_' + str(bb).zfill(3) + '_pixx')
- dataFrameHeader.append('body_' + str(bb).zfill(3) + '_pixy')
- dataFrameHeader.append('body_' + str(bb).zfill(3) + '_conf')
-
- for hr in range(0,int(handCols/3)): #loop through the number of handR markers (i.e. #handCols/3)
- dataFrameHeader.append('handR_' + str(hr).zfill(3) + '_pixx')
- dataFrameHeader.append('handR_' + str(hr).zfill(3) + '_pixy')
- dataFrameHeader.append('handR_' + str(hr).zfill(3) + '_conf')
-
- for hl in range(0,int(handCols/3)): #loop through the number of handL markers (i.e. #handCols/3)
- dataFrameHeader.append('handL_' + str(hl).zfill(3) + '_pixx')
- dataFrameHeader.append('handL_' + str(hl).zfill(3) + '_pixy')
- dataFrameHeader.append('handL_' + str(hl).zfill(3) + '_conf')
-
- for ff in range(0,int(faceCols/3)): #loop through the number of Face markers (i.e. #faceCols/3)
- dataFrameHeader.append('face_' + str(ff).zfill(3) + '_pixx')
- dataFrameHeader.append('face_' + str(ff).zfill(3) + '_pixy')
- dataFrameHeader.append('face_' + str(ff).zfill(3) + '_conf')
-
- assert len(dataFrameHeader) == headerLength, ['Header is the wrong length! Should be ' + str(headerLength) + ' but it is ' + str(len(dataFrameHeader)) + ' Check version of OpenPose?']
-
- ## %%
- ## load in data from json files
- #numFrames = int(len(list(Path(session.openPose_jsonPathList[0]).glob('*')))) #lol
- numFrames = int(session.numFrames)
- numMarkers= int(int(len(dataFrameHeader)/3))
- numCams = int(session.numCams) #rebuilding numCams here instead of using session.numCams in case
-
- openPoseData_nCams_nFrames_nImgPts_XYC = np.ndarray([numCams,numFrames,numMarkers,3]) #hardcoding for now because I am a bad person
-
- for thisCams_JsonFolderPath in track(session.openPose_jsonPathList, description='Parsing json\'s intow a dataframe (per cam)' ):
- thisCamNum += 1
- # print('Parsing into a dataframe: ', thisCams_JsonFolderPath.name )
- jsonPaths = sorted(Path(thisCams_JsonFolderPath).glob('*.json')) #glob is a "generator(?)" for paths to all the jason for THIS camara
-
- for thisJsonPath in jsonPaths: #loop throug all the json files and save their 'people' data to a dictionary (which will then be formatted into a pandas dataframe). NOTE - will be empty array if no hoomans visible in frame
- # print('loading: ', thisJsonPath.name)
- frameNum = int(thisJsonPath.stem.split('_')[-2]) #frame number we're on
- thisJsonData = json.loads(thisJsonPath.read_bytes())
- thisJsonData = thisJsonData['people'] # #FEATURE_REQUEST - at some point, we should check the openpose version (save it with the data somehow, verify everything is the same version, use different markernamlists for different versions, etc)
-
- if thisJsonData: #if this json has data
- bodyData = np.array(thisJsonData[0]['pose_keypoints_2d'])
- handRData = np.array(thisJsonData[0]['hand_right_keypoints_2d'])
- handLData = np.array(thisJsonData[0]['hand_left_keypoints_2d'])
- faceData = np.array(thisJsonData[0]['face_keypoints_2d'])
- thisFrameRow = np.hstack((bodyData,handRData, handLData, faceData)) #horizontally concatenate these arrays
- f=2
- else: #if this json is empty, just stuff it fulla NaNs
- thisFrameRow = np.empty([headerLength])
- thisFrameRow.fill(np.nan)
-
-
- assert thisFrameRow.size == headerLength, ['Header is the wrong length! Should be ' + str(headerLength) + ' but it is ' + str(thisFrameRow.size) + ' Check version of OpenPose?']
-
- if frameNum < openPoseData_nCams_nFrames_nImgPts_XYC.shape[1]: #NOTE: THIS SHOULDN"T BE NECESSARY. CURRENT Vid Trim Methods can (apparently) produce vids with off-by-one numbers of frames
- openPoseData_nCams_nFrames_nImgPts_XYC[thisCamNum, frameNum, :, :] = np.reshape(thisFrameRow, [137,3]) #hard coding the number of OpenPose Image Points b/c I'm a bad person
-
-
-
-
- # session.dataFrameHeader = dataFrameHeader
- # session.numImgPoints = numImgPoints
- #session.numFrames = frameNum #NOTE - Need to find a safer way to get this number
-
- path_to_openpose_2d = session.dataArrayPath/'openPoseData_2d.npy'
- np.save(path_to_openpose_2d, openPoseData_nCams_nFrames_nImgPts_XYC)
-
- return openPoseData_nCams_nFrames_nImgPts_XYC
diff --git a/freemocap/fmc_origin_alignment.py b/freemocap/fmc_origin_alignment.py
deleted file mode 100644
index 9c767cbd..00000000
--- a/freemocap/fmc_origin_alignment.py
+++ /dev/null
@@ -1,232 +0,0 @@
-
-import numpy as np
-import matplotlib.pyplot as plt
-
-
-from rich.progress import track
-
-
-from freemocap import fmc_skeleton_data_holder
-
-
-def create_vector(point1,point2):
- """Put two points in, make a vector"""
- vector = point2 - point1
- return vector
-
-def calculate_translation_distance(skeleton_right_heel):
- """Take in the right heel point, and calculate the distance between the right heel and the origin"""
-
- translation_distance = skeleton_right_heel - [0,0,0]
- return translation_distance
-
-
-def translate_skeleton_frame(rotated_skeleton_data_frame, translation_distance):
- """Take in a frame of rotated skeleton data, and apply the translation distance to each point in the skeleton"""
-
- translated_skeleton_frame = rotated_skeleton_data_frame - translation_distance
- return translated_skeleton_frame
-
-def calculate_skewed_symmetric_cross_product(cross_product_vector):
- skew_symmetric_cross_product = np.array([[0, -cross_product_vector[2], cross_product_vector[1]],
- [cross_product_vector[2], 0, -cross_product_vector[0]],
- [-cross_product_vector[1], cross_product_vector[0], 0]])
- return skew_symmetric_cross_product
-
-
-def calculate_rotation_matrix(vector1,vector2):
- """Put in two vectors to calculate the rotation matrix between those two vectors"""
- #based on the code found here: https://math.stackexchange.com/questions/180418/calculate-rotation-matrix-to-align-vector-a-to-vector-b-in-3d"""
-
- identity_matrix = np.identity(3)
- vector_cross_product = np.cross(vector1,vector2)
- vector_dot_product = np.dot(vector1,vector2)
- skew_symmetric_cross_product = calculate_skewed_symmetric_cross_product(vector_cross_product)
- rotation_matrix = identity_matrix + skew_symmetric_cross_product + (np.dot(skew_symmetric_cross_product,skew_symmetric_cross_product))*(1 - vector_dot_product)/(np.linalg.norm(vector_cross_product)**2)
-
- return rotation_matrix
-
-def rotate_point(point,rotation_matrix):
- rotated_point = np.dot(rotation_matrix,point)
- return rotated_point
-
-def rotate_skeleton_frame(this_frame_aligned_skeleton_data, rotation_matrix):
- """Take in a frame of skeleton data, and apply the rotation matrix to each point in the skeleton"""
-
- this_frame_rotated_skeleton = np.zeros(this_frame_aligned_skeleton_data.shape) #initialize the array to hold the rotated skeleton data for this frame
- num_tracked_points = this_frame_aligned_skeleton_data.shape[0]
-
- for i in range(num_tracked_points):
- this_frame_rotated_skeleton[i,:] = rotate_point(this_frame_aligned_skeleton_data[i,:],rotation_matrix)
-
- return this_frame_rotated_skeleton
-
-
-def align_skeleton_with_origin(skeleton_data, skeleton_indices ,good_frame, debug = False):
-
- #skeleton_type_to_plot = session_info['skeleton_type']
-
- #save_file = this_freemocap_data_array_path/'{}_origin_aligned_skeleton_3D.npy'.format(skeleton_type_to_plot)
-
- origin = np.array([0, 0, 0])
- x_axis = np.array([1, 0, 0])
- y_axis = np.array([0, 1, 0])
- z_axis = np.array([0, 0, 1])
-
- x_vector = create_vector(origin,x_axis)
- y_vector = create_vector(origin,y_axis)
- z_vector = create_vector(origin,z_axis)
-
- #origin_normal = create_normal_vector(x_vector,y_vector) #create a normal vector to the origin (basically the z axis)
- origin_normal_unit_vector = z_vector #note - this is kinda unncessary because the origin normal unit vector == original normal vector
-
- num_frames = skeleton_data.shape[0]
-
- #Original Raw Data
- raw_skeleton_holder = fmc_skeleton_data_holder.SkeletonDataHolder(skeleton_data, skeleton_indices, good_frame)
-
- raw_good_frame_skeleton_data = raw_skeleton_holder.good_frame_skeleton_data
- raw_mid_hip_XYZ = raw_skeleton_holder.mid_hip_XYZ
- raw_spine_unit_vector = raw_skeleton_holder.spine_unit_vector
-
- #Translating Data
- mid_hip_translation_distance = calculate_translation_distance(raw_mid_hip_XYZ)
- hip_translated_skeleton_data = np.zeros(skeleton_data.shape)
- foot_translated_skeleton_data = hip_translated_skeleton_data.copy()
-
- for frame in track(range(num_frames), description = 'Translating Skeleton Hips to Origin'):
- hip_translated_skeleton_data[frame,:,:] = translate_skeleton_frame(skeleton_data[frame,:,:],mid_hip_translation_distance) #translate the skeleton data for each frame
-
- hip_translated_skeleton_holder = fmc_skeleton_data_holder.SkeletonDataHolder(hip_translated_skeleton_data, skeleton_indices, good_frame)
- hip_translated_mid_foot_XYZ = hip_translated_skeleton_holder.mid_foot_XYZ
-
- mid_foot_translated_distance = calculate_translation_distance(hip_translated_mid_foot_XYZ)
-
- for frame in track (range(num_frames), description = 'Translating Skeleton Feet to Origin'):
- foot_translated_skeleton_data[frame,:,:] = translate_skeleton_frame(hip_translated_skeleton_data[frame,:,:],mid_foot_translated_distance)
-
- foot_translated_skeleton_holder = fmc_skeleton_data_holder.SkeletonDataHolder(foot_translated_skeleton_data, skeleton_indices, good_frame)
- foot_translated_good_frame_skeleton_data = foot_translated_skeleton_holder.good_frame_skeleton_data
-
- foot_translated_mid_hip_XYZ = foot_translated_skeleton_holder.mid_hip_XYZ
- foot_translated_spine_unit_vector = foot_translated_skeleton_holder.spine_unit_vector
-
- foot_translated_heel_unit_vector = foot_translated_skeleton_holder.heel_unit_vector
- foot_translated_heel_vector_origin = foot_translated_skeleton_holder.heel_vector_origin
-
- #Rotating for +y alignment
-
- rotation_matrix_to_align_skeleton_with_positive_y = calculate_rotation_matrix(foot_translated_heel_unit_vector,-1*x_vector)
-
- y_aligned_skeleton_data = np.zeros(skeleton_data.shape)
-
- for frame in track(range(num_frames), description = 'Rotating Feet to Align with Positive Y'):
- y_aligned_skeleton_data [frame,:,:] = rotate_skeleton_frame(foot_translated_skeleton_data[frame,:,:],rotation_matrix_to_align_skeleton_with_positive_y)
-
- y_aligned_skeleton_holder = fmc_skeleton_data_holder.SkeletonDataHolder(y_aligned_skeleton_data, skeleton_indices, good_frame)
- y_aligned_good_frame_skeleton_data = y_aligned_skeleton_holder.good_frame_skeleton_data
-
- y_aligned_mid_hip_XYZ = y_aligned_skeleton_holder.mid_hip_XYZ
- y_aligned_spine_unit_vector = y_aligned_skeleton_holder.spine_unit_vector
-
- y_aligned_heel_unit_vector = y_aligned_skeleton_holder.heel_unit_vector
- y_aligned_heel_vector_origin = y_aligned_skeleton_holder.heel_vector_origin
-
- #Rotating for spine alignment
-
- spine_aligned_skeleton_data = np.zeros(skeleton_data.shape)
-
- rotation_matrix_to_align_spine = calculate_rotation_matrix(y_aligned_spine_unit_vector,origin_normal_unit_vector)
-
- for frame in track(range(num_frames), description = 'Rotating Spine to Align with Positive Z'):
- spine_aligned_skeleton_data [frame,:,:] = rotate_skeleton_frame(y_aligned_skeleton_data[frame,:,:],rotation_matrix_to_align_spine)
-
- spine_aligned_skeleton_holder = fmc_skeleton_data_holder.SkeletonDataHolder(spine_aligned_skeleton_data, skeleton_indices, good_frame)
- spine_aligned_good_frame_skeleton_data = spine_aligned_skeleton_holder.good_frame_skeleton_data
-
- spine_aligned_mid_hip_XYZ = spine_aligned_skeleton_holder.mid_hip_XYZ
- spine_aligned_spine_unit_vector = spine_aligned_skeleton_holder.spine_unit_vector
-
- spine_aligned_heel_unit_vector = spine_aligned_skeleton_holder.heel_unit_vector
- spine_aligned_heel_vector_origin = spine_aligned_skeleton_holder.heel_vector_origin
-
-
-
-
- if debug:
- def plot_origin_vectors(plot_ax,x_vector,y_vector,z_vector,origin):
- Zvector_X,Zvector_Y,Zvector_Z = zip(origin_normal_unit_vector*800)
- Xvector_X,Xvector_Y,Xvector_Z = zip(x_vector*800)
- Yvector_X,Yvector_Y,Yvector_Z = zip(y_vector*800)
-
- Origin_X,Origin_Y,Origin_Z = zip(origin)
-
- plot_ax.quiver(Origin_X,Origin_Y,Origin_Z,Zvector_X,Zvector_Y,Zvector_Z,arrow_length_ratio=0.1,color='b', label = 'Z-axis')
- plot_ax.quiver(Origin_X,Origin_Y,Origin_Z,Xvector_X,Xvector_Y,Xvector_Z,arrow_length_ratio=0.1,color='r', label = 'X-axis')
- plot_ax.quiver(Origin_X,Origin_Y,Origin_Z,Yvector_X,Yvector_Y,Yvector_Z,arrow_length_ratio=0.1,color='g', label = 'Y-axis')
-
- def set_axes_ranges(plot_ax,skeleton_data, ax_range):
-
- mx = np.nanmean(skeleton_data[:,0])
- my = np.nanmean(skeleton_data[:,1])
- mz = np.nanmean(skeleton_data[:,2])
-
- plot_ax.set_xlim(mx-ax_range,mx+ax_range)
- plot_ax.set_ylim(my-ax_range,my+ax_range)
- plot_ax.set_zlim(mz-ax_range,mz+ax_range)
-
- def plot_spine_unit_vector(plot_ax,skeleton_data,skeleton_mid_hip_XYZ,skeleton_spine_unit_vector):
-
- skeleton_spine_unit_x, skeleton_spine_unit_y, skeleton_spine_unit_z = zip(skeleton_spine_unit_vector*800)
-
- plot_ax.quiver(skeleton_mid_hip_XYZ[0],skeleton_mid_hip_XYZ[1],skeleton_mid_hip_XYZ[2], skeleton_spine_unit_x,skeleton_spine_unit_y,skeleton_spine_unit_z,arrow_length_ratio=0.1,color='pink')
-
- def plot_heel_unit_vector(plot_ax,skeleton_heel_unit_vector, heel_vector_origin_XYZ):
-
- origin_heel_x, origin_heel_y, origin_heel_z = zip(heel_vector_origin_XYZ)
-
- skeleton_heel_unit_x, skeleton_heel_unit_y, skeleton_heel_unit_z = zip(skeleton_heel_unit_vector*500)
-
- plot_ax.quiver(origin_heel_x,origin_heel_y,origin_heel_z, skeleton_heel_unit_x,skeleton_heel_unit_y,skeleton_heel_unit_z,arrow_length_ratio=0.1,color='orange')
-
-
- figure = plt.figure()
- ax1 = figure.add_subplot(221,projection = '3d')
- ax2 = figure.add_subplot(222,projection = '3d')
- ax3 = figure.add_subplot(223,projection = '3d')
- ax4 = figure.add_subplot(224,projection = '3d')
-
- ax1.set_title('Original Skeleton')
- ax2.set_title('Skeleton Translated to Origin')
- ax3.set_title('Skeleton Rotated to Make +Y Forwards')
- ax4.set_title('Skeleton Rotated to Make +Z Up')
-
- ax_range = 1800
-
- set_axes_ranges(ax1,raw_good_frame_skeleton_data,ax_range)
- ax1.scatter(raw_good_frame_skeleton_data[:,0],raw_good_frame_skeleton_data[:,1],raw_good_frame_skeleton_data[:,2],c='r')
- plot_origin_vectors(ax1,x_vector,y_vector,z_vector,origin)
- plot_spine_unit_vector(ax1,raw_good_frame_skeleton_data,raw_mid_hip_XYZ,raw_spine_unit_vector)
-
- set_axes_ranges(ax2,foot_translated_good_frame_skeleton_data,ax_range)
- plot_origin_vectors(ax2,x_vector,y_vector,z_vector,origin)
- ax2.scatter(foot_translated_good_frame_skeleton_data[:,0],foot_translated_good_frame_skeleton_data[:,1],foot_translated_good_frame_skeleton_data[:,2],c='r')
- plot_heel_unit_vector(ax2,foot_translated_heel_unit_vector,foot_translated_heel_vector_origin)
-
- set_axes_ranges(ax3,y_aligned_good_frame_skeleton_data,ax_range)
- plot_origin_vectors(ax3,x_vector,y_vector,z_vector,origin)
- ax3.scatter(y_aligned_good_frame_skeleton_data[:,0],y_aligned_good_frame_skeleton_data[:,1],y_aligned_good_frame_skeleton_data[:,2],c='r')
- plot_heel_unit_vector(ax3,y_aligned_heel_unit_vector,y_aligned_heel_vector_origin)
- plot_spine_unit_vector(ax3,y_aligned_good_frame_skeleton_data,y_aligned_mid_hip_XYZ,y_aligned_spine_unit_vector)
- ax3.legend()
-
- set_axes_ranges(ax4,spine_aligned_good_frame_skeleton_data,ax_range)
- plot_origin_vectors(ax4,x_vector,y_vector,z_vector,origin)
- ax4.scatter(spine_aligned_good_frame_skeleton_data[:,0],spine_aligned_good_frame_skeleton_data[:,1],spine_aligned_good_frame_skeleton_data[:,2],c='r')
- plot_heel_unit_vector(ax4,spine_aligned_heel_unit_vector,spine_aligned_heel_vector_origin)
- plot_spine_unit_vector(ax4,spine_aligned_good_frame_skeleton_data,spine_aligned_mid_hip_XYZ,spine_aligned_spine_unit_vector)
-
- plt.show()
-
- return spine_aligned_skeleton_data
-
diff --git a/freemocap/fmc_pyqtgraph.py b/freemocap/fmc_pyqtgraph.py
deleted file mode 100644
index f4fff34c..00000000
--- a/freemocap/fmc_pyqtgraph.py
+++ /dev/null
@@ -1,472 +0,0 @@
-from pyqtgraph.Qt import QtCore, QtGui
-import pyqtgraph.opengl as gl
-import pyqtgraph as pg
-import pyqtgraph.console
-from pyqtgraph.dockarea import Dock, DockArea
-import cv2
-
-import numpy as np
-from pathlib import Path
-import sys
-
-
-class PlaySkeletonWidget:
- def __init__(self, session):
-
- # set up PyQT widget (the window that pops up and shows the plots, I think ? cribbed from - https://gist.github.com/markjay4k/da2f55e28514be7160a7c5fbf95bd243)
- # self.app = QtGui.QApplication(sys.argv)
- self.Skel3dViewWidget = gl.GLViewWidget()
- self.Skel3dViewWidget.opts["distance"] = 2000
- self.Skel3dViewWidget.setWindowTitle("SessionID: {}".format(session.sessionID))
- self.Skel3dViewWidget.setGeometry(0, 110, 1920, 1080)
- self.Skel3dViewWidget.show()
-
- # load data to be plotted
- self.useOpenPose = session.useOpenPose
- if self.useOpenPose:
- self.skel_fr_mar_xyz = np.load(
- session.dataArrayPath / "openPoseSkel_3d.npy"
- )
- self.skelScatterItem = gl.GLScatterPlotItem(
- pos=self.skel_fr_mar_xyz, color=(1, 0, 1, 0.8), size=10, pxMode=False
- )
-
- self.Skel3dViewWidget.addItem(self.skelScatterItem)
-
- elif session.useMediaPipe:
- self.skel_fr_mar_xyz = np.load(
- session.dataArrayPath / "mediaPipeSkel_3d.npy"
- )
- self.skelScatterItem = gl.GLScatterPlotItem(
- pos=self.skel_fr_mar_xyz, color=(1, 0, 1, 0.8), size=10, pxMode=False
- )
-
- self.Skel3dViewWidget.addItem(self.skelScatterItem)
-
- # make skeleton line plots (numbers specify what order to connects the dots)
- # self.head = [17, 15, 0, 1, 0, 16, 18]
- # self.spine = [1, 8]
- # self.rArm = [17, 15, 0, 16, 18]
- # self.rArm = [4, 3, 2, 1]
- # self.lArm = [1, 5, 6, 7]
- # self.rLeg = [11, 10, 9, 8]
- # self.lLeg = [14, 13, 12, 8]
- # self.rFoot = [11, 23, 22, 11, 24]
- # self.lFoot = [14, 20, 19, 14, 21]
-
- # # Make some handy maps ;D
- # rHandIDstart = 25
- # lHandIDstart = rHandIDstart + 21
-
- # self.rHand = (
- # np.array(
- # [
- # 0,
- # 1,
- # 2,
- # 3,
- # 4,
- # False,
- # 0,
- # 5,
- # 6,
- # 7,
- # 8,
- # False,
- # 0,
- # 9,
- # 10,
- # 11,
- # 12,
- # False,
- # 0,
- # 13,
- # 14,
- # 15,
- # 16,
- # False,
- # 0,
- # 17,
- # 18,
- # 19,
- # 20,
- # ]
- # )
- # + rHandIDstart
- # )
- # self.lHand = self.rHand + lHandIDstart
-
- # self.headLineItem = gl.GLLinePlotItem(
- # pos=self.skel_fr_mar_xyz[:, self.head, :],
- # color=(1, 1, 1, 0.2),
- # width=4.0,
- # antialias=True,
- # )
- # self.Skel3dViewWidget.addItem(self.headLineItem)
-
- # self.spineLineItem = gl.GLLinePlotItem(
- # pos=self.skel_fr_mar_xyz[:, self.spine, :],
- # color=(1, 1, 1, 0.9),
- # width=4.0,
- # antialias=True,
- # )
- # self.Skel3dViewWidget.addItem(self.spineLineItem)
-
- # self.rArmLineItem = gl.GLLinePlotItem(
- # pos=self.skel_fr_mar_xyz[:, self.rArm, :],
- # color=(1, 0.2, 0.15, 0.9),
- # width=4.0,
- # antialias=True,
- # )
- # self.Skel3dViewWidget.addItem(self.rArmLineItem)
-
- # self.lArmLineItem = gl.GLLinePlotItem(
- # pos=self.skel_fr_mar_xyz[:, self.lArm, :],
- # color=(0.4, 0.6, 1, 0.9),
- # width=4.0,
- # antialias=True,
- # )
- # self.Skel3dViewWidget.addItem(self.lArmLineItem)
-
- # self.rLegLineItem = gl.GLLinePlotItem(
- # pos=self.skel_fr_mar_xyz[:, self.rLeg, :],
- # color=(1, 0.2, 0.15, 0.9),
- # width=4.0,
- # antialias=True,
- # )
- # self.Skel3dViewWidget.addItem(self.rLegLineItem)
-
- # self.lLegLineItem = gl.GLLinePlotItem(
- # pos=self.skel_fr_mar_xyz[:, self.lLeg, :],
- # color=(0.4, 0.6, 1, 0.9),
- # width=4.0,
- # antialias=True,
- # )
- # self.Skel3dViewWidget.addItem(self.lLegLineItem)
-
- # self.rFootLineItem = gl.GLLinePlotItem(
- # pos=self.skel_fr_mar_xyz[:, self.rFoot, :],
- # color=(1, 0.2, 0.15, 0.9),
- # width=4.0,
- # antialias=True,
- # )
- # self.Skel3dViewWidget.addItem(self.rFootLineItem)
-
- # self.lFootLineItem = gl.GLLinePlotItem(
- # pos=self.skel_fr_mar_xyz[:, self.lFoot, :],
- # color=(0.4, 0.6, 1, 0.9),
- # width=4.0,
- # antialias=True,
- # )
- # self.Skel3dViewWidget.addItem(self.lFootLineItem)
-
- # # plot handybois
- # self.rHandLineItem = gl.GLLinePlotItem(
- # pos=self.skel_fr_mar_xyz[:, self.rHand, :],
- # color=(0.2, 0.4, 1, 0.9),
- # width=1.0,
- # antialias=True,
- # )
- # # self.Skel3dViewWidget.addItem(self.rHandLineItem)
-
- # self.lHandLineItem = gl.GLLinePlotItem(
- # pos=self.skel_fr_mar_xyz[:, self.lHand, :],
- # color=(1, 0.1, 0.05, 0.9),
- # width=1.0,
- # antialias=True,
- # )
- # # self.Skel3dViewWidget.addItem(self.lHandLineItem)
-
- self.useDLC = session.useDLC
- if self.useDLC:
- # self.dlc_fr_mar_xyz = np.load(session.dataArrayPath/'mediaPipeSkel_3d.npy')
- self.dlc_fr_mar_xyz = np.load(session.dataArrayPath / "deepLabCut_3d.npy")
- self.dlcScatterItem = gl.GLScatterPlotItem(
- pos=self.dlc_fr_mar_xyz, color=(1, 0, 0, 0.8), size=60, pxMode=False
- )
- self.Skel3dViewWidget.addItem(self.dlcScatterItem)
-
- self.dlc0LineItem = gl.GLLinePlotItem(
- pos=self.dlc_fr_mar_xyz[:, 0, :],
- color=(0, 1, 1, 0.5),
- width=4.0,
- antialias=True,
- )
- self.dlc1LineItem = gl.GLLinePlotItem(
- pos=self.dlc_fr_mar_xyz[:, 1, :],
- color=(1, 0, 1, 0.5),
- width=4.0,
- antialias=True,
- )
- self.dlc2LineItem = gl.GLLinePlotItem(
- pos=self.dlc_fr_mar_xyz[:, 2, :],
- color=(1, 1, 0, 0.5),
- width=4.0,
- antialias=True,
- )
-
- self.Skel3dViewWidget.addItem(self.dlc0LineItem)
- self.Skel3dViewWidget.addItem(self.dlc1LineItem)
- self.Skel3dViewWidget.addItem(self.dlc2LineItem)
-
- self.tailLength = 10
-
- self.charuco_mar_dim = np.load(session.dataArrayPath/'charuco_3d_points.npy')
- self.charucoScatterItem = gl.GLScatterPlotItem(pos=self.charuco_mar_dim, color=(1,1,1,.8), size=10, pxMode=False)
- self.Skel3dViewWidget.addItem(self.charucoScatterItem)
-
- # plot videos Frames!
-
- # set frame counter
- self.currentFrameNumber = 0
- self.framerate = 50 # frames per second
- self.frameDuration = 1000 / self.framerate # milliseconds
-
- # def start(self):
- # if (sys.flags.interactive != 1) or not hasattr(QtCore, 'PYQT_VERSION'):
- # QtGui.QApplication.instance().exec_()
-
- def update(self):
-
- # Plots up Mr. Skreleton :D
- # Plots the dots
-
- self.skelScatterItem.setData(
- pos=self.skel_fr_mar_xyz[self.currentFrameNumber, :, :]
- )
-
- # connect the dottos
- if self.useOpenPose:
- self.headLineItem.setData(
- pos=self.skel_fr_mar_xyz[self.currentFrameNumber, self.head, :]
- )
- self.spineLineItem.setData(
- pos=self.skel_fr_mar_xyz[self.currentFrameNumber, self.spine, :]
- )
- self.rArmLineItem.setData(
- pos=self.skel_fr_mar_xyz[self.currentFrameNumber, self.rArm, :]
- )
- self.lArmLineItem.setData(
- pos=self.skel_fr_mar_xyz[self.currentFrameNumber, self.lArm, :]
- )
- self.rLegLineItem.setData(
- pos=self.skel_fr_mar_xyz[self.currentFrameNumber, self.rLeg, :]
- )
- self.lLegLineItem.setData(
- pos=self.skel_fr_mar_xyz[self.currentFrameNumber, self.lLeg, :]
- )
- self.rFootLineItem.setData(
- pos=self.skel_fr_mar_xyz[self.currentFrameNumber, self.rFoot, :]
- )
- self.lFootLineItem.setData(
- pos=self.skel_fr_mar_xyz[self.currentFrameNumber, self.lFoot, :]
- )
-
- self.rHandLineItem.setData(
- pos=self.skel_fr_mar_xyz[self.currentFrameNumber, self.rHand, :]
- )
- self.lHandLineItem.setData(
- pos=self.skel_fr_mar_xyz[self.currentFrameNumber, self.lHand, :]
- )
-
- if self.useDLC:
- # Plot DeepLabCut data
- self.dlcScatterItem.setData(
- pos=self.dlc_fr_mar_xyz[self.currentFrameNumber, :, :]
- )
-
- if self.currentFrameNumber > self.tailLength:
- self.tailIndexes = range(
- self.currentFrameNumber - self.tailLength, self.currentFrameNumber
- )
- self.dlc0LineItem.setData(
- pos=self.dlc_fr_mar_xyz[self.tailIndexes, 0, :]
- )
- self.dlc1LineItem.setData(
- pos=self.dlc_fr_mar_xyz[self.tailIndexes, 1, :]
- )
- self.dlc2LineItem.setData(
- pos=self.dlc_fr_mar_xyz[self.tailIndexes, 2, :]
- )
-
- self.currentFrameNumber += 1
- if self.currentFrameNumber >= self.skel_fr_mar_xyz.shape[0]:
- self.currentFrameNumber = 0
-
- def animate(self):
- timer = QtCore.QTimer()
- timer.timeout.connect(self.update)
- # timer.start(self.frameDuration)
- timer.start(0)
- # self.start()
-
-
-class VideoWindowWidget:
- def __init__(self, vidNum, videoPath, session):
- # set up video capture
- self.vidCap = cv2.VideoCapture(str(videoPath))
- success, image = self.vidCap.read()
- self.vidCap.set(
- cv2.CAP_PROP_POS_FRAMES, 0
- ) # reset video capture so things start on the first frame
-
- self.videoWidget = pg.GraphicsLayoutWidget()
- self.videoWidget.show() ## show widget alone in its own window
- self.videoWidget.setWindowTitle("Video Name")
- self.view = self.videoWidget.addViewBox()
- ## lock the aspect ratio so pixels are always square
- self.view.setAspectLocked(True)
-
- ## Create image item
- self.imgItem = pg.ImageItem(border="w")
- self.view.addItem(self.imgItem)
-
- ## Set initial view bounds
- self.view.setRange(QtCore.QRectF(0, 0, image.shape[0], image.shape[1]))
-
- # set image, I guess?
- self.imgItem.setImage(image)
-
- def update(self):
- success, image = self.vidCap.read()
-
- if success:
- image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
- image = cv2.rotate(image, cv2.ROTATE_90_CLOCKWISE)
- self.imgItem.setImage(image)
- else:
- self.vidCap.set(
- cv2.CAP_PROP_POS_FRAMES, 0
- ) # reset video capture so video will loop
- success, image = self.vidCap.read()
- self.imgItem.setImage(image)
-
-
-class PlayerDockedWindow:
- def __init__(self, session, displayVid):
-
- app = pg.mkQApp("DockArea Example")
- self.displayVid = displayVid
- self.win = QtGui.QMainWindow()
- area = DockArea()
- self.win.setCentralWidget(area)
- winHeight = 1000
- winWidth = 1900
- self.win.resize(winHeight, winWidth)
- self.win.setWindowTitle("FreeMoCap")
-
- ## Create docks, place them into the window one at a time.
- ## Note that size arguments are only a suggestion; docks will still have to
- ## fill the entire dock area and obey the limits of their internal widgets.
-
- self.VidPathList = []
- self.dock_name_dictionary = {}
-
- if displayVid == 0:
- path_to_search = session.syncedVidPath
- elif displayVid == 1:
- path_to_search = session.openPoseDataPath
- for count, vidPath in enumerate(path_to_search.glob("*.mp4")):
- self.VidPathList.append(vidPath)
- # dock_name = 'dock_video{}'.format(count)
-
- dock_name = count
- self.dock_name_dictionary[dock_name] = None
-
- dock_3dView = Dock(
- "Session: {}".format(session.sessionID), size=(1, 1), closable=True
- ) ## give this dock the minimum possible size
- dock_Console = Dock(
- "Dock2 - Console", size=(winHeight, winWidth), closable=True
- )
-
- for key in self.dock_name_dictionary:
- self.dock_name_dictionary[key] = Dock(str(key), size=(1, 1), closable=True)
- # dock_video0 = Dock("Video0", size=(1,1), closable=True)
- # dock_video1 = Dock("Video1", size=(1,1), closable=True)
- # dock_video2 = Dock("Video2", size=(1,1), closable=True)
- # dock_video3 = Dock("Video3", size=(1,1), closable=True)
-
- area.addDock(
- dock_3dView, "left"
- ) ## place d1 at left edge of dock area (it will fill the whole space since there are no other docks yet)
- direction_list = ["top", "left", "bottom", "top"]
- for key, value in self.dock_name_dictionary.items():
- if (key % 2) == 0:
- area.addDock(value, "right")
- previous_dock = value
- else:
- area.addDock(value, "bottom", previous_dock)
- # previous_dock = value
-
- # area.addDock(dock_video0, 'right') ## place d2 at right edge of dock area
- # area.addDock(dock_video1, 'right', dock_video0)## place d3 at bottom edge of d1
- # area.addDock(dock_video2, 'bottom',dock_video0) ## place d4 at right edge of dock area
- # area.addDock(dock_video3, 'left', dock_video2) ## place d5 at left edge of d1
- # area.moveDock(dock_video1, 'right', dock_video0)
-
- ## Add widgets into each dock
-
- ## first dock gets save/restore buttons
- w1 = pg.LayoutWidget()
- label = QtGui.QLabel(
- """ -- DockArea Example --
- This window has 6 Dock widgets in it. Each dock can be dragged
- by its title bar to occupy a different space within the window
- but note that one dock has its title bar hidden). Additionally,
- the borders between docks may be dragged to resize. Docks that are dragged on top
- of one another are stacked in a tabbed layout. Double-click a dock title
- bar to place it in its own window.
- """
- )
-
- w2 = pg.console.ConsoleWidget()
- dock_Console.addWidget(w2)
-
- self.playSkel = PlaySkeletonWidget(session)
-
- dock_3dView.addWidget(self.playSkel.Skel3dViewWidget)
-
- # self.VidPathList = []
- # for vidPath in session.syncedVidPath.glob('*.mp4'):
- # self.VidPathList.append(vidPath)
- self.widget_list = []
- for key, dock_video in self.dock_name_dictionary.items():
- self.videoWidget = VideoWindowWidget(
- key, str(self.VidPathList[key]), session
- )
- self.widget_list.append(self.videoWidget)
- dock_video.addWidget(self.videoWidget.videoWidget)
- # self.video0Widget = VideoWindowWidget(0,str(self.VidPathList[0]), session)
- # dock_video0.addWidget(self.video0Widget.videoWidget )
-
- # self.video1Widget = VideoWindowWidget(1,str(self.VidPathList[1]),session)
- # dock_video1.addWidget(self.video1Widget.videoWidget )
-
- # self.video2Widget = VideoWindowWidget(2,str(self.VidPathList[2]), session)
- # dock_video2.addWidget(self.video2Widget.videoWidget )
-
- # self.video3Widget = VideoWindowWidget(3,str(self.VidPathList[3]),session)
- # dock_video3.addWidget(self.video3Widget.videoWidget )
-
- self.win.show()
-
- def update(self):
- self.playSkel.update()
- for widget in self.widget_list:
- widget.update()
-
- # self.video0Widget.update()
- # self.video1Widget.update()
- # self.video2Widget.update()
- # self.video3Widget.update()
-
- def animate(self):
- timer = QtCore.QTimer()
- timer.timeout.connect(self.update)
- timer.start(self.playSkel.frameDuration)
- self.start()
-
- def start(self):
- if (sys.flags.interactive != 1) or not hasattr(QtCore, "PYQT_VERSION"):
- QtGui.QApplication.instance().exec_()
diff --git a/freemocap/fmc_runme.py b/freemocap/fmc_runme.py
deleted file mode 100644
index e3012d02..00000000
--- a/freemocap/fmc_runme.py
+++ /dev/null
@@ -1,394 +0,0 @@
-
-from freemocap.fmc_startup import startup, startupGUI
-from freemocap.webcam import camera_settings, timesync
-
-from pathlib import Path
-import os
-import subprocess
-import time
-from aniposelib.boards import CharucoBoard
-
-import numpy as np
-from scipy.signal import savgol_filter
-
-import cv2
-
-#Rich stuff
-from rich import print
-from rich.console import Console
-console = Console()
-from rich.markdown import Markdown
-from rich.traceback import install
-install(show_locals=False)
-from rich import inspect
-from rich.padding import Padding
-
-
-from freemocap import (
- fmc_good_frame_finder,
- recordingconfig,
- runcams,
- calibrate,
- fmc_mediapipe,
- fmc_openpose,
- fmc_deeplabcut,
- fmc_origin_alignment,
- fmc_mediapipe_annotation,
- fmc_skeleton_data_holder,
- reconstruct3D,
- play_skeleton_animation,
- session,
-
-)
-
-
-
-thisStage = 0 #global
-
-# TODO: Replace the below functions with the RunMe options.
-def RunMe(sessionID=None,
- stage=1,
- useOpenPose=False,
- runOpenPose = True,
- useMediaPipe=True,
- runMediaPipe=True,
- useDLC=False,
- dlcConfigPath=None,
- debug=False,
- setDataPath = False,
- userDataPath = None,
- recordVid = True,
- showAnimation = True,
- reconstructionConfidenceThreshold = .5,
- charucoSquareSize = 36,#mm - ~the size of the squares when printed on 8.5x11" paper based on parameters in ReadMe.md
- calVideoFrameLength = 1,
- startFrame = 0,
- useBlender = False,
- resetBlenderExe = False,
- get_synced_unix_timestamps = True,
- good_clean_frame_number = 0,
- use_saved_calibration = False,
- bundle_adjust_3d_points=False,
- place_skeleton_on_origin = False,
- save_annotated_videos = False,
- ):
- """
- Starts the freemocap pipeline based on either user-input values, or default values. Creates a new session class instance (called sesh)
- based on the specified inputs. Checks for previous user preferences and choices if they exist, or will prompt the user for new choices
- if they don't. Runs the initialization for the system and runs each stage of the pipeline.
- """
-
- welcome_md = Markdown("""# Welcome to FreeMoCap βœ¨πŸ’€βœ¨ """)
- console.print(welcome_md)
-
- sesh = session.Session()
-
- sesh.sessionID = sessionID
- sesh.useOpenPose= useOpenPose
- sesh.useMediaPipe = useMediaPipe
- sesh.useDLC= useDLC
- sesh.debug = debug
- sesh.setDataPath = setDataPath
- sesh.userDataPath = userDataPath
- sesh.dataFolderName = recordingconfig.dataFolder
- sesh.startFrame = startFrame
- sesh.get_synced_unix_timestamps = get_synced_unix_timestamps
- sesh.use_saved_calibration = use_saved_calibration
-
- # %% Startup
- sesh.freemocap_module_path = Path(__file__).parent
-
-
-
- startup.get_user_preferences(sesh,stage)
-
- if sesh.useDLC and stage<5:
- import deeplabcut as dlc
- dlc_config_paths = startup.get_dlc_paths(session)
-
- if stage > 1:
- startup.get_data_folder_path(sesh)
-
- if sesh.sessionID == None:
- subfolders = [f.path for f in os.scandir(sesh.dataFolderPath) if f.is_dir()] # copy-pasta from who knows where
- sesh.sessionID = Path(subfolders[-1]).stem # grab the name of the last folder in the list of subfolders
-
- console.rule()
- print('Running ' + str(sesh.sessionID) + ' from ' + str(sesh.dataFolderPath))
- console.rule()
-
- if useBlender == True:
-
- subprocessPath = sesh.freemocap_module_path/'fmc_blender.py'
- blenderPath = startup.get_blender_path(sesh,resetBlenderExe)
-
-
- board = CharucoBoard(7, 5,
- #square_length=1, # here, in mm but any unit works (JSM NOTE - just using '1' so resulting units will be in 'charuco squarelenghts`)
- #marker_length=.8,
- # square_length = 121, #big boi charuco
- # marker_length = 98,
- square_length = charucoSquareSize,#mm
- marker_length = charucoSquareSize*.8,#mm
- marker_bits=4, dict_size=250)
- sesh.board = board
-
-
-
- # %% Initialization
- if stage == 1:
- camera_settings.initialize(sesh,stage,board)
- elif stage ==2:
- timesync.time_sync_initialize(sesh)
- else:
- sesh.initialize(stage)
-
- # %% Stage One
-
- if stage <= 1:
- thisStage=1
- console.rule(style="color({})".format(14))
- console.rule('Starting Video Recordings'.upper(), style="color({})".format(14))
- console.rule(style="color({})".format(14))
-
- runcams.RecordCams(sesh, sesh.cam_inputs, sesh.parameterDictionary, sesh.rotationInputs)
- sesh.save_session()
- else:
- print('Skipping Video Recording')
-
-
- # %% Stage Two
- if stage <= 2:
- thisStage=2
- console.rule(style="color({})".format(thisStage))
- console.rule('Synchronizing Recorded Videos'.upper(),style="color({})".format(thisStage))
- console.rule(style="color({})".format(thisStage))
-
- runcams.SyncCams(sesh, sesh.timeStampData,sesh.numCamRange,sesh.vidNames,sesh.camIDs)
- sesh.save_session()
- else:
- print('Skipping Video Syncing')
-
- # %% Stage Three
- if stage <= 3:
- thisStage=3
- console.rule(style="color({})".format(thisStage))
- console.rule('Starting Capture Volume Calibration'.upper(),style="color({})".format(thisStage))
- console.rule(style="color({})".format(thisStage))
- console.print(Padding('Using Anipose to calculate 6 degree-of-freedom position (and distortion coeffs) of each camera based on detected charuco boards. This information is used to create a Camera Projection Matrix for each camera, which is later used in the 3d reconstruction stage', (1,4)), overflow="fold", justify='center',style="color({})".format(thisStage))
- console.rule('See https://anipose.org for details', style="color({})".format(thisStage))
- console.rule(style="color({})".format(thisStage))
-
- if sesh.numFrames is None:
- a_sync_vid_path = list(sesh.syncedVidPath.glob('*.mp4'))
- temp_cap = cv2.VideoCapture(str(a_sync_vid_path[0]))
- sesh.numFrames = temp_cap.get(cv2.CAP_PROP_FRAME_COUNT)
- temp_cap.release()
-
- sesh.cgroup, sesh.mean_charuco_fr_mar_xyz = calibrate.CalibrateCaptureVolume(sesh,board, calVideoFrameLength)
-
- print('Anipose Calibration Successful!')
- else:
- print('Skipping Calibration')
-
- # %% Stage Four
- if stage <= 4:
- thisStage=4
- thisStageColor=12
- console.rule(style="color({})".format(thisStageColor))
- console.rule('Starting 2D Point Trackers'.upper(),style="color({})".format(thisStageColor))
- stage4_msg ='This step implements various computer vision that track the skeleton (and other objects) in the 2d videos, to produce the data that will be combined with the `camera projection matrices` from the calibration stage to produce the estimates of 3d movement. \n \n Each algorithm is different, but most involve using [bold magenta] convolutional neural networks [/bold magenta] trained from labeled videos to produce a 2d probability map of the likelihood that the tracked bodypart/object/feature (e.g. \'LeftElbow\') is in a given location. \n \n The peak of that distrubtion on each frame is recorded as the pixel-location of that item on that frame (e.g. \'LeftElbow(pixel-x, pixel-y, confidence\') where the a confidence value proportional to the underlying probability distribution (i.e. tall peaks in the probablitiy distribution indicate high confidence that the LeftElbow actually is at this pixel-x, pixel-y location) \n \nThis part is crazy future tech sci fi stuff. Seriously unbelievable this kind of thing is possible ✨'
- console.print(Padding(stage4_msg, (1,4)), overflow="fold", justify='center',style="color({})".format(thisStageColor))
- console.rule(style="color({})".format(thisStageColor))
-
-
- if sesh.useMediaPipe:
-
- console.rule(style="color({})".format(thisStage))
- console.rule('Running MediaPipe skeleton tracker - https://google.github.io/mediapipe', style="color({})".format(thisStage))
- console.rule(style="color({})".format(thisStage))
-
- if runMediaPipe:
- fmc_mediapipe.runMediaPipe(sesh)
- sesh.mediaPipeData_nCams_nFrames_nImgPts_XYC = fmc_mediapipe.parseMediaPipe(sesh)
-
- else:
- print('`runMediaPipe` set to False, so we\'re loading MediaPipe data from npy file')
- sesh.mediaPipeData_nCams_nFrames_nImgPts_XYC = np.load(sesh.dataArrayPath/'mediaPipeData_2d.npy', allow_pickle=True)
-
- if save_annotated_videos:
- fmc_mediapipe_annotation.annotate_session_videos_with_mediapipe(sesh)
-
-
- sesh.mediaPipeSkel_fr_mar_xyz, sesh.mediaPipeSkel_reprojErr = reconstruct3D.reconstruct3D(sesh,sesh.mediaPipeData_nCams_nFrames_nImgPts_XYC, confidenceThreshold=reconstructionConfidenceThreshold)
-
- if bundle_adjust_3d_points:
- sesh.mediaPipeSkel_fr_mar_xyz_og = sesh.mediaPipeSkel_fr_mar_xyz.copy()
- np.save(sesh.dataArrayPath/'mediaPipeSkel_3d_raw.npy', sesh.mediaPipeSkel_fr_mar_xyz_og) #save data to npy
-
- from mediapipe.python.solutions import holistic as mp_holistic
- mediapipe_body_pose_connections = [this_connection for this_connection in mp_holistic.POSE_CONNECTIONS]
- with console.status('Running bundle adjustment optimization on 3d points...'):
- sesh.mediaPipeSkel_fr_mar_xyz = sesh.cgroup.optim_points(sesh.mediaPipeData_nCams_nFrames_nImgPts_XYC[:,:,:,:2],
- sesh.mediaPipeSkel_fr_mar_xyz,
- constraints=mediapipe_body_pose_connections,
- verbose=True)
- print('Done adjusting bundles!')
-
-
-
- np.save(sesh.dataArrayPath/'mediaPipeSkel_3d.npy', sesh.mediaPipeSkel_fr_mar_xyz) #save data to npy
- np.save(sesh.dataArrayPath/'mediaPipeSkel_reprojErr.npy', sesh.mediaPipeSkel_reprojErr) #save data to npy
-
- #smoooooooooth, just a bit
- smoothWinLength = 5
- smoothOrder = 3
- for dim in range(sesh.mediaPipeSkel_fr_mar_xyz.shape[2]):
- for mm in range(sesh.mediaPipeSkel_fr_mar_xyz.shape[1]):
- sesh.mediaPipeSkel_fr_mar_xyz[:,mm,dim] = savgol_filter(sesh.mediaPipeSkel_fr_mar_xyz[:,mm,dim], smoothWinLength, smoothOrder)
-
-
- if place_skeleton_on_origin:
- sesh.mediaPipeSkel_fr_mar_xyz_smoothed_unrotated = sesh.mediaPipeSkel_fr_mar_xyz.copy()
- np.save(sesh.dataArrayPath/'mediaPipeSkel_3d_smoothed_unrotated.npy', sesh.mediaPipeSkel_fr_mar_xyz_smoothed_unrotated) #save data to npy
- good_frame = fmc_good_frame_finder.find_good_frame(sesh.mediaPipeSkel_fr_mar_xyz, .6, debug = False) #.6 is an initial guess for the velocity. seems to be a safe bet for for all the cases I've tried
-
- mediapipe_indices = fmc_mediapipe.mediapipe_indices
-
- origin_aligned_skeleton_data_XYZ = fmc_origin_alignment.align_skeleton_with_origin(sesh.mediaPipeSkel_fr_mar_xyz, mediapipe_indices, good_frame, debug = False)
- np.save(sesh.dataArrayPath/'mediaPipeSkel_3d_smoothed.npy', origin_aligned_skeleton_data_XYZ) #save data to npy
-
- else:
- np.save(sesh.dataArrayPath/'mediaPipeSkel_3d_smoothed.npy', sesh.mediaPipeSkel_fr_mar_xyz)
-
-
-
-
- sesh.save_session()
-
-
- if sesh.useOpenPose:
- console.rule(style="color({})".format(thisStage))
- console.rule('Running OpenPose skeleton tracker - https://github.com/CMU-Perceptual-Computing-Lab/openpose', style="color({})".format(thisStage))
- console.rule(style="color({})".format(thisStage))
-
-
- fmc_openpose.runOpenPose(sesh, runOpenPose=runOpenPose)
- sesh.openPoseData_nCams_nFrames_nImgPts_XYC = fmc_openpose.parseOpenPose(sesh)
- sesh.openPoseSkel_fr_mar_xyz, sesh.openPoseSkel_reprojErr = reconstruct3D.reconstruct3D(sesh,sesh.openPoseData_nCams_nFrames_nImgPts_XYC, confidenceThreshold=reconstructionConfidenceThreshold)
- np.save(sesh.dataArrayPath/'openPoseSkel_3d.npy', sesh.openPoseSkel_fr_mar_xyz) #save data to npy
- np.save(sesh.dataArrayPath/'openPoseSkel_reprojErr.npy', sesh.openPoseSkel_reprojErr) #save data to npy
-
- smoothWinLength = 5
- smoothOrder = 3
- for dim in range(sesh.openPoseSkel_fr_mar_xyz.shape[2]):
- for mm in range(sesh.openPoseSkel_fr_mar_xyz.shape[1]):
- sesh.openPoseSkel_fr_mar_xyz[:,mm,dim] = savgol_filter(sesh.openPoseSkel_fr_mar_xyz[:,mm,dim], smoothWinLength, smoothOrder)
-
- np.save(sesh.dataArrayPath/'openPoseSkel_3d_smoothed.npy', sesh.openPoseSkel_fr_mar_xyz) #save data to npy
-
- sesh.save_session()
- sesh.syncedVidList = []
-
- if sesh.useDLC:
-
- console.rule(style="color({})".format(thisStage))
- console.rule('Running DeepLabCut :mouse: - https://deeplabcut.org', style="color({})".format(thisStage))
- console.rule(style="color({})".format(thisStage))
-
-
- for vid in sesh.syncedVidPath.glob('*.mp4'):
- sesh.syncedVidList.append(str(vid))
-
- for config_path in dlc_config_paths:
- dlc.analyze_videos(config_path,sesh.syncedVidList, destfolder= sesh.dlcDataPath, save_as_csv=True)
- sesh.dlcData_nCams_nFrames_nImgPts_XYC = fmc_deeplabcut.parseDeepLabCut(sesh, config_path)
- sesh.dlc_fr_mar_xyz, sesh.dlc_reprojErr = reconstruct3D.reconstruct3D(sesh,sesh.dlcData_nCams_nFrames_nImgPts_XYC, confidenceThreshold=reconstructionConfidenceThreshold)
- np.save(sesh.dataArrayPath/'deepLabCut_3d.npy', sesh.dlc_fr_mar_xyz) #save data to npy
- np.save(sesh.dataArrayPath/'deepLabCut_reprojErr.npy', sesh.dlc_reprojErr) #save data to npy
- sesh.save_session()
- else:
-
- print('Skipping 2d point tracking')
-
-
- # %% Stage 5 - Use Blender to create output data files
- if stage <=5:
-
-
- try:
- if useBlender == True:
- thisStage=5
- console.rule(style="color({})".format(thisStage))
- console.rule('Exporting Files...'.upper(), style="color({})".format(thisStage))
- console.rule('Hijacking Blender\'s file format converters to export FreeMoCap data as various file format (.blend, .usd, .gltf, .fbx)', style="color({})".format(thisStage))
- console.rule(style="color({})".format(thisStage))
-
- path_to_this_py_file = Path(__file__).parent.resolve()
- fmc_blender_script_path = path_to_this_py_file /'freemocap_blender_megascript.py'
-
- command_str = str(blenderPath) + " --background" + " --python " + str(fmc_blender_script_path) + " -- " + str(sesh.sessionPath) +' ' + str(good_clean_frame_number)
- # command_str = [str(blenderPath), "--background", "--python", str(fmc_blender_script_path), "--", str(sesh.sessionPath)]
- blender_process = subprocess.Popen(
- command_str,
- shell=False,
- stdout=subprocess.PIPE,
- stderr=subprocess.PIPE
- )
- while True:
- output = blender_process.stdout.readline()
- if blender_process.poll() is not None:
- break
- if output:
- print(output.strip().decode())
-
- if blender_process.returncode == 0:
- print("Blender returned an error:")
- print(blender_process.stderr.read().decode())
-
-
-
- except:
- console.print_exception()
-
-
- # %% Stage 6 - Make Animation
- if stage <= 6:
- thisStage=6
- console.rule(style="color({})".format(thisStage))
- console.rule('Creating the Skreleton animation!'.upper(),style="color({})".format(thisStage))
- console.print('The video creation is very slow. All of the animation making code is crazy slow, tbh. Sorry about that, future iterations will be better lol :sweat_smile:',overflow="fold", justify='center',style="color({})".format(thisStage))
- console.rule(style="color({})".format(thisStage))
-
-
-
- play_skeleton_animation.PlaySkeletonAnimation(
- sesh,
- startFrame=sesh.startFrame,
- azimuth=-90,
- elevation=-81,
- useOpenPose=useOpenPose,
- useMediaPipe=useMediaPipe,
- useDLC=useDLC,
- recordVid = recordVid,
- showAnimation=showAnimation,
- )
- console.rule(style="color({})".format(thisStage))
- else:
- print('Skipping Skeleton Plotting')
-
-
- console.rule(style="color({})".format(13))
- console.rule('All Done!'.upper(), style="color({})".format(13))
- console.rule(style="color({})".format(13))
- console.rule('Session Data folder is at: ', style="color({})".format(13))
- console.rule(str(sesh.sessionPath), style="color({})".format(13))
- console.rule(style="color({})".format(13))
- console.rule(style="color({})".format(10))
- console.rule("Thank you for supporting the FreeMoCap Project", style="color({})".format(10))
- console.rule(style="color({})".format(10))
- console.rule(style="color({})".format(13))
- console.print('~βœ¨πŸ’€βœ¨~',justify="center")
- console.print('❀️', justify="center")
- console.rule(style="color({})".format(13))
- console.rule(style="color({})".format(14))
diff --git a/freemocap/fmc_skeleton_data_holder.py b/freemocap/fmc_skeleton_data_holder.py
deleted file mode 100644
index b3f41428..00000000
--- a/freemocap/fmc_skeleton_data_holder.py
+++ /dev/null
@@ -1,100 +0,0 @@
-
-import numpy as np
-
-
-
-
-class SkeletonDataHolder:
- def __init__(self, skeleton_data, skeleton_indices_list,good_frame):
- self.skeleton_data = skeleton_data
- self.skeleton_indices_list = skeleton_indices_list
-
-
- self.set_indices_as_properties(skeleton_indices_list)
- self.good_frame_skeleton_data = self.get_good_frame_of_data(good_frame,skeleton_data)
- self.run_joint_finder_calculations()
- self.run_vector_calculations()
-
-
- def run_joint_finder_calculations(self):
- self.mid_hip_XYZ = self.calculate_mid_hip_XYZ_coordinates(self.good_frame_skeleton_data, self.left_hip_index,self.right_hip_index)
- self.mid_foot_XYZ = self.calculate_mid_foot_XYZ_coordinate(self.good_frame_skeleton_data, self.left_heel_index, self.right_heel_index)
- self.shoulder_center_XYZ = self.calculate_shoulder_center_XYZ_coordinates(self.good_frame_skeleton_data, self.left_shoulder_index, self.right_shoulder_index)
-
- def run_vector_calculations(self):
- self.spine_vector, self.spine_unit_vector = self.calculate_spine_vector_and_unit_vector(self.good_frame_skeleton_data, self.mid_hip_XYZ, self.shoulder_center_XYZ)
-
-
- self.heel_vector_origin = self.good_frame_skeleton_data[self.right_heel_index,:]
- self.heel_vector = self.create_vector(self.heel_vector_origin ,self.good_frame_skeleton_data[self.left_heel_index,:])
-
- self.heel_unit_vector = self.create_unit_vector(self.heel_vector)
-
- def set_indices_as_properties(self, indices_list):
- self.left_hip_index = indices_list.index('left_hip')
- self.right_hip_index = indices_list.index('right_hip')
-
- self.left_shoulder_index = indices_list.index('left_shoulder')
- self.right_shoulder_index = indices_list.index('right_shoulder')
-
- self.left_toe_index = indices_list.index('left_foot_index')
- self.right_toe_index = indices_list.index('right_foot_index')
- self.left_heel_index = indices_list.index('left_heel')
- self.right_heel_index = indices_list.index('right_heel')
-
- def get_good_frame_of_data(self,good_frame,skeleton_data):
- """Take in a good frame, and return the base frame"""
- good_frame_skeleton_data = skeleton_data[good_frame,:,:]
- return good_frame_skeleton_data
-
- def create_vector(self,point1,point2):
- """Put two points in, make a vector"""
- vector = point2 - point1
- return vector
-
- def create_normal_vector(self,vector1,vector2):
- """Put two vectors in, make a normal vector"""
- normal_vector = np.cross(vector1,vector2)
- return normal_vector
-
- def create_unit_vector(self,vector):
- """Take in a vector, make it a unit vector"""
- unit_vector = vector/np.linalg.norm(vector)
- return unit_vector
-
- def calculate_normal_vector_to_foot(self,heel_one_index, toe_one_index, heel_two_index, skeleton_data):
- foot_one_vector = self.create_vector(skeleton_data[heel_one_index,:],skeleton_data[toe_one_index,:])
- heel_vector = self.create_vector(skeleton_data[heel_one_index,:],skeleton_data[heel_two_index,:])
-
- foot_normal_vector = self.create_normal_vector(heel_vector,foot_one_vector)
-
- return foot_normal_vector, foot_one_vector, heel_vector
-
- def calculate_shoulder_center_XYZ_coordinates(self, skeleton_data,left_shoulder_index,right_shoulder_index ):
- """Take in the left and right shoulder indices, and calculate the shoulder center point"""
- left_shoulder_point = skeleton_data[left_shoulder_index,:]
- right_shoulder_point = skeleton_data[right_shoulder_index,:]
- shoulder_center_XYZ_coordinates = (left_shoulder_point + right_shoulder_point)/2
-
- return shoulder_center_XYZ_coordinates
-
- def calculate_mid_hip_XYZ_coordinates(self,skeleton_data,left_hip_index,right_hip_index):
- """Take in the left and right hip indices, and calculate the mid hip point"""
- left_hip_point = skeleton_data[left_hip_index,:]
- right_hip_point = skeleton_data[right_hip_index,:]
- mid_hip_XYZ_coordinates = (left_hip_point + right_hip_point)/2
-
- return mid_hip_XYZ_coordinates
-
- def calculate_spine_vector_and_unit_vector(self,skeleton_data,mid_hip_XYZ, mid_shoulder_XYZ):
- spine_vector = self.create_vector(mid_hip_XYZ,mid_shoulder_XYZ)
- spine_unit_vector = self.create_unit_vector(spine_vector)
- return spine_vector, spine_unit_vector
-
- def calculate_mid_foot_XYZ_coordinate(self, skeleton_data, right_heel_index, left_heel_index):
- """Take in the primary and secondary foot indices, and calculate the mid foot point"""
- right_foot_point = skeleton_data[right_heel_index,:]
- left_foot_point = skeleton_data[left_heel_index,:]
- mid_foot_XYZ_coordinates = (right_foot_point + left_foot_point)/2
-
- return mid_foot_XYZ_coordinates
\ No newline at end of file
diff --git a/freemocap/fmc_startup/__init__.py b/freemocap/fmc_startup/__init__.py
deleted file mode 100644
index 9059c793..00000000
--- a/freemocap/fmc_startup/__init__.py
+++ /dev/null
@@ -1,6 +0,0 @@
-# -*- coding: utf-8 -*-
-"""
-Created on Mon Mar 1 13:39:34 2021
-
-@author: Rontc
-"""
diff --git a/freemocap/fmc_startup/startup.py b/freemocap/fmc_startup/startup.py
deleted file mode 100644
index ebcb09d8..00000000
--- a/freemocap/fmc_startup/startup.py
+++ /dev/null
@@ -1,111 +0,0 @@
-from pathlib import Path
-
-from ruamel.yaml import YAML
-
-from freemocap import recordingconfig
-from freemocap.fmc_startup import startupGUI
-
-import tkinter as tk
-from tkinter import filedialog
-
-
-def get_user_preferences(session,stage):
- """
- load user preferences if they exist, create a new preferences yaml if they don't
- """
- path_to_this_py_file = Path(__file__).parent
- preferences_path = path_to_this_py_file/'user_preferences.yaml'
- preferences_yaml = YAML()
-
- #check for a user preferences yaml, if it doesn't exist, build one using the default parameters in recordingconfig.py
- if preferences_path.exists():
- preferences = preferences_yaml.load(preferences_path)
- else:
- preferences = recordingconfig.parameters_for_yaml
- preferences_yaml.dump(preferences, preferences_path)
-
- session.preferences = preferences
- session.preferences_path = preferences_path
-
-def get_dlc_paths(session):
- try:
- saved_dlc_paths = session.preferences['saved']['dlc_config_paths']
- except:
- saved_dlc_paths = session.preferences['default']['dlc_config_paths']
-
- dlc_config_paths = startupGUI.RunChooseDLCPathGUI(session,saved_dlc_paths)
-
- session.preferences['saved']['dlc_config_paths'] = dlc_config_paths
- session.save_user_preferences(session.preferences)
- return dlc_config_paths
-
-def get_data_folder_path(session):
- #if we are rerunning a session folder
- # 1) Check if we're using the last saved dataFolderPath, or if the user wants to choose a different one
- # a. if the user wants to choose one, bring up a GUI to let them decide
- # b. if we're using the last known path - parse the user preferences yaml (and check if that yaml exists)
- # 2) Check that the data folder exists
- # 3) If no sessionID was user-input, search the chosen directory for the last session created
- if session.setDataPath == True:
- session.basePath = startupGUI.RunChooseDataPathGUI(session)
- session.preferences['saved']['path_to_save'] = str(session.basePath)
- session.save_user_preferences(session.preferences)
-
- #sesh.dataFolderPath = Path(basePath)/sesh.dataFolderName
-
- elif session.userDataPath is not None:
- session.basePath = session.userDataPath
-
- else:
- try:
- current_path_to_data = session.preferences['saved']['path_to_save']
- session.basePath = Path(current_path_to_data)
- except KeyError:
- print('Saved Data path not found, please choose a new one')
- session.basePath = startupGUI.RunChooseDataPathGUI(session)
- session.preferences['saved']['path_to_save'] = str(session.basePath)
- session.save_user_preferences(session.preferences)
-
-
- if session.basePath.stem == session.dataFolderName: #don't recursively craete 'FreeMoCap_Data' folders!
- dataFolder = session.basePath
- else:
- dataFolder = session.basePath/session.dataFolderName
-
- session.dataFolderPath = dataFolder
-
-
- if not dataFolder.exists():
- print('Data folder not found at this path. Please choose another path.')
- session.basePath = startupGUI.RunChooseDataPathGUI(session)
- session.preferences['saved']['path_to_save'] = str(session.basePath)
- session.save_user_preferences(session.preferences)
-
- if session.basePath.stem == session.dataFolderName: #don't recursively craete 'FreeMoCap_Data' folders!
- dataFolder = session.basePath
- else:
- dataFolder = session.basePath/session.dataFolderName
- session.dataFolderPath = dataFolder
-
-
-
-
-
-def get_blender_path(session, resetBlenderExe):
- if resetBlenderExe == True:
- print('resetting blender.exe path')
- session.preferences['saved']['blenderEXEpath'] = None
- if session.preferences['saved']['blenderEXEpath'] == None:
- print('Please select your blender.exe file')
- root = tk.Tk()
- root.withdraw()
- blender_file_path = filedialog.askopenfilename(title = 'Select your Blender executable (usually somehwere like `C:/Program Files/Blender Foundation/2.93/blender.exe')
- print('Using blender executable located at:', blender_file_path)
- session.preferences['saved']['blenderEXEpath'] = blender_file_path
- session.save_user_preferences(session.preferences)
- else:
- blender_file_path = session.preferences['saved']['blenderEXEpath']
- print('Using blender executable located at:', blender_file_path)
-
- return blender_file_path
-
diff --git a/freemocap/fmc_startup/startupGUI.py b/freemocap/fmc_startup/startupGUI.py
deleted file mode 100644
index c2ba8646..00000000
--- a/freemocap/fmc_startup/startupGUI.py
+++ /dev/null
@@ -1,176 +0,0 @@
-import tkinter as tk
-from tkinter import Tk, Label, Button, Frame, Listbox, Entry, filedialog
-from pathlib import Path
-
-from numpy.lib.npyio import save
-
-class setDataPathGUI:
- def __init__(self, master,session):
- self.master = master
- self.session = session
-
- chooseText = "Please choose the directory your FreeMoCap_data folder is located in"
- chooseLabel = Label(master, text=chooseText)
- chooseLabel.pack(side="top")
-
- self.currentPath = session.preferences['saved']['path_to_save']
- text = 'Current file path: ' + str(self.currentPath)
- self.currentPathText = tk.StringVar()
- self.currentPathText.set(text)
- currentPathLabel = Label(master,textvariable = self.currentPathText)
- currentPathLabel.pack()
-
- changepath_button = Button(master,text = 'Change Folder Path',command = self.openFileDialog)
- changepath_button.pack(side = 'left')
-
- proceed_button = Button(text="Proceed", command=self.proceed)
- stop_button = Button(text="Quit", command=self.stop)
- proceed_button.pack()
- stop_button.pack()
-
-
-
- def openFileDialog(self):
- self.currentPath = filedialog.askdirectory(
- title='Open a file',
- initialdir= Path.cwd())
- self.currentPathText.set('Current file path: ' + self.currentPath)
-
-
- def stop(self):
- self.master.destroy()
-
-
- def proceed(self):
- self.continueToRecording = True
- self.dataPath = self.currentPath
- self.master.destroy()
-
-
-class DLCConfigPathGUI:
- def __init__(self,master,session,saved_dlc_paths):
- #saved_dlc_paths = ['one','two','three']
- self.master = master
- self.dlc_paths = saved_dlc_paths.copy()
- self.session = session
-
- introText = "Here are your currently saved DLC config paths"
- introLabel = Label(master, text=introText)
- introLabel.pack(side="top")
-
- #savedPathText = self.write_to_string(saved_dlc_paths)
- self.savedPathVar = tk.StringVar()
- #savedPathVar.set(savedPathText)
- self.update_dlc_path_label(self.dlc_paths)
- savedPathLabel = Label(master,textvariable=self.savedPathVar)
- savedPathLabel.pack()
-
- addpath_button = Button(master,text = 'Add a file path',command = self.openFileDialog)
- addpath_button.pack(side='top')
-
- clearpath_button = Button(master,text = 'Clear file paths',command = self.clearPaths)
- clearpath_button.pack(side='top')
-
- savepath_button = Button(master,text = 'Save file paths and Proceed',command = self.savePaths)
- savepath_button.pack(side = 'top')
-
-
- def update_dlc_path_label(self,saved_dlc_paths):
- dlc_string_list = '\n'.join(saved_dlc_paths)
- self.savedPathVar.set(dlc_string_list)
- return dlc_string_list
-
- def openFileDialog(self):
- chosen_path = filedialog.askopenfilename(
- title='Open a file',
- initialdir= Path.cwd(),
- filetypes=[('Yaml','*.yaml')])
- self.dlc_paths.append(chosen_path)
- self.update_dlc_path_label(self.dlc_paths)
- f = 2
-
- def clearPaths(self):
- self.dlc_paths = []
- self.update_dlc_path_label(self.dlc_paths)
-
- def savePaths(self):
- self.config_paths= self.dlc_paths
- self.master.destroy()
-
-
- f = 2
-
-
-
-
-class setBlenderPathGUI:
- def __init__(self, master,session):
- self.master = master
- self.session = session
-
- chooseText = "Choose your Blender executable"
- chooseLabel = Label(master, text=chooseText)
- chooseLabel.pack(side="top")
-
- self.currentPath = Path.cwd()
- text = 'Current file path: ' + str(self.currentPath)
- self.currentPathText = tk.StringVar()
- self.currentPathText.set(text)
- currentPathLabel = Label(master,textvariable = self.currentPathText)
- currentPathLabel.pack()
-
- changepath_button = Button(master,text = 'Change Folder Path',command = self.openFileDialog)
- changepath_button.pack(side = 'left')
-
- proceed_button = Button(text="Proceed", command=self.proceed)
- stop_button = Button(text="Quit", command=self.stop)
- proceed_button.pack()
- stop_button.pack()
-
-
-
- def openFileDialog(self):
- self.currentPath = filedialog.askopenfilename(
- title='Open your Blender executable',
- initialdir= Path.cwd())
- self.currentPathText.set('Current file path: ' + self.currentPath)
-
-
- def stop(self):
- self.master.destroy()
-
-
- def proceed(self):
- self.continueToRecording = True
- self.dataPath = self.currentPath
- self.master.destroy()
-
-
-def RunChooseBlenderPathGUI(session):
- root = tk.Tk()
- chosenBlenderPath = setBlenderPathGUI(root, session)
- root.mainloop()
-
- return chosenBlenderPath.dataPath
-
-
-
-
-def RunChooseDataPathGUI(session):
- root = tk.Tk()
- chosenDataPath = setDataPathGUI(root, session)
- root.mainloop()
-
- return Path(chosenDataPath.dataPath)
-
-
-def RunChooseDLCPathGUI(session,saved_dlc_paths):
- root = tk.Tk()
- chosenDLCPaths = DLCConfigPathGUI(root,session,saved_dlc_paths)
- root.mainloop()
-
- return chosenDLCPaths.config_paths
-
- f = 2
-
-
\ No newline at end of file
diff --git a/freemocap/fmc_trackdata_handler.py b/freemocap/fmc_trackdata_handler.py
deleted file mode 100644
index 90198338..00000000
--- a/freemocap/fmc_trackdata_handler.py
+++ /dev/null
@@ -1,305 +0,0 @@
-"""
-### Data Handler class for wrapping and organizing OpenPose data into a more selfcontained and accessible format.
-
-### Example code:
-
-import fmc_trackdata_handler as df
-import openpose_data_mappings as data_mapping
-
-### Make empty data structure
-data_handler = df.FmcTracDataHandler()
-
-### Set mapping
-data_handler.set_parent_mapping(data_mapping.parent_mapping)
-data_handler.set_point_name_mapping(data_mapping.point_name_mapping)
-
-### Load openpose npy data into variable
-import numpy as np
-datafile_path = r"G:\Shared drives\000_projects\cl005_northeasternMarkerlessMocap\incoming\datasets\sesh_21-05-31_111833\DataArrays\openPoseSkel_3d.npy"
-data = np.load(datafile_path)
-
-### Import data into data handler as an actor.
-# This step can be repeated for multiple datasets, adding each as an individual actor
-actor_name = "tester"
-data_handler.import_actor_raw_data(actor_name, data)
-
-### Saving data handler object to file
-file_path = "/absolute/path/to/file/filename" # Suffix is being set to FILE_SUFFIX automatically
-save_obj_to_file(file_path, data_handler, override=False)
-
-### Loading data handler from file
-file_path = "/absolute/path/to/file/filename.fmcData"
-data_h = df.load_obj_from_file(file_path)
-
-"""
-
-
-import numpy as np
-from pathlib import Path
-import pickle
-
-FILE_SUFFIX = ".fmcData"
-
-class FmcTracDataHandler(object):
- """
- # data structure:
- {
- "header":{
- "version": str(),
- "tags": list(),
- "author": str(),
- "export_date": datetime(),
- "camera_count": int(),
- "license": str(),
- "calibration_obj": class,
- },
- "content":{
- str(actor_name): {
- "sample_count": int(),
- "tracking_points": {
- str(tracking_point_name): {"parents": list(), samples: list()}
- }
- }
- },
- }
- """
-
- def __init__(self):
- self.data = {"header":{}, "content":{}}
-
- def has_actor(self, actor_name):
- return actor_name in self.data["content"]
-
- def has_trackingpoint_name(self, actor_name, point_name):
- return self.has_actor(actor_name) and point_name in self.data["content"][actor_name]["tracking_points"]
-
- def set_point_name_mapping(self, point_name_mapping):
- self.point_name_mapping = point_name_mapping
-
- def set_parent_mapping(self, parent_mapping):
- self.parent_mapping = parent_mapping
-
- def init_actor(self, actor_name):
- if not self.has_actor(actor_name):
- self.data["content"][actor_name] = {}
- else:
- raise Exception("Actor already exist in dataset. Please remove it before re-adding")
-
- def init_tracking_point_name(self, actor_name, point_name):
- if not self.has_actor(actor_name):
- self.init_actor(actor_name)
- if not "tracking_points" in self.data["content"][actor_name]:
- self.data["content"][actor_name]["tracking_points"] = {}
- self.data["content"][actor_name]["tracking_points"][point_name] = {}
-
- def set_actor_data(self, actor_name, data_label, data):
- if not self.has_actor(actor_name):
- self.init_actor(actor_name)
- self.data["content"][actor_name][data_label] = data
-
-
- def set_tracking_point_samples(self, actor_name, point_name, samples):
- if not self.has_trackingpoint_name(actor_name, point_name):
- self.init_tracking_point_name(actor_name, point_name)
- self.data["content"][actor_name]["tracking_points"][point_name]["samples"] = samples
-
- def set_tracking_point_parents(self, actor_name, point_name, parents):
- if not self.has_trackingpoint_name(actor_name, point_name):
- self.init_tracking_point_name(actor_name, point_name)
- self.data["content"][actor_name]["tracking_points"][point_name]["parents"] = parents
-
- def set_actor_sample_count(self, actor_name, sample_count):
- if self.has_actor(actor_name):
- self.data["content"][actor_name]["sample_count"] = sample_count
- else:
- raise ValueError("Object does not contain an actor called: %s" % actor_name)
-
- def set_header(self,key, value):
- self.data["header"][key] = value
-
- def set_version(self, version):
- self.set_header("version", version)
-
- def set_tags(self, tag_list):
- self.set_header("tags", tag_list)
-
- def set_author(self, author):
- self.set_header("author", author)
-
- def set_date(self, datetime_obj):
- self.set_header("export_date", datetime_obj)
-
- def set_camera_count(self, camera_count):
- self.set_header("camera_count", camera_count)
-
- def set_license(self, license_string):
- self.set_header("license", license_string)
-
- def set_calibration_obj(self, calibration_obj):
- self.set_header("calibration_obj", calibration_obj)
-
- def import_actor_raw_data(self, actor_label, raw_data):
- mapped_data = self.map_point_names(raw_data)
- parent_mapping = self.get_parent_mapping()
-
- sample_count = False
- for point_name in mapped_data:
- parent_list = []
- if point_name in parent_mapping:
- parent_list.append(parent_mapping[point_name])
-
- #print("Trackingpoint: %s" % point_name)
- samples = mapped_data[point_name]
- self.set_tracking_point_samples(actor_label, point_name, samples)
- self.set_tracking_point_parents(actor_label, point_name, parent_list)
-
- if sample_count == False:
- sample_count = len(samples)
- else:
- if not sample_count == len(samples):
- raise NotImplementedError("Tracking points have different sample count. This is not supported yet")
- else:
- sample_count = len(samples)
- self.set_actor_sample_count(actor_label, sample_count)
-
-
- def get_data(self):
- return self.data
-
- def get_actor_data(self, actor_label):
- if self.has_actor(actor_name):
- return self.data["content"][actor_label]
- else:
- raise ValueError("Object has no actor named %s" % actor_label)
-
- def list_actors(self):
- return list(self.data["content"].keys())
-
- def get_actor_tracking_points(self, actor_name):
- return self.data["content"][actor_name]["tracking_points"]
-
- def get_point_parents(self, actor_name, point_name):
- return self.data["content"][actor_name]["tracking_points"][point_name]["parents"]
-
- def get_actor_sample_count(self, actor_name):
- if self.has_actor(actor_name):
- return self.data["content"][actor_name]["sample_count"]
- else:
- raise ValueError("Object does not contain an actor called: %s" % actor_name)
-
-
-
-
-
- ### OpenPose mapping
- ################################################################################
- def map_point_names(self, data):
- """
- input data of format:
- [sample_idx][point_index] = (x,y,z)
-
- output format
- {point_name:
- [(x,y,z), (x,y,z),...]} # list of samples
- """
- point_names = self.get_point_name_mapping()
-
- # initiating data container for each point in point_names, added generated names for indices beyond length of point_names
- first_sample = data[0]
- if len(first_sample) > len(point_names): # Check if there is an equal amount of names points and indices in the data
- surplus_sample_points = len(first_sample) - len(point_names)
- for i in range(surplus_sample_points):
- point_names.append("generatedName%s" % str(i).zfill(3))
-
- # reordering data to be ["point_name"][sample_i][x,y,z]
- data_reform = {}
- for i, point_name in enumerate(point_names):
- data_reform[point_name] = data[:,i,:]
-
- return data_reform
-
-
-
- def get_parent_mapping(self):
- """
- Returns a dictionary that maps point names to their parent point
- """
- if not self.parent_mapping == False:
- return self.parent_mapping
- else:
- raise ValueError("No parent mapping is set. Use set_parent_mapping() to define an appropriate map")
-
- def get_point_name_mapping(self):
- """
- Returns a list of names corresponding to the data positions
- """
- if not self.point_name_mapping == False:
- return self.point_name_mapping
- else:
- raise ValueError("No point name mapping is set. Use set_point_name_mapping() to define an appropriate map")
-
-
-
-
-
-def load_obj_from_file(file_path):
- # Loads file saved through this class
- f = Path(file_path)
-
- if f.is_file():
- if f.suffix.lower() == FILE_SUFFIX.lower():
- print(f"Reading file from: {f.absolute()}")
- with open(file_path, "rb") as infile:
- data = pickle.load(infile)
- if not isinstance(data, FmcTracDataHandler):
- raise ValueError("Loaded data is not an instance of FmcTracDataHandler")
- else:
- raise ValueError("File has wrong extension. Should be '%s'" % FILE_SUFFIX)
- else:
- raise ValueError("File does not exist")
-
- return data
-
-
-
-
-def save_obj_to_file(file_path, fmxDataObj, override=False):
- f = Path(file_path)
- f= f.with_suffix(FILE_SUFFIX)
- if f.exists() and override == False:
- raise NotImplementedError(f"File already exists and override set to False, Skipping\nFilepath: {f.absolute()}")
- with open(f, 'wb') as handle:
- pickle.dump(fmxDataObj, handle, protocol=2)
- print(f"Saved file to: {f.absolute()}")
-
-f = 2
-# import fmc_trackdata_handler as df
-# import openpose_data_mappings as data_mapping
-
-# ## Make empty data structure
-# data_handler = df.FmcTracDataHandler()
-
-# ## Set mapping
-# data_handler.set_parent_mapping(data_mapping.parent_mapping)
-# data_handler.set_point_name_mapping(data_mapping.point_name_mapping)
-
-# ## Load openpose npy data into variable
-# import numpy as np
-# datafile_path = r"C:\Users\Rontc\Documents\GitHub\freemocap\FreeMocap_Data\sesh_21-07-29_104227\DataArrays\openPoseSkel_3d.npy"
-# data = np.load(datafile_path)
-
-# ## Import data into data handler as an actor.
-# #This step can be repeated for multiple datasets, adding each as an individual actor
-# actor_name = "tester"
-# data_handler.import_actor_raw_data(actor_name, data)
-
-# ## Saving data handler object to file
-# file_path = r"C:\Users\Rontc\Documents\GitHub\freemocap\FreeMocap_Data\sesh_21-07-29_104227\DataArrays\openPoseSkel_3d" # Suffix is being set to FILE_SUFFIX automatically
-# df.save_obj_to_file(file_path, data_handler, override=False)
-
-# ## Loading data handler from file
-# file_path = r"C:\Users\Rontc\Documents\GitHub\freemocap\FreeMocap_Data\sesh_21-07-29_104227\DataArrays\openPoseSkel_3d.fmcData"
-# data_h = df.load_obj_from_file(file_path)
-
-# f = 2
-
diff --git a/freemocap/freemocap_blender_megascript.py b/freemocap/freemocap_blender_megascript.py
deleted file mode 100644
index bed22c29..00000000
--- a/freemocap/freemocap_blender_megascript.py
+++ /dev/null
@@ -1,1634 +0,0 @@
-from typing import Annotated
-import bpy
-import addon_utils
-import numpy as np
-from pathlib import Path
-import sys
-import traceback
-print(' - Starting blender megascript - ')
-
-#######################################################################
-##% Activate necessary addons
-addon_utils.enable("io_import_images_as_planes")
-addon_utils.enable("rigify")
-
-#######################################################################
-
-try:
- ##% Session path
- # #get session path as command line argument
- argv = sys.argv
- argv = argv[argv.index("--") + 1:]
- session_path = argv[0]
-
- if len(argv)>1:
- good_clean_frame_number = int(argv[1])
- else:
- good_clean_frame_number = 0
-except:
- print('we appear to be running from the Blender Scripting tab! Manually enter your `session_path` at line 23')
- session_path = Path(r'C:\Users\jonma\Dropbox\FreeMoCapProject\FreeMocap_Data\sesh_2022-05-07_17_15_05_pupil_wobble_juggle_0')
- good_clean_frame_number = 3341
-
-
-print(str(session_path))
-session_path = Path(session_path)
-path_to_mediapipe_npy = session_path / 'DataArrays' / 'mediaPipeSkel_3d_smoothed.npy'
-path_to_mediapipe_3d_reproj = session_path / 'DataArrays' / 'mediaPipeSkel_reprojErr.npy'
-
-
-#######################################################################
-#%% load mediapipe data
-#%%
-print('loading data')
-# %%
-mediapipe_skel_fr_mar_dim = np.load(path_to_mediapipe_npy)
-mediapipe_skel_fr_mar_dim = mediapipe_skel_fr_mar_dim/1000 #convert to meters
-
-mediapipe_reproj_fr_mar = np.load(path_to_mediapipe_3d_reproj)
-mediapipe_reproj_fr_mar = mediapipe_reproj_fr_mar/1000 #convert to meters
-
-body_marker_range = np.arange(0,33)
-right_hand_marker_range = np.arange(33, 33+21)
-left_hand_marker_range = np.arange(33+21, 33+21+21)
-face_marker_range = np.arange(left_hand_marker_range[-1], mediapipe_skel_fr_mar_dim.shape[1])
-
-body_skel_fr_mar_dim = mediapipe_skel_fr_mar_dim[:, body_marker_range, :,]
-right_hand_fr_mar_dim = mediapipe_skel_fr_mar_dim[:, right_hand_marker_range, :,]
-left_hand_fr_mar_dim = mediapipe_skel_fr_mar_dim[:, left_hand_marker_range, :,]
-face_fr_mar_dim = mediapipe_skel_fr_mar_dim[:, face_marker_range, :,]
-
-
-#%% Session Specific stuff
-number_of_frames = mediapipe_skel_fr_mar_dim.shape[0]
-start_frame = 1
-end_frame = number_of_frames
-
-bpy.context.scene.frame_start = start_frame
-bpy.context.scene.frame_end = end_frame
-
-
-########################
-## Find Good Clean Frame with some fiddly nonsense
-if good_clean_frame_number == 0:
- frame_nan_counts = []
- frame_mean_reproj_error = []
-
- for this_frame in range(mediapipe_skel_fr_mar_dim.shape[0]):
- frame_nan_counts.append(np.sum(np.isnan(mediapipe_skel_fr_mar_dim[this_frame,:,0])))
- frame_mean_reproj_error.append(np.nanmean(mediapipe_reproj_fr_mar[this_frame,:]))
-
- nan_times_vis = np.array(frame_nan_counts)*np.array(frame_mean_reproj_error)
- num_frames = len(frame_nan_counts)
- # nan_times_vis[0:int(num_frames/5)] = np.nanmax(nan_times_vis)
- # nan_times_vis[-int(num_frames/5):-1] = np.nanmax(nan_times_vis)
-
- good_clean_frame_number = np.nanargmin(nan_times_vis) # the frame with the fewest nans (i.e. hopefully a frame where all tracked points are visible)
-
-print(f"----good_clean_frame_number: {good_clean_frame_number}----")
-
-#######################################################################
-#%% Mediapipe tracked point names
-mediapipe_tracked_point_names = [
- "nose",
- "left_eye_inner",
- "left_eye",
- "left_eye_outer",
- "right_eye_inner",
- "right_eye",
- "right_eye_outer",
- "left_ear",
- "right_ear",
- "mouth_left",
- "mouth_right",
- "left_shoulder",
- "right_shoulder",
- "left_elbow",
- "right_elbow",
- "left_wrist",
- "right_wrist",
- "left_pinky",
- "right_pinky",
- "left_index",
- "right_index",
- "left_thumb",
- "right_thumb",
- "left_hip",
- "right_hip",
- "left_knee",
- "right_knee",
- "left_ankle",
- "right_ankle",
- "left_heel",
- "right_heel",
- "left_foot_index",
- "right_foot_index",
- "right_hand_wrist",
- "right_hand_thumb_cmc",
- "right_hand_thumb_mcp",
- "right_hand_thumb_ip",
- "right_hand_thumb_tip",
- "right_hand_index_finger_mcp",
- "right_hand_index_finger_pip",
- "right_hand_index_finger_dip",
- "right_hand_index_finger_tip",
- "right_hand_middle_finger_mcp",
- "right_hand_middle_finger_pip",
- "right_hand_middle_finger_dip",
- "right_hand_middle_finger_tip",
- "right_hand_ring_finger_mcp",
- "right_hand_ring_finger_pip",
- "right_hand_ring_finger_dip",
- "right_hand_ring_finger_tip",
- "right_hand_pinky_finger_mcp",
- "right_hand_pinky_finger_pip",
- "right_hand_pinky_finger_dip",
- "right_hand_pinky_finger_tip",
- "left_hand_wrist",
- "left_hand_thumb_cmc",
- "left_hand_thumb_mcp",
- "left_hand_thumb_ip",
- "left_hand_thumb_tip",
- "left_hand_index_finger_mcp",
- "left_hand_index_finger_pip",
- "left_hand_index_finger_dip",
- "left_hand_index_finger_tip",
- "left_hand_middle_finger_mcp",
- "left_hand_middle_finger_pip",
- "left_hand_middle_finger_dip",
- "left_hand_middle_finger_tip",
- "left_hand_ring_finger_mcp",
- "left_hand_ring_finger_pip",
- "left_hand_ring_finger_dip",
- "left_hand_ring_finger_tip",
- "left_hand_pinky_finger_mcp",
- "left_hand_pinky_finger_pip",
- "left_hand_pinky_finger_dip",
- "left_hand_pinky_finger_tip",
- ]
-
-
-#####################################################################
-## Blender Stuff
-#####################################################################
-
-try:
- #####################################################################
- ###%% clear scene
- print('clearing scene')
- try:
- bpy.ops.object.mode_set(mode='OBJECT')
- except:
- pass
-
- try:
- bpy.ops.object.select_all(action='SELECT') # select all objects
- bpy.ops.object.delete(use_global=True) # delete all objects from all scenes
- except:
- pass
-
- #######################################################################
- #%% create world origin
-
- bpy.ops.object.empty_add(type='ARROWS')
- world_origin_axes = bpy.context.active_object
- world_origin_axes.name = 'world_origin' #will stay at origin
- # inspect(world_origin_axes, methods=True)
-
- bpy.ops.object.empty_add(type='ARROWS')
- freemocap_origin_axes = bpy.context.active_object
- freemocap_origin_axes.name = 'freemocap_origin_axes' #will translate to put skelly on ground symmetric-ish about origin
-
-
- #######################################################################
- #%% load empties
- print('loading {} empties on {} frames'.format(len(mediapipe_tracked_point_names), number_of_frames))
-
- empty_size = .01
-
- for this_point_index, this_point_name in enumerate(mediapipe_tracked_point_names):
- print(f'loading {this_point_name}...')
- bpy.ops.object.empty_add(type='SPHERE')
- this_empty = bpy.context.active_object
- this_empty.name = this_point_name
-
- if 'face' in this_point_name:
- this_empty.scale = [empty_size/4]*3
- if 'hand' in this_point_name:
- this_empty.scale = [empty_size/2]*3
- else:
- this_empty.scale = [empty_size]*3
-
- this_empty.parent = freemocap_origin_axes
-
- this_point_fr_xyz = mediapipe_skel_fr_mar_dim[:,this_point_index,:]
-
- for frame_num in range(end_frame):
-
- this_empty.location = [this_point_fr_xyz[frame_num,0],
- this_point_fr_xyz[frame_num,1],
- this_point_fr_xyz[frame_num,2]]
- bpy.context.view_layer.update()
-
- this_empty.keyframe_insert(data_path='location',frame=frame_num)
-
- #######################################################################
- #%% create virtual markers
- left_ear_index = 7
- right_ear_index = 8
- #######################################################################
- print('creating virtual markers')
- print('head_center - midway between left and right ears')
- hips_xyz = (mediapipe_skel_fr_mar_dim[:,left_ear_index,:] + mediapipe_skel_fr_mar_dim[:,right_ear_index,:])/2
- bpy.ops.object.empty_add(type='SPHERE')
- this_empty = bpy.context.active_object
- this_empty.name = 'head_center'
- this_empty.scale = [empty_size]*3
- this_empty.parent = freemocap_origin_axes
- mediapipe_tracked_point_names.append(this_empty.name)
-
- for frame_num in range(end_frame):
- this_empty.location = [hips_xyz[frame_num,0],
- hips_xyz[frame_num,1],
- hips_xyz[frame_num,2]]
- this_empty.keyframe_insert(data_path='location',frame=frame_num)
-
- print('neck_center - midway between left and right shoulders')
- left_shoulder_index = 11
- right_shoulder_index = 12
- neck_xyz = (mediapipe_skel_fr_mar_dim[:,left_shoulder_index,:] + mediapipe_skel_fr_mar_dim[:,right_shoulder_index,:])/2
- bpy.ops.object.empty_add(type='PLAIN_AXES')
- this_empty = bpy.context.active_object
- this_empty.name = 'neck_center'
- this_empty.scale = [empty_size]*3
- this_empty.parent = freemocap_origin_axes
- mediapipe_tracked_point_names.append(this_empty.name)
-
- for frame_num in range(end_frame):
- this_empty.location = [neck_xyz[frame_num,0],
- neck_xyz[frame_num,1],
- neck_xyz[frame_num,2]]
- this_empty.keyframe_insert(data_path='location',frame=frame_num)
-
-
-
- print('hip_center - midway between left and right hips')
- left_hip_index = 23
- right_hip_index = 24
- hips_xyz = (mediapipe_skel_fr_mar_dim[:,left_hip_index,:] + mediapipe_skel_fr_mar_dim[:,right_hip_index,:])/2
- bpy.ops.object.empty_add(type='PLAIN_AXES')
- this_empty = bpy.context.active_object
- this_empty.name = 'hip_center'
- this_empty.scale = [empty_size]*3
- this_empty.parent = freemocap_origin_axes
- mediapipe_tracked_point_names.append(this_empty.name)
- rig_constraint_dict_of_dicts = {
- "spine": {
- 'COPY_LOCATION': 'hip_center',
- 'STRETCH_TO': 'chest_center',
- },
- "spine.001": {
- 'STRETCH_TO': 'neck_center',
- },
- "spine.002": {
- 'STRETCH_TO': 'head_center',
- },
- "spine.003": {
- 'STRETCH_TO': 'nose',
- },
- "pelvis.L": {
- 'STRETCH_TO': 'left_hip',
- },
- "thigh.L": {
- 'COPY_LOCATION': 'left_hip',
- 'STRETCH_TO': 'left_knee',
- },
- "shin.L": {
- 'STRETCH_TO': 'left_ankle',
- },
- "foot.L": {
- 'STRETCH_TO': 'left_foot_index',
- },
- "heel.02.L": {
- 'STRETCH_TO': 'left_ankle',
- },
- "shoulder.L": {
- 'COPY_LOCATION': 'neck_center',
- 'STRETCH_TO': 'left_shoulder',
- },
- "upper_arm.L": {
- 'STRETCH_TO': 'left_elbow',
- },
- "forearm.L": {
- 'STRETCH_TO': 'left_wrist',
- },
- "hand.L": {
- 'STRETCH_TO': 'left_index',
- },
- "pelvis.R": {
- 'STRETCH_TO': 'right_hip',
- },
- "thigh.R": {
- 'COPY_LOCATION': 'right_hip',
- 'STRETCH_TO': 'right_knee',
- },
- "shin.R": {
- 'STRETCH_TO': 'right_ankle',
- },
- "foot.R": {
- 'STRETCH_TO': 'right_foot_index',
- },
- "heel.02.R": {
- 'STRETCH_TO': 'right_ankle',
- },
- "shoulder.R": {
- 'COPY_LOCATION': 'neck_center',
- 'STRETCH_TO': 'right_shoulder',
- },
- "upper_arm.R": {
- 'STRETCH_TO': 'right_elbow',
- },
- "forearm.R": {
- 'STRETCH_TO': 'right_wrist',
- },
- "hand.R": {
- 'STRETCH_TO': 'right_index',
- },
- "thumb.01.R": {
- 'COPY_LOCATION': 'right_wrist',
- 'STRETCH_TO': 'right_hand_thumb_mcp',
- },
- "thumb.02.R": {
- 'STRETCH_TO': 'right_hand_thumb_ip',
- },
- "thumb.02.R": {
- 'STRETCH_TO': 'right_hand_thumb_tip',
- },
- "palm.01.R": {
- 'COPY_LOCATION': 'right_wrist',
- 'STRETCH_TO': 'right_hand_index_finger_mcp',
- },
- "f_index.01.R": {
- 'STRETCH_TO': 'right_hand_index_finger_pip',
- },
- "f_index.02.R": {
- 'STRETCH_TO': 'right_hand_index_finger_dip',
- },
- "f_index.03.R": {
- 'STRETCH_TO': 'right_hand_index_finger_tip',
- },
- "palm.02.R": {
- 'COPY_LOCATION': 'right_wrist',
- 'STRETCH_TO': 'right_hand_middle_finger_mcp',
- },
- "f_middle.01.R": {
- 'STRETCH_TO': 'right_hand_middle_finger_pip',
- },
- "f_middle.02.R": {
- 'STRETCH_TO': 'right_hand_middle_finger_dip',
- },
- "f_middle.03.R": {
- 'STRETCH_TO': 'right_hand_middle_finger_tip',
- },
- "palm.03.R": {
- 'COPY_LOCATION': 'right_wrist',
- 'STRETCH_TO': 'right_hand_ring_finger_mcp',
- },
- "f_ring.01.R": {
- 'STRETCH_TO': 'right_hand_ring_finger_pip',
- },
- "f_ring.02.R": {
- 'STRETCH_TO': 'right_hand_ring_finger_dip',
- },
- "f_ring.03.R": {
- 'STRETCH_TO': 'right_hand_ring_finger_tip',
- },
- "palm.04.R": {
- 'COPY_LOCATION': 'right_wrist',
- 'STRETCH_TO': 'right_hand_pinky_finger_mcp',
- },
- "f_pinky.01.R": {
- 'STRETCH_TO': 'right_hand_pinky_finger_pip',
- },
- "f_pinky.02.R": {
- 'STRETCH_TO': 'right_hand_pinky_finger_dip',
- },
- "f_pinky.03.R": {
- 'STRETCH_TO': 'right_hand_pinky_finger_tip',
- },
- "thumb.01.L": {
- 'COPY_LOCATION': 'left_wrist',
- 'STRETCH_TO': 'left_hand_thumb_mcp',
- },
- "thumb.02.L": {
- 'STRETCH_TO': 'left_hand_thumb_ip',
- },
- "thumb.03.L": {
- 'STRETCH_TO': 'left_hand_thumb_tip',
- },
- "palm.01.L": {
- 'COPY_LOCATION': 'left_wrist',
- 'STRETCH_TO': 'left_hand_index_finger_mcp',
- },
- "f_index.01.L": {
- 'STRETCH_TO': 'left_hand_index_finger_pip',
- },
- "f_index.02.L": {
- 'STRETCH_TO': 'left_hand_index_finger_dip',
- },
- "f_index.03.L": {
- 'STRETCH_TO': 'left_hand_index_finger_tip',
- },
- "palm.02.L": {
- 'COPY_LOCATION': 'left_wrist',
- 'STRETCH_TO': 'left_hand_middle_finger_mcp',
- },
- "f_middle.01.L": {
- 'STRETCH_TO': 'left_hand_middle_finger_pip',
- },
- "f_middle.02.L": {
- 'STRETCH_TO': 'left_hand_middle_finger_dip',
- },
- "f_middle.03.L": {
- 'STRETCH_TO': 'left_hand_middle_finger_tip',
- },
- "palm.03.L": {
- 'COPY_LOCATION': 'left_wrist',
- 'STRETCH_TO': 'left_hand_ring_finger_mcp',
- },
- "f_ring.01.L": {
- 'STRETCH_TO': 'left_hand_ring_finger_pip',
- },
- "f_ring.02.L": {
- 'STRETCH_TO': 'left_hand_ring_finger_dip',
- },
- "f_ring.03.L": {
- 'STRETCH_TO': 'left_hand_ring_finger_tip',
- },
- "palm.04.L": {
- 'COPY_LOCATION': 'left_wrist',
- 'STRETCH_TO': 'left_hand_pinky_finger_mcp',
- },
- "f_pinky.01.L": {
- 'STRETCH_TO': 'left_hand_pinky_finger_pip',
- },
- "f_pinky.02.L": {
- 'STRETCH_TO': 'left_hand_pinky_finger_dip',
- },
- "f_pinky.03.L": {
- 'STRETCH_TO': 'left_hand_pinky_finger_tip',
- },
-}
-
- #loop through dictionary applying constraints
- try:
- bpy.ops.object.mode_set(mode='POSE')
- except:
- pass
-
- for frame_num in range(end_frame):
- this_empty.location = [hips_xyz[frame_num,0],
- hips_xyz[frame_num,1],
- hips_xyz[frame_num,2]]
- this_empty.keyframe_insert(data_path='location',frame=frame_num)
-
-
- print('chest_center - mean of R/L shoulders and R/L hips')
- chest_xyz = (neck_xyz + hips_xyz)/2
- bpy.ops.object.empty_add(type='PLAIN_AXES')
- this_empty = bpy.context.active_object
- this_empty.name = 'chest_center'
- this_empty.scale = [empty_size]*3
- this_empty.parent = freemocap_origin_axes
- mediapipe_tracked_point_names.append(this_empty.name)
-
- for frame_num in range(end_frame):
- this_empty.location = [chest_xyz[frame_num,0],
- chest_xyz[frame_num,1],
- chest_xyz[frame_num,2]]
- this_empty.keyframe_insert(data_path='location',frame=frame_num)
-
- print('Done loading empties :D')
-
-
- ######################################################################
- ## Fit Rigify metarig armatures to empties
-
- bpy.context.scene.frame_set(good_clean_frame_number)
-
- #each bone name has to match one in the Blender Rigify Human Metarig, or it will be ignored
- metarig_bone_empty_pairs_dict_of_dicts = {
- "nose.001": {
- 'head': 'head_center',
- 'tail': 'nose',
- },
- "nose.L.001": {
- 'head': 'nose',
- 'tail': 'left_eye_inner',
- },
- "eye.L": {
- 'head': 'left_eye_inner',
- 'tail': 'left_eye',
- },
- "lid.B.L": {
- 'head': 'left_eye',
- 'tail': 'left_eye_outer',
- },
- "ear.L": {
- 'head': 'left_eye_outer',
- 'tail': 'left_ear',
- },
- "nose.R.001": {
- 'head': 'nose',
- 'tail': 'right_eye_inner',
- },
- "eye.R": {
- 'head': 'right_eye_inner',
- 'tail': 'right_eye',
- },
- "lid.B.R": {
- 'head': 'right_eye',
- 'tail': 'right_eye_outer',
- },
- "ear.R": {
- 'head': 'right_eye_outer',
- 'tail': 'right_ear',
- },
- "lip.T.R": {
- 'head': 'nose',
- 'tail': 'mouth_right',
- },
- "lip.B.R": {
- 'head': 'mouth_right',
- 'tail': 'mouth_left',
- },
- "lip.T.L": {
- 'head': 'nose',
- 'tail': 'mouth_left',
- },
- "hand.L": {
- 'head': 'left_wrist',
- 'tail': 'left_index',
- },
- "forearm.L": {
- 'head': 'left_elbow',
- 'tail': 'left_wrist',
- },
- "upper_arm.L": {
- 'head': 'left_shoulder',
- 'tail': 'left_elbow',
- },
- "shoulder.L": {
- 'head': 'neck_center',
- 'tail': 'left_shoulder',
- },
- "hand.R": {
- 'head': 'right_wrist',
- 'tail': 'right_index',
- },
- "forearm.R": {
- 'head': 'right_elbow',
- 'tail': 'right_wrist',
- },
- "upper_arm.R": {
- 'head': 'right_shoulder',
- 'tail': 'right_elbow',
- },
- "shoulder.R": {
- 'head': 'neck_center',
- 'tail': 'right_shoulder',
- },
- "thigh.L": {
- 'head': 'left_hip',
- 'tail': 'left_knee',
- },
- "shin.L": {
- 'head': 'left_knee',
- 'tail': 'left_ankle',
- },
- "heel.02.L": {
- 'head': 'left_heel',
- 'tail': 'left_ankle',
- },
- "foot.L": {
- 'head': 'left_ankle',
- 'tail': 'left_foot_index',
- },
- "toe.L": {
- 'head': 'left_foot_index',
- 'tail': 'left_heel',
- },
- "thigh.R": {
- 'head': 'right_hip',
- 'tail': 'right_knee',
- },
- "shin.R": {
- 'head': 'right_knee',
- 'tail': 'right_ankle',
- },
- "heel.02.R": {
- 'head': 'right_heel',
- 'tail': 'right_ankle',
- },
- "foot.R": {
- 'head': 'right_ankle',
- 'tail': 'right_foot_index',
- },
- "toe.R": {
- 'head': 'right_foot_index',
- 'tail': 'right_heel',
- },
- "pelvis.L": {
- 'head': 'hip_center',
- 'tail': 'left_hip',
- },
- "pelvis.R": {
- 'head': 'hip_center',
- 'tail': 'right_hip',
- },
- "spine": {
- 'head': 'hip_center',
- 'tail': 'chest_center',
- },
- "spine.001": {
- 'head': 'chest_center',
- 'tail': 'neck_center',
- },
- "spine.002": {
- 'head': 'neck_center',
- 'tail': 'head_center',
- },
- "spine.003": {
- 'head': 'head_center',
- 'tail': 'nose',
- },
- "palm.01.R": {
- 'head': 'right_wrist',
- 'tail': 'right_hand_index_finger_mcp',
- },
- "palm.02.R": {
- 'head': 'right_wrist',
- 'tail': 'right_hand_middle_finger_mcp',
- },
- "palm.03.R": {
- 'head': 'right_wrist',
- 'tail': 'right_hand_ring_finger_mcp',
- },
- "palm.04.R": {
- 'head': 'right_wrist',
- 'tail': 'right_hand_pinky_finger_mcp',
- },
-
- "thumb.01.R": {
- 'head': 'right_wrist',
- 'tail': 'right_hand_thumb_mcp',
- },
- "thumb.02.R": {
- 'head': 'right_hand_thumb_mcp',
- 'tail': 'right_hand_thumb_ip',
- },
- "thumb.03.R": {
- 'head': 'right_hand_thumb_ip',
- 'tail': 'right_hand_thumb_tip',
- },
-
- "f_index.01.R": {
- 'head': 'right_hand_index_finger_mcp',
- 'tail': 'right_hand_index_finger_pip',
- },
- "f_index.02.R": {
- 'head': 'right_hand_index_finger_pip',
- 'tail': 'right_hand_index_finger_dip',
- },
- "f_index.03.R": {
- 'head': 'right_hand_index_finger_dip',
- 'tail': 'right_hand_index_finger_tip',
- },
-
- "f_middle.01.R": {
- 'head': 'right_hand_middle_finger_mcp',
- 'tail': 'right_hand_middle_finger_pip',
- },
- "f_middle.02.R": {
- 'head': 'right_hand_middle_finger_pip',
- 'tail': 'right_hand_middle_finger_dip',
- },
- "f_middle.03.R": {
- 'head': 'right_hand_middle_finger_dip',
- 'tail': 'right_hand_middle_finger_tip',
- },
-
- "f_ring.01.R": {
- 'head': 'right_hand_ring_finger_mcp',
- 'tail': 'right_hand_ring_finger_pip',
- },
- "f_ring.02.R": {
- 'head': 'right_hand_ring_finger_pip',
- 'tail': 'right_hand_ring_finger_dip',
- },
- "f_ring.03.R": {
- 'head': 'right_hand_ring_finger_dip',
- 'tail': 'right_hand_ring_finger_tip',
- },
-
- "f_pinky.01.R": {
- 'head': 'right_hand_pinky_finger_mcp',
- 'tail': 'right_hand_pinky_finger_pip',
- },
- "f_pinky.02.R": {
- 'head': 'right_hand_pinky_finger_pip',
- 'tail': 'right_hand_pinky_finger_dip',
- },
- "f_pinky.03.R": {
- 'head': 'right_hand_pinky_finger_dip',
- 'tail': 'right_hand_pinky_finger_tip',
- },
- "thumb.01.L": {
- 'head': 'left_wrist',
- 'tail': 'left_hand_thumb_mcp',
- },
- "thumb.02.L": {
- 'head': 'left_hand_thumb_mcp',
- 'tail': 'left_hand_thumb_ip',
- },
- "thumb.03.L": {
- 'head': 'left_hand_thumb_ip',
- 'tail': 'left_hand_thumb_tip',
- },
- "palm.01.L": {
- 'head': 'left_wrist',
- 'tail': 'left_hand_index_finger_mcp',
- },
- "palm.02.L": {
- 'head': 'left_wrist',
- 'tail': 'left_hand_middle_finger_mcp',
- },
- "palm.03.L": {
- 'head': 'left_wrist',
- 'tail': 'left_hand_ring_finger_mcp',
- },
- "palm.04.L": {
- 'head': 'left_wrist',
- 'tail': 'left_hand_pinky_finger_mcp',
- },
- "f_index.01.L": {
- 'head': 'left_hand_index_finger_mcp',
- 'tail': 'left_hand_index_finger_pip',
- },
- "f_index.02.L": {
- 'head': 'left_hand_index_finger_pip',
- 'tail': 'left_hand_index_finger_dip',
- },
- "f_index.03.L": {
- 'head': 'left_hand_index_finger_dip',
- 'tail': 'left_hand_index_finger_tip',
- },
-
- "f_middle.01.L": {
- 'head': 'left_hand_middle_finger_mcp',
- 'tail': 'left_hand_middle_finger_pip',
- },
- "f_middle.02.L": {
- 'head': 'left_hand_middle_finger_pip',
- 'tail': 'left_hand_middle_finger_dip',
- },
- "f_middle.03.L": {
- 'head': 'left_hand_middle_finger_dip',
- 'tail': 'left_hand_middle_finger_tip',
- },
- "f_ring.01.L": {
- 'head': 'left_hand_ring_finger_mcp',
- 'tail': 'left_hand_ring_finger_pip',
- },
- "f_ring.02.L": {
- 'head': 'left_hand_ring_finger_pip',
- 'tail': 'left_hand_ring_finger_dip',
- },
- "f_ring.03.L": {
- 'head': 'left_hand_ring_finger_dip',
- 'tail': 'left_hand_ring_finger_tip',
- },
- "f_pinky.01.L": {
- 'head': 'left_hand_pinky_finger_mcp',
- 'tail': 'left_hand_pinky_finger_pip',
- },
- "f_pinky.02.L": {
- 'head': 'left_hand_pinky_finger_pip',
- 'tail': 'left_hand_pinky_finger_dip',
- },
- "f_pinky.03.L": {
- 'head': 'left_hand_pinky_finger_dip',
- 'tail': 'left_hand_pinky_finger_tip',
- },
-
- }
-
-
- #%% create metarig
- bpy.ops.object.armature_human_metarig_add()
- this_metarig = bpy.context.active_object
-
- #%% loop through dictionary - set head and tail of each bone's to the relevant empty
- # bpy.ops.object.posemode_toggle()
- try:
- bpy.ops.object.mode_set(mode='EDIT')
- except:
- pass
-
- for this_bone in list(this_metarig.data.bones):
- this_bone_name = this_bone.name
- print(f'--{this_bone_name}--')
-
- this_edit_bone= this_metarig.data.edit_bones[this_bone_name] # note this is using EDIT_bones, not regular bones b/c blender is a wild wacky place
-
- if this_bone_name in metarig_bone_empty_pairs_dict_of_dicts:
- this_bone_dict = metarig_bone_empty_pairs_dict_of_dicts[this_bone_name]
-
- this_head_empty_name = this_bone_dict['head']
- this_tail_empty_name = this_bone_dict['tail']
- print('setting (bone:head->tail){}:{}->{})'.format(this_bone_name, this_head_empty_name, this_tail_empty_name))
-
- if this_tail_empty_name is not None:
- print(f'setting bone: {this_bone_name}: head: {bpy.data.objects[this_head_empty_name].location}, tail: {bpy.data.objects[this_tail_empty_name].location}')
- this_edit_bone.head = bpy.data.objects[this_head_empty_name].location
- this_edit_bone.tail = bpy.data.objects[this_tail_empty_name].location
- else: #remove bones with no tail (and/or head) until we figure out a better plan
- print(f'removing bone: {this_bone_name}')
- this_metarig.data.edit_bones.remove(this_edit_bone)
- else:
- print(f'removing bone: {this_bone_name}')
- this_metarig.data.edit_bones.remove(this_edit_bone)
-
- try:
- bpy.ops.object.mode_set(mode='OBJECT')
- except:
- pass
-
-
-
-
- #######################################################
- #### Damped track bones to empties
- bpy.ops.object.mode_set(mode='OBJECT')
- armature_name = 'metarig'
- this_armature = bpy.data.objects[armature_name]
-
- rig_constraint_dict_of_dicts = {
- "nose.001": {
- 'COPY_LOCATION': 'head_center',
- 'DAMPED_TRACK': 'nose',
- },
- "nose.L.001": {
- 'DAMPED_TRACK': 'left_eye_inner',
- },
- "eye.L": {
- 'DAMPED_TRACK': 'left_eye',
- },
- "lid.B.L": {
- 'DAMPED_TRACK': 'left_eye_outer',
- },
- "ear.L": {
- 'DAMPED_TRACK': 'left_ear',
- },
- "nose.R.001": {
- 'DAMPED_TRACK': 'right_eye_inner',
- },
- "eye.R": {
- 'DAMPED_TRACK': 'right_eye',
- },
- "lid.B.R": {
- 'DAMPED_TRACK': 'right_eye_outer',
- },
- "ear.R": {
- 'DAMPED_TRACK': 'right_ear',
- },
- "lip.T.R": {
- 'DAMPED_TRACK': 'mouth_right',
- },
- "lip.B.R": {
- 'DAMPED_TRACK': 'mouth_left',
- },
- "lip.T.L": {
- 'DAMPED_TRACK': 'nose',
- },
- "spine": {
- 'COPY_LOCATION': 'hip_center',
- 'DAMPED_TRACK': 'chest_center',
- },
- "spine.001": {
- 'DAMPED_TRACK': 'neck_center',
- },
- "spine.002": {
- 'DAMPED_TRACK': 'head_center',
- },
- "spine.003": {
- 'DAMPED_TRACK': 'nose',
- },
- "pelvis.L": {
- 'DAMPED_TRACK': 'left_hip',
- },
- "thigh.L": {
- 'COPY_LOCATION': 'left_hip',
- 'DAMPED_TRACK': 'left_knee',
- },
- "shin.L": {
- 'DAMPED_TRACK': 'left_ankle',
- },
- "foot.L": {
- 'DAMPED_TRACK': 'left_foot_index',
- },
- "heel.02.L": {
- 'DAMPED_TRACK': 'left_ankle',
- },
- "shoulder.L": {
- 'COPY_LOCATION': 'neck_center',
- 'DAMPED_TRACK': 'left_shoulder',
- },
- "upper_arm.L": {
- 'DAMPED_TRACK': 'left_elbow',
- },
- "forearm.L": {
- 'DAMPED_TRACK': 'left_wrist',
- },
- "hand.L": {
- 'DAMPED_TRACK': 'left_index',
- },
- "pelvis.R": {
- 'DAMPED_TRACK': 'right_hip',
- },
- "thigh.R": {
- 'COPY_LOCATION': 'right_hip',
- 'DAMPED_TRACK': 'right_knee',
- },
- "shin.R": {
- 'DAMPED_TRACK': 'right_ankle',
- },
- "foot.R": {
- 'DAMPED_TRACK': 'right_foot_index',
- },
- "heel.02.R": {
- 'DAMPED_TRACK': 'right_ankle',
- },
- "shoulder.R": {
- 'COPY_LOCATION': 'neck_center',
- 'DAMPED_TRACK': 'right_shoulder',
- },
- "upper_arm.R": {
- 'DAMPED_TRACK': 'right_elbow',
- },
- "forearm.R": {
- 'DAMPED_TRACK': 'right_wrist',
- },
- "hand.R": {
- 'DAMPED_TRACK': 'right_index',
- },
- "thumb.01.R": {
- 'COPY_LOCATION': 'right_wrist',
- 'DAMPED_TRACK': 'right_hand_thumb_mcp',
- },
- "thumb.02.R": {
- 'DAMPED_TRACK': 'right_hand_thumb_ip',
- },
- "thumb.02.R": {
- 'DAMPED_TRACK': 'right_hand_thumb_tip',
- },
- "palm.01.R": {
- 'COPY_LOCATION': 'right_wrist',
- 'DAMPED_TRACK': 'right_hand_index_finger_mcp',
- },
- "f_index.01.R": {
- 'DAMPED_TRACK': 'right_hand_index_finger_pip',
- },
- "f_index.02.R": {
- 'DAMPED_TRACK': 'right_hand_index_finger_dip',
- },
- "f_index.03.R": {
- 'DAMPED_TRACK': 'right_hand_index_finger_tip',
- },
- "palm.02.R": {
- 'COPY_LOCATION': 'right_wrist',
- 'DAMPED_TRACK': 'right_hand_middle_finger_mcp',
- },
- "f_middle.01.R": {
- 'DAMPED_TRACK': 'right_hand_middle_finger_pip',
- },
- "f_middle.02.R": {
- 'DAMPED_TRACK': 'right_hand_middle_finger_dip',
- },
- "f_middle.03.R": {
- 'DAMPED_TRACK': 'right_hand_middle_finger_tip',
- },
- "palm.03.R": {
- 'COPY_LOCATION': 'right_wrist',
- 'DAMPED_TRACK': 'right_hand_ring_finger_mcp',
- },
- "f_ring.01.R": {
- 'DAMPED_TRACK': 'right_hand_ring_finger_pip',
- },
- "f_ring.02.R": {
- 'DAMPED_TRACK': 'right_hand_ring_finger_dip',
- },
- "f_ring.03.R": {
- 'DAMPED_TRACK': 'right_hand_ring_finger_tip',
- },
- "palm.04.R": {
- 'COPY_LOCATION': 'right_wrist',
- 'DAMPED_TRACK': 'right_hand_pinky_finger_mcp',
- },
- "f_pinky.01.R": {
- 'DAMPED_TRACK': 'right_hand_pinky_finger_pip',
- },
- "f_pinky.02.R": {
- 'DAMPED_TRACK': 'right_hand_pinky_finger_dip',
- },
- "f_pinky.03.R": {
- 'DAMPED_TRACK': 'right_hand_pinky_finger_tip',
- },
- "thumb.01.L": {
- 'COPY_LOCATION': 'left_wrist',
- 'DAMPED_TRACK': 'left_hand_thumb_mcp',
- },
- "thumb.02.L": {
- 'DAMPED_TRACK': 'left_hand_thumb_ip',
- },
- "thumb.03.L": {
- 'DAMPED_TRACK': 'left_hand_thumb_tip',
- },
- "palm.01.L": {
- 'COPY_LOCATION': 'left_wrist',
- 'DAMPED_TRACK': 'left_hand_index_finger_mcp',
- },
- "f_index.01.L": {
- 'DAMPED_TRACK': 'left_hand_index_finger_pip',
- },
- "f_index.02.L": {
- 'DAMPED_TRACK': 'left_hand_index_finger_dip',
- },
- "f_index.03.L": {
- 'DAMPED_TRACK': 'left_hand_index_finger_tip',
- },
- "palm.02.L": {
- 'COPY_LOCATION': 'left_wrist',
- 'DAMPED_TRACK': 'left_hand_middle_finger_mcp',
- },
- "f_middle.01.L": {
- 'DAMPED_TRACK': 'left_hand_middle_finger_pip',
- },
- "f_middle.02.L": {
- 'DAMPED_TRACK': 'left_hand_middle_finger_dip',
- },
- "f_middle.03.L": {
- 'DAMPED_TRACK': 'left_hand_middle_finger_tip',
- },
- "palm.03.L": {
- 'COPY_LOCATION': 'left_wrist',
- 'DAMPED_TRACK': 'left_hand_ring_finger_mcp',
- },
- "f_ring.01.L": {
- 'DAMPED_TRACK': 'left_hand_ring_finger_pip',
- },
- "f_ring.02.L": {
- 'DAMPED_TRACK': 'left_hand_ring_finger_dip',
- },
- "f_ring.03.L": {
- 'DAMPED_TRACK': 'left_hand_ring_finger_tip',
- },
- "palm.04.L": {
- 'COPY_LOCATION': 'left_wrist',
- 'DAMPED_TRACK': 'left_hand_pinky_finger_mcp',
- },
- "f_pinky.01.L": {
- 'DAMPED_TRACK': 'left_hand_pinky_finger_pip',
- },
- "f_pinky.02.L": {
- 'DAMPED_TRACK': 'left_hand_pinky_finger_dip',
- },
- "f_pinky.03.L": {
- 'DAMPED_TRACK': 'left_hand_pinky_finger_tip',
- },
- }
-
- #loop through dictionary applying constraints
- try:
- bpy.ops.object.mode_set(mode='POSE')
- except:
- pass
-
- for this_bone_name, this_bone_dict in rig_constraint_dict_of_dicts.items():
- print(f'---Setting constraints for bone:{this_bone_name}---')
-
- for this_constraint_name, this_constraint_target_empty_name in this_bone_dict.items():
- print(f'constraint: {this_constraint_name} with target:{this_constraint_target_empty_name}')
- print('grab bone')
- this_bone= this_armature.pose.bones[this_bone_name]
- print('apply bone')
- this_constraint = this_bone.constraints.new(type=this_constraint_name)
- this_constraint.name = this_constraint_name
- this_constraint.target = bpy.data.objects[this_constraint_target_empty_name] #point constraint at relevant empty object
-
- ##############
- ## create extra bones
-
- extra_bone_empty_pairs_dict_of_dicts = {
- "hand.L": {
- 'head': 'left_wrist',
- 'tail': 'left_index',
- },
- "forearm.L": {
- 'head': 'left_elbow',
- 'tail': 'left_wrist',
- },
- }
-
- ###################################################################
- #### Create Stick Figure Mesh
-
- stick_figure_mesh_edge_pairs_dict_of_dicts = {
- "nose.001": {
- 'head': 'head_center',
- 'tail': 'nose',
- },
- "nose.L.001": {
- 'head': 'nose',
- 'tail': 'left_eye_inner',
- },
- "eye.L": {
- 'head': 'left_eye_inner',
- 'tail': 'left_eye',
- },
- "lid.B.L": {
- 'head': 'left_eye',
- 'tail': 'left_eye_outer',
- },
- "ear.L": {
- 'head': 'left_eye_outer',
- 'tail': 'left_ear',
- },
- "nose.R.001": {
- 'head': 'nose',
- 'tail': 'right_eye_inner',
- },
- "eye.R": {
- 'head': 'right_eye_inner',
- 'tail': 'right_eye',
- },
- "lid.B.R": {
- 'head': 'right_eye',
- 'tail': 'right_eye_outer',
- },
- "ear.R": {
- 'head': 'right_eye_outer',
- 'tail': 'right_ear',
- },
- "lip.T.R": {
- 'head': 'nose',
- 'tail': 'mouth_right',
- },
- "lip.B.R": {
- 'head': 'mouth_right',
- 'tail': 'mouth_left',
- },
- "lip.T.L": {
- 'head': 'nose',
- 'tail': 'mouth_left',
- },
- "forearm.L": {
- 'head': 'left_elbow',
- 'tail': 'left_wrist',
- },
- "upper_arm.L": {
- 'head': 'left_shoulder',
- 'tail': 'left_elbow',
- },
- "shoulder.L": {
- 'head': 'neck_center',
- 'tail': 'left_shoulder',
- },
- "forearm.R": {
- 'head': 'right_elbow',
- 'tail': 'right_wrist',
- },
- "upper_arm.R": {
- 'head': 'right_shoulder',
- 'tail': 'right_elbow',
- },
- "shoulder.R": {
- 'head': 'neck_center',
- 'tail': 'right_shoulder',
- },
- "thigh.L": {
- 'head': 'left_hip',
- 'tail': 'left_knee',
- },
- "shin.L": {
- 'head': 'left_knee',
- 'tail': 'left_ankle',
- },
- "heel.02.L": {
- 'head': 'left_heel',
- 'tail': 'left_ankle',
- },
- "foot.L": {
- 'head': 'left_ankle',
- 'tail': 'left_foot_index',
- },
- "toe.L": {
- 'head': 'left_foot_index',
- 'tail': 'left_heel',
- },
- "thigh.R": {
- 'head': 'right_hip',
- 'tail': 'right_knee',
- },
- "shin.R": {
- 'head': 'right_knee',
- 'tail': 'right_ankle',
- },
- "heel.02.R": {
- 'head': 'right_heel',
- 'tail': 'right_ankle',
- },
- "foot.R": {
- 'head': 'right_ankle',
- 'tail': 'right_foot_index',
- },
- "toe.R": {
- 'head': 'right_foot_index',
- 'tail': 'right_heel',
- },
- "pelvis.L": {
- 'head': 'hip_center',
- 'tail': 'left_hip',
- },
- "pelvis.R": {
- 'head': 'hip_center',
- 'tail': 'right_hip',
- },
- "spine": {
- 'head': 'hip_center',
- 'tail': 'chest_center',
- },
- "spine.001": {
- 'head': 'chest_center',
- 'tail': 'neck_center',
- },
- "spine.002": {
- 'head': 'neck_center',
- 'tail': 'head_center',
- },
- "spine.003": {
- 'head': 'head_center',
- 'tail': 'nose',
- },
- "palm.01.R": {
- 'head': 'right_wrist',
- 'tail': 'right_hand_index_finger_mcp',
- },
- "palm.02.R": {
- 'head': 'right_wrist',
- 'tail': 'right_hand_middle_finger_mcp',
- },
- "palm.03.R": {
- 'head': 'right_wrist',
- 'tail': 'right_hand_ring_finger_mcp',
- },
- "palm.04.R": {
- 'head': 'right_wrist',
- 'tail': 'right_hand_pinky_finger_mcp',
- },
-
- "thumb.01.R": {
- 'head': 'right_wrist',
- 'tail': 'right_hand_thumb_cmc',
- },
- "thumb.02.R": {
- 'head': 'right_hand_thumb_cmc',
- 'tail': 'right_hand_thumb_mcp',
- },
- "thumb.03.R": {
- 'head': 'right_hand_thumb_mcp',
- 'tail': 'right_hand_thumb_ip',
- },
- "thumb.04.R": {
- 'head': 'right_hand_thumb_ip',
- 'tail': 'right_hand_thumb_tip',
- },
- "f_index.01.R": {
- 'head': 'right_hand_index_finger_mcp',
- 'tail': 'right_hand_index_finger_pip',
- },
- "f_index.02.R": {
- 'head': 'right_hand_index_finger_pip',
- 'tail': 'right_hand_index_finger_dip',
- },
- "f_index.03.R": {
- 'head': 'right_hand_index_finger_dip',
- 'tail': 'right_hand_index_finger_tip',
- },
- "f_middle.01.R": {
- 'head': 'right_hand_middle_finger_mcp',
- 'tail': 'right_hand_middle_finger_pip',
- },
- "f_middle.02.R": {
- 'head': 'right_hand_middle_finger_pip',
- 'tail': 'right_hand_middle_finger_dip',
- },
- "f_middle.03.R": {
- 'head': 'right_hand_middle_finger_dip',
- 'tail': 'right_hand_middle_finger_tip',
- },
- "f_ring.01.R": {
- 'head': 'right_hand_ring_finger_mcp',
- 'tail': 'right_hand_ring_finger_pip',
- },
- "f_ring.02.R": {
- 'head': 'right_hand_ring_finger_pip',
- 'tail': 'right_hand_ring_finger_dip',
- },
- "f_ring.03.R": {
- 'head': 'right_hand_ring_finger_dip',
- 'tail': 'right_hand_ring_finger_tip',
- },
-
- "f_pinky.01.R": {
- 'head': 'right_hand_pinky_finger_mcp',
- 'tail': 'right_hand_pinky_finger_pip',
- },
- "f_pinky.02.R": {
- 'head': 'right_hand_pinky_finger_pip',
- 'tail': 'right_hand_pinky_finger_dip',
- },
- "f_pinky.03.R": {
- 'head': 'right_hand_pinky_finger_dip',
- 'tail': 'right_hand_pinky_finger_tip',
- },
- "thumb.01.L": {
- 'head': 'left_wrist',
- 'tail': 'left_hand_thumb_cmc',
- },
- "thumb.02.L": {
- 'head': 'left_hand_thumb_cmc',
- 'tail': 'left_hand_thumb_mcp',
- },
- "thumb.03.L": {
- 'head': 'left_hand_thumb_mcp',
- 'tail': 'left_hand_thumb_ip',
- },
- "thumb.04.L": {
- 'head': 'left_hand_thumb_ip',
- 'tail': 'left_hand_thumb_tip',
- },
- "palm.01.L": {
- 'head': 'left_wrist',
- 'tail': 'left_hand_index_finger_mcp',
- },
- "palm.02.L": {
- 'head': 'left_wrist',
- 'tail': 'left_hand_middle_finger_mcp',
- },
- "palm.03.L": {
- 'head': 'left_wrist',
- 'tail': 'left_hand_ring_finger_mcp',
- },
- "palm.04.L": {
- 'head': 'left_wrist',
- 'tail': 'left_hand_pinky_finger_mcp',
- },
- "f_index.01.L": {
- 'head': 'left_hand_index_finger_mcp',
- 'tail': 'left_hand_index_finger_pip',
- },
- "f_index.02.L": {
- 'head': 'left_hand_index_finger_pip',
- 'tail': 'left_hand_index_finger_dip',
- },
- "f_index.03.L": {
- 'head': 'left_hand_index_finger_dip',
- 'tail': 'left_hand_index_finger_tip',
- },
- "f_middle.01.L": {
- 'head': 'left_hand_middle_finger_mcp',
- 'tail': 'left_hand_middle_finger_pip',
- },
- "f_middle.02.L": {
- 'head': 'left_hand_middle_finger_pip',
- 'tail': 'left_hand_middle_finger_dip',
- },
- "f_middle.03.L": {
- 'head': 'left_hand_middle_finger_dip',
- 'tail': 'left_hand_middle_finger_tip',
- },
- "f_ring.01.L": {
- 'head': 'left_hand_ring_finger_mcp',
- 'tail': 'left_hand_ring_finger_pip',
- },
- "f_ring.02.L": {
- 'head': 'left_hand_ring_finger_pip',
- 'tail': 'left_hand_ring_finger_dip',
- },
- "f_ring.03.L": {
- 'head': 'left_hand_ring_finger_dip',
- 'tail': 'left_hand_ring_finger_tip',
- },
- "f_pinky.01.L": {
- 'head': 'left_hand_pinky_finger_mcp',
- 'tail': 'left_hand_pinky_finger_pip',
- },
- "f_pinky.02.L": {
- 'head': 'left_hand_pinky_finger_pip',
- 'tail': 'left_hand_pinky_finger_dip',
- },
- "f_pinky.03.L": {
- 'head': 'left_hand_pinky_finger_dip',
- 'tail': 'left_hand_pinky_finger_tip',
- },
- }
-
- mediapipe_virtual_markers_weights_dict = {
- 'head_center':{
- 'right_ear': .5,
- 'left_ear': .5
- },
- 'neck_center':{
- 'right_shoulder': .5,
- 'left_shoulder': .5
- },
- 'hip_center':{
- 'right_hip': .5,
- 'left_hip': .5
- },
- 'chest_center':{
- 'right_shoulder': .25,
- 'left_shoulder': .25,
- 'right_hip': .25,
- 'left_hip': .25,
- },
- }
-
- print('loading data as stick figure mesh \o/')
- #######################################################################
-
- #%% create virtual marker points (redundant from above, I think ? )
-
-
-
- current_frame = bpy.data.scenes[0].frame_current
- virtual_point_index_dict = {}
- for this_virtual_marker_dict in mediapipe_virtual_markers_weights_dict.items():
- this_virtual_marker_name = this_virtual_marker_dict[0]
- these_weighted_points = []
- for this_weighted_point_dict in this_virtual_marker_dict[1].items():
- this_point_name = this_weighted_point_dict[0]
-
- this_weight = this_weighted_point_dict[1]
- these_weighted_points.append(
- mediapipe_skel_fr_mar_dim[
- :,
- mediapipe_tracked_point_names.index(this_point_name),
- :
- ]*this_weight
- )
- this_virtual_point_fr_xyz = np.sum(these_weighted_points, axis=0)
- this_virtual_point_fr_mar_xyz = np.expand_dims(this_virtual_point_fr_xyz, axis=1)
- mediapipe_skel_fr_mar_dim = np.append(mediapipe_skel_fr_mar_dim,this_virtual_point_fr_mar_xyz, axis=1)
- virtual_point_index_dict[this_virtual_marker_name] = mediapipe_skel_fr_mar_dim.shape[1]-1
- print(f'Virtual marker: {this_virtual_marker_name} created at marker index {mediapipe_skel_fr_mar_dim.shape[1]-1}')
-
-
- #%% define edges
-
-
- edges = []
- #regular data
- for this_bone_dict in stick_figure_mesh_edge_pairs_dict_of_dicts.items():
- edge_name = this_bone_dict[0]
- head_name = this_bone_dict[1]['head']
- tail_name = this_bone_dict[1]['tail']
-
-
- try:
-
- head_index = mediapipe_tracked_point_names.index(head_name)
- tail_index = mediapipe_tracked_point_names.index(tail_name)
-
- if 'center' in head_name: #virtual markers are acting weird so we're brute forcing it :-/ this will fail if there is a virtual marker without 'center' in the name....
- head_index = virtual_point_index_dict[head_name]
- if 'center' in tail_name:
- tail_index = virtual_point_index_dict[tail_name]
-
- this_edge =(head_index, tail_index)
-
- edges.append(this_edge)
- print(f'edge created for bone: ({this_bone_dict[0]} : {head_name}-{tail_name}), indicies({this_edge[0]},{this_edge[1]})')
- except:
- print(f'edge FAILED for for bone:{this_bone_dict[0]} : {head_name}-{tail_name}')
- pass
-
- print('edges created!')
-
-
- ##############################
- #%% Create mesh
- try:
- bpy.ops.object.mode_set(mode='OBJECT')
- except:
- pass
-
- print('loading verticies')
- vertices = mediapipe_skel_fr_mar_dim[current_frame,:,:] #don't plot face dottos until we know what to do with them
- print('done loading verticies')
- #edges defined above
- faces = []
- stick_figure_mesh = bpy.data.meshes.new('stick_figure_mesh')
- print('a')
- stick_figure_mesh.from_pydata(vertices, edges, faces)
- print('b')
- stick_figure_mesh.update()
- print('c')
- # make object from mesh
- stick_figure_mesh_object = bpy.data.objects.new('stick_figure_mesh', stick_figure_mesh)
- print('d')
- # make collection
- mesh_collection = bpy.data.collections.new('mesh_collection')
- print('e')
- bpy.context.scene.collection.children.link(mesh_collection)
- print('f')
- # add object to scene collection
- mesh_collection.objects.link(stick_figure_mesh_object)
- print('g')
-
- bpy.context.view_layer.objects.active = bpy.data.objects['stick_figure_mesh']
- print('h')
-
- bpy.context.object.mode
- try:
- bpy.ops.object.editmode_toggle()
- except:
- pass
- print('i')
-
- #### skin that mesh!
- print('skinning mesh \o/')
- bpy.data.objects['stick_figure_mesh'].modifiers.new('stick_figure_mesh_skin', 'SKIN')
- print('resizing mesh')
- skin_radius = .025
- bpy.ops.transform.skin_resize(value=(skin_radius, skin_radius, skin_radius))
-
- ########
- # # parent mesh to armature
- print('parenting mesh to armarture with automatic weights...')
- bpy.ops.object.mode_set(mode='OBJECT')
- bpy.data.objects['stick_figure_mesh'].parent = this_metarig
- bpy.context.view_layer.objects.active = this_metarig
- bpy.context.active_object.select_set(True)
- bpy.data.objects['stick_figure_mesh'].select_set(True)
- bpy.ops.object.parent_set(type='ARMATURE_AUTO')
-
-
- #####################
- ## Load nSynched Videos
- try:
- print('loading videos as planes...')
- annotated_videos_path = session_path / 'annotated_videos'
-
- if annotated_videos_path.is_dir():
- vidFolderPath = annotated_videos_path
- else:
- vidFolderPath = session_path / 'SyncedVideos'
-
- world_origin = bpy.data.objects['world_origin']
-
- number_of_videos = len(list(vidFolderPath.glob('*.mp4')))
-
- vid_location_scale = 1
-
-
- for vid_number, thisVidPath, in enumerate(vidFolderPath.glob('*.mp4')):
- print(thisVidPath)
- # use 'images as planes' add on to load in the video files as planes
- bpy.ops.import_image.to_plane(files=[{"name":thisVidPath.name}], directory=str(thisVidPath.parent), shader='EMISSION', )
- this_vid_as_plane = bpy.context.active_object
- this_vid_as_plane.name = 'vid_' + str(vid_number)
-
-
- vid_x = (vid_number - number_of_videos/2) * vid_location_scale
-
- this_vid_as_plane.location = [vid_x, vid_location_scale, vid_location_scale]
- this_vid_as_plane.rotation_euler = [np.pi/2, 0, 0]
- this_vid_as_plane.scale = [vid_location_scale*1.5]*3
- this_vid_as_plane.parent = world_origin
- # create a light
- # bpy.ops.object.light_add(type='POINT', radius=1, align='WORLD')
- except:
- print('Failed to load videos to Blender scene - You might need to install the "images as planes" addon to this version of Blender')
-except Exception as e:
- print(e)
- print('Something broke in the Blender Megascript - Maybe it failed to find a good clean frame and then that borked something downstream?')
-
-# set shading type to 'Material Preview' so you can see the videos
-
-# save .blend file
-sessionID = session_path.stem
-blend_file_save_path = session_path / (sessionID + '.blend')
-print(f"Saving Blender output file to: {str(blend_file_save_path)}")
-bpy.ops.wm.save_as_mainfile(filepath= str(blend_file_save_path) )
\ No newline at end of file
diff --git a/freemocap/openpose_data_mappings.py b/freemocap/openpose_data_mappings.py
deleted file mode 100644
index 2dc96311..00000000
--- a/freemocap/openpose_data_mappings.py
+++ /dev/null
@@ -1,82 +0,0 @@
-# define point parents by name. Only points listed will have a parent. If a point is not listed, it will be without parents
-# child_name : parent_name
-parent_mapping = {
- 'REye': 'Nose',
- 'LKnee': 'LHip',
- 'LWrist': 'LElbow',
- 'LSmallToe': 'LBigToe',
- 'RShoulder': 'Neck',
- 'LBigToe': 'LAnkle',
- 'RKnee': 'RHip',
- 'LEar': 'LEye',
- 'REar': 'REye',
- 'RBigToe': 'RAnkle',
- 'RAnkle': 'RKnee',
- 'LElbow': 'LShoulder',
- 'RElbow': 'RShoulder',
- 'LAnkle': 'LKnee',
- 'RHeel': 'RAnkle',
- 'RWrist': 'RElbow',
- 'RSmallToe': 'RBigToe',
- 'RHip': 'MidHip',
- 'Nose': 'Neck',
- 'MidHip': 'Neck',
- 'LShoulder': 'Neck',
- 'LEye': 'Nose',
- 'LHip': 'MidHip',
- 'LHeel': 'LAnkle',
- 'HandL15': 'HandL14',
- #'HandL13': 'HandL00',
- 'HandL14': 'HandL13',
- 'HandL20': 'HandL19',
- 'RWrist': 'RElbow',
- 'HandL12': 'HandL11',
- 'HandL18': 'HandL17',
- #'HandL02': 'HandL01',
- 'HandL03': 'HandL02',
- #'HandL17': 'HandL00',
- #'HandL01': 'HandL00',
- 'HandL06': 'HandL05',
- 'HandL07': 'HandL06',
- 'HandL04': 'HandL03',
- #'HandL05': 'HandL00',
- 'HandL11': 'HandL10',
- 'HandL08': 'HandL07',
- #'HandL09': 'HandL00',
- 'HandL19': 'HandL18',
- 'HandL16': 'HandL15',
- 'HandL10': 'HandL09',
- 'HandR14': 'HandR13',
- 'HandR08': 'HandR07',
- #'HandR09': 'HandR00',
- 'HandR19': 'HandR18',
- 'HandR18': 'HandR17',
- 'HandR04': 'HandR03',
- #'HandR05': 'HandR00',
- 'HandR06': 'HandR05',
- 'HandR07': 'HandR06',
- #'HandR13': 'HandR00',
- #'HandR01': 'HandR00',
- #'HandR02': 'HandR01',
- 'HandR03': 'HandR02',
- #'HandR17': 'HandR00',
- 'HandR20': 'HandR19',
- 'LWrist': 'LElbow',
- 'HandR11': 'HandR10',
- 'HandR12': 'HandR11',
- 'HandR16': 'HandR15',
- 'HandR10': 'HandR09',
- 'HandR15': 'HandR14'
-}
-
-
-# point name corresponding to Open Pose list indices
-# If the imported list is longer than the point_name_mapping, all residual points will be given a generic name
-point_name_mapping = [
- "Nose", "Neck", "RShoulder", "RElbow", "RWrist", "LShoulder", # limbs
- "LElbow", "LWrist", "MidHip", "RHip", "RKnee", "RAnkle", "LHip", "LKnee", # limbs
- "LAnkle", "REye", "LEye", "REar", "LEar", "LBigToe", "LSmallToe", "LHeel", # limbs
- "RBigToe", "RSmallToe", "RHeel", # limbs
- "HandR00", "HandR01", "HandR02", "HandR03", "HandR04", "HandR05", "HandR06", "HandR07", "HandR08", "HandR09", "HandR10", "HandR11", "HandR12", "HandR13", "HandR14", "HandR15", "HandR16", "HandR17", "HandR18", "HandR19", "HandR20", # Right Hand
- "HandL00", "HandL01", "HandL02", "HandL03", "HandL04", "HandL05", "HandL06", "HandL07", "HandL08", "HandL09", "HandL10", "HandL11", "HandL12", "HandL13", "HandL14", "HandL15", "HandL16", "HandL17", "HandL18", "HandL19", "HandL20", # Left Hand
-]
diff --git a/freemocap/package-lock.json b/freemocap/package-lock.json
deleted file mode 100644
index 1f051745..00000000
--- a/freemocap/package-lock.json
+++ /dev/null
@@ -1,6 +0,0 @@
-{
- "name": "freemocap",
- "lockfileVersion": 2,
- "requires": true,
- "packages": {}
-}
diff --git a/freemocap/parameters.yaml b/freemocap/parameters.yaml
deleted file mode 100644
index 1853dee4..00000000
--- a/freemocap/parameters.yaml
+++ /dev/null
@@ -1,32 +0,0 @@
-#default parameters
-
-
-
-
-default:
- rotations: {}
- parameters:
- exposure: -5
- resWidth: 640
- resHeight: 480
- framerate: 25
- codec: DIVX
-
-#saved parameters
-
-
-
-
-
-saved:
- rotations:
- 0: 90
- 1: 90
- 2: 90
- 3: 270
- parameters:
- exposure: -9
- resWidth: 640
- resHeight: 480
- framerate: 30
- codec: H264
diff --git a/freemocap/play_skeleton_animation.py b/freemocap/play_skeleton_animation.py
deleted file mode 100644
index b31b36e8..00000000
--- a/freemocap/play_skeleton_animation.py
+++ /dev/null
@@ -1,1051 +0,0 @@
-"""
-============
-β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆ β–ˆβ–ˆ
-β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ
-β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ
-β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ
-β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆ
-============
-Font - ANSI Regular - https://patorjk.com/software/taag/#p=display&f=ANSI%20Regular&t=Play%20Skeleton%20Animation
-============
-Originally based on tutorial from - https://matplotlib.org/2.1.2/gallery/animation/simple_3danim.html
-
-Create a matplotlib animation from a FreeMoCap recording session.
-"""
-
-
-################################################################################################################
-################################################################################################################
-###
-### β–ˆβ–ˆ β–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ
-### β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ
-### β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ
-### β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ
-### β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ
-###
-################################################################################################################
-################################################################################################################
-
-
-import numpy as np
-
-import matplotlib as mpl
-import matplotlib.pyplot as plt
-import mpl_toolkits.mplot3d.axes3d as p3
-import matplotlib.animation as animation
-from matplotlib.widgets import Slider
-import cv2
-from scipy.signal import savgol_filter
-import moviepy.editor as mp
-
-import os
-import copy
-from pathlib import Path
-import time
-
-#RICH CONSOLE STUFF
-from rich import pretty
-pretty.install() #makes all print statement output pretty
-from rich import inspect
-from rich.console import Console
-console = Console()
-from rich.traceback import install as rich_traceback_install
-from rich.markdown import Markdown
-
-#colors from Taylor Davis branding -
-humon_dark = np.array([37, 67, 66])/255
-humon_green = np.array([53, 93, 95])/255
-humon_blue = np.array([14, 90, 253])/255
-humon_red = np.array([217, 61, 67])/255
-
-
-def PlaySkeletonAnimation(
- session=None,
- vidType=1,
- startFrame=0,
- azimuth=-90,
- elevation=-70,
- useOpenPose=True,
- useMediaPipe=False,
- useDLC=False,
- recordVid = True,
- showAnimation =True,
- ):
-
-
-
-
- ###
- ###
- ### β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ
- ### β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ
- ### β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆ
- ### β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ
- ### β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ
- ###
- def update_figure(frameNum):
- """
- Called by matplotlib animator for each frame.
- """
-
- if useOpenPose:
- op_skel_dottos = matplotlib_artist_objs['op_skel_dottos']
- op_skel_trajectories = figure_data['openPose_skel_trajectories|mar|fr_dim']
-
- if useMediaPipe:
- mp_skel_dottos = matplotlib_artist_objs['mp_skel_dottos']
- mp_skel_trajectories = figure_data['mediaPipe_skel_trajectories|mar|fr_dim']
-
- charuco_dottos = matplotlib_artist_objs['charuco_dottos']
- charuco_trajectories = figure_data['charuco_trajectories|mar|fr_dim']
-
- if useDLC:
- dlc_dottos = matplotlib_artist_objs['dlc_dottos']
- dlc_trajectories = figure_data['dlc_trajectories|mar|fr_dim']
-
- #function to update the lines for each 3d body segment
- def update_3d_skel_segments(key, data_fr_mar_xyz):
- """
- updates the Artist of each body segment with the current frame data.
- """
- split = key.split('_')
-
- if split[0] == 'op':
- dict_of_segments_idxs = dict_of_openPoseSegmentIdx_dicts[key]
- if split[0] == 'mp':
- dict_of_segments_idxs = dict_of_mediaPipeSegmentIdx_dicts[key]
- elif split[0] == 'dlc':
- dict_of_segments_idxs = dict_of_dlcSegmentIdx_dicts[key]
-
- try:
- dict_of_artists = matplotlib_artist_objs[key]
- except:
- print('KeyError:', key)
-
-
- for thisItem in dict_of_segments_idxs.items():
- segName = thisItem[0]
- segArtist = dict_of_artists[segName]
- segArtist.set_data((data_fr_mar_xyz[frameNum, dict_of_segments_idxs[segName], 0], data_fr_mar_xyz[frameNum, dict_of_segments_idxs[segName], 1]))
- segArtist.set_3d_properties(data_fr_mar_xyz[frameNum, dict_of_segments_idxs[segName], 2])
-
- if useOpenPose:
- update_3d_skel_segments('op_body', openPose_skel_fr_mar_xyz)
- update_3d_skel_segments('op_rHand', openPose_skel_fr_mar_xyz)
- update_3d_skel_segments('op_lHand', openPose_skel_fr_mar_xyz)
- update_3d_skel_segments('op_face', openPose_skel_fr_mar_xyz)
-
- if useMediaPipe:
- update_3d_skel_segments('mp_body', mediaPipe_skel_fr_mar_xyz)
- update_3d_skel_segments('mp_rHand', mediaPipe_skel_fr_mar_xyz)
- update_3d_skel_segments('mp_lHand', mediaPipe_skel_fr_mar_xyz)
-
- if useDLC:
- update_3d_skel_segments('dlc_pinkBall', dlc_fr_mar_xyz)
- update_3d_skel_segments('dlc_redBall', dlc_fr_mar_xyz)
- update_3d_skel_segments('dlc_greenBall', dlc_fr_mar_xyz)
- update_3d_skel_segments('dlc_wobbleBoard', dlc_fr_mar_xyz)
- update_3d_skel_segments('dlc_wobbleWheel', dlc_fr_mar_xyz)
-
- for bb in range(3):
- thisTailArtist = matplotlib_artist_objs['ball_tails'][bb]
-
- thisTailArtist.set_data((dlc_trajectories[bb][frameNum-ballTailLen:frameNum+1, 0],
- dlc_trajectories[bb][frameNum-ballTailLen:frameNum+1, 1]))
-
- thisTailArtist.set_3d_properties(dlc_trajectories[bb][frameNum-ballTailLen:frameNum+1, 2])
- #dlc data
- marNum = -1
- for thisDotto, thisTraj in zip(dlc_dottos,dlc_trajectories):
- marNum+=1
- # NOTE: there is no .set_data() for 3 dim data...
- thisDotto.set_data(thisTraj[ frameNum, 0:2])
- thisDotto.set_3d_properties(thisTraj[ frameNum, 2])
-
- #Plots the dots!
- #openpose data
- if useOpenPose:
- marNum = -1
- for thisSkelDotto, thisTraj in zip(op_skel_dottos,op_skel_trajectories):
- marNum+=1
- # NOTE: there is no .set_data() for 3 dim data...
- thisSkelDotto.set_data(thisTraj[ frameNum, 0:2])
- thisSkelDotto.set_3d_properties(thisTraj[ frameNum, 2])
-
- #mediapipe data
- if useMediaPipe:
- marNum = -1
- for thisSkelDotto, thisTraj in zip(mp_skel_dottos,mp_skel_trajectories):
- marNum+=1
- # NOTE: there is no .set_data() for 3 dim data...
- thisSkelDotto.set_data(thisTraj[ frameNum, 0:2])
- thisSkelDotto.set_3d_properties(thisTraj[ frameNum, 2])
-
-
-
- #charuco data
- for thisDotto, thisTraj in zip(charuco_dottos,charuco_trajectories):
-
- if frameNum<charuco_trajectories[0].shape[0]:
- thisDotto.set_data(thisTraj[ frameNum, 0:2])
- thisDotto.set_3d_properties(thisTraj[ frameNum, 2])
- else:
- thisDotto.set_color('none')
-
-
-
-
- # function to update the lines for each body segment
- def update_2d_skel_segments(vidNum,key):
- """
- updates the Artist of each body segment with the current frame data.
- """
- split = key.split('_')
- if split[0] == 'op':
- dict_of_segments_idxs = dict_of_openPoseSegmentIdx_dicts[key]
- dict_of_artists = thisVidOpenPoseArtist_dict[key]
- elif split[0] == 'mp':
- dict_of_segments_idxs = dict_of_mediaPipeSegmentIdx_dicts[key]
- dict_of_artists = thisVidMediaPipeArtist_dict[key]
-
-
- for thisItem in dict_of_segments_idxs.items():
- segName = thisItem[0]
- segArtist = dict_of_artists[segName]
-
- if split[0] == 'op':
- xData = openPose_nCams_nFrames_nImgPts_XYC[vidNum, frameNum, dict_of_segments_idxs[segName],0]
- yData = openPose_nCams_nFrames_nImgPts_XYC[vidNum, frameNum, dict_of_segments_idxs[segName],1]
- elif split[0] == 'mp':
- xData = mediaPipe_nCams_nFrames_nImgPts_XYC[vidNum, frameNum, dict_of_segments_idxs[segName],0]
- yData = mediaPipe_nCams_nFrames_nImgPts_XYC[vidNum, frameNum, dict_of_segments_idxs[segName],1]
-
- xDataMasked = np.ma.masked_array(xData, mask=(xData==0))
- yDataMasked = np.ma.masked_array(yData, mask=(xData==0))
- segArtist.set_data(xDataMasked,yDataMasked)
-
-
- #update video frames
- for vidNum, thisVidArtist in enumerate(vidAristList):
- vidCapObjList[vidNum].set(cv2.CAP_PROP_POS_FRAMES, frameNum)
- success, image = vidCapObjList[vidNum].read()
-
- if success:
- thisVidArtist.set_array(cv2.cvtColor(image, cv2.COLOR_BGR2RGB))
- else:
- vidCapObjList[vidNum].set(cv2.CAP_PROP_POS_FRAMES, 0)
- success, image = vidCapObjList[vidNum].read()
-
- if useOpenPose:
- thisVidOpenPoseArtist_dict = list_of_vidOpenPoseArtistdicts[vidNum]
- update_2d_skel_segments(vidNum,'op_body')
- update_2d_skel_segments(vidNum,'op_rHand')
- update_2d_skel_segments(vidNum,'op_lHand')
- update_2d_skel_segments(vidNum,'op_face')
-
- if useMediaPipe:
- thisVidMediaPipeArtist_dict = list_of_vidMediaPipeArtistdicts[vidNum]
- update_2d_skel_segments(vidNum,'mp_body')
- update_2d_skel_segments(vidNum,'mp_rHand')
- update_2d_skel_segments(vidNum,'mp_lHand')
-
- if useDLC: #JSM NOTE - this one won't work, we'll need to fix it the next time we get DLC data
- thisVidDLCArtist[0].set_data( dlcData_nCams_nFrames_nImgPts_XYC[vidNum,frameNum,:,0],
- dlcData_nCams_nFrames_nImgPts_XYC[vidNum,frameNum,:,1],)
-
-
- #shift timeseries xlims along with the frameNum
- xTimeSeriesAx.set_xlim([(frameNum/fps)-timeRange, (frameNum/fps)+timeRange])
- yTimeSeriesAx.set_xlim([(frameNum/fps)-timeRange, (frameNum/fps)+timeRange])
- for thisArtistKey in xCurrTimeArtists:
-
- xCurrTimeArtists[thisArtistKey][0].set_xdata(frameNum/fps)
- yCurrTimeArtists[thisArtistKey][0].set_xdata(frameNum/fps)
- if not thisArtistKey == 'blackLine':
- xCurrTimeArtists[thisArtistKey][0].set_ydata(xCurrTimeYdata[thisArtistKey][frameNum] )
- yCurrTimeArtists[thisArtistKey][0].set_ydata(yCurrTimeYdata[thisArtistKey][frameNum] )
-
- yCurrTimeArtists['frameNumber'].set_x(frameNum/fps+3/fps)
- yCurrTimeArtists['frameNumber'].set_text('Frame# '+ str(frameNum))
- # if recordVid:
- # thisFramePath = str(animationFramePath) + '/'+ str(session.sessionID) + "_frame_" + str(frameNum).zfill(6) + ".png"
- # plt.savefig(thisFramePath)
- # # fig.suptitle("nSessionID: {}, Frame: {} of {}".format(session.sessionID, frameNum, numFrames), fontsize=10)
- # # animSlider.set_val(val=frameNum)
-
- ####
- #### β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ
- #### β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ
- #### β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆ
- #### β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ
- #### β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ
- ####
-
-
- fig = plt.figure(dpi=200)
- plt.ion()
-
-
- ###
- ### β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ
- ### β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ
- ### β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ
- ### β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ
- ### β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ
- ###
- ###
-
- # ax3d = p3.Axes3D(fig)
- ax3d = fig.add_subplot(projection='3d')
- ax3d.set_position([-.065, .28, .7, .7]) # [left, bottom, width, height])
- ax3d.set_xticklabels([])
- ax3d.set_yticklabels([])
- ax3d.set_zticklabels([])
-
- # ax3d.set_xlabel('X')
- # ax3d.set_ylabel('Y')
- # ax3d.set_zlabel('Z')
- # ax3d.set_axis_off()
-
-
- ax3d.tick_params(length=0) # WHY DOESNT THIS WORK? I HATE THOSE TICK MARKS >:(
-
- smoothData=True
- smoothWinLength = 5
- smoothOrder = 3
-
- if useOpenPose:
- try:
- openPose_skel_fr_mar_xyz = np.load(session.dataArrayPath / 'openPoseSkel_3d.npy')
- openPose_nCams_nFrames_nImgPts_XYC = np.load(session.dataArrayPath / 'openPoseData_2d.npy')
- except:
- print('No openPose data found.')
-
- if smoothData:
- for dim in range(openPose_skel_fr_mar_xyz.shape[2]):
- for mm in range(openPose_skel_fr_mar_xyz.shape[1]):
- openPose_skel_fr_mar_xyz[:,mm,dim] = savgol_filter(openPose_skel_fr_mar_xyz[:,mm,dim], smoothWinLength, smoothOrder)
-
- if useMediaPipe:
- try:
- mediaPipe_skel_fr_mar_xyz = np.load(session.dataArrayPath / 'mediaPipeSkel_3d_smoothed.npy')
- mediaPipe_nCams_nFrames_nImgPts_XYC = np.load(session.dataArrayPath / 'mediaPipeData_2d.npy')
- except:
- print('No mediaPipe data found.')
-
- if smoothData:
- for dim in range(mediaPipe_skel_fr_mar_xyz.shape[2]):
- for mm in range(mediaPipe_skel_fr_mar_xyz.shape[1]):
- mediaPipe_skel_fr_mar_xyz[:,mm,dim] = savgol_filter(mediaPipe_skel_fr_mar_xyz[:,mm,dim], smoothWinLength, smoothOrder)
-
- try:
- charuco_fr_mar_xyz = np.load(session.dataArrayPath / 'charuco_3d_points.npy')
- except:
- console.warning('No charuco data found')
-
-
-
-
- figure_data = dict()
- if useOpenPose:
- figure_data['openPose_skel_trajectories|mar|fr_dim'] = [openPose_skel_fr_mar_xyz[:,markerNum,:] for markerNum in range(openPose_skel_fr_mar_xyz.shape[1])]
- figure_data['openPose_skel_fr_mar_xyz'] = openPose_skel_fr_mar_xyz
-
- dict_of_openPoseSegmentIdx_dicts, dict_of_op_skel_lineColor = formatOpenPoseStickIndices() #these will help us draw body and hands stick figures
-
-
- if useMediaPipe:
- mediaPipe_trajectories = [mediaPipe_skel_fr_mar_xyz[:,markerNum,:] for markerNum in range(mediaPipe_skel_fr_mar_xyz.shape[1])]
- figure_data['mediaPipe_skel_trajectories|mar|fr_dim'] = [mediaPipe_skel_fr_mar_xyz[:,markerNum,:] for markerNum in range(mediaPipe_skel_fr_mar_xyz.shape[1])]
- figure_data['mediaPipe_skel_fr_mar_xyz'] = mediaPipe_skel_fr_mar_xyz
-
- dict_of_mediaPipeSegmentIdx_dicts, dict_of_mp_skel_lineColor = formatMediaPipeStickIndices() #these will help us draw body and hands stick figures
-
-
- charuco_trajectories = [charuco_fr_mar_xyz[:,markerNum,:] for markerNum in range(charuco_fr_mar_xyz.shape[1])]
- figure_data['charuco_trajectories|mar|fr_dim'] = charuco_trajectories
- figure_data['charuco_fr_mar_xyz'] = charuco_fr_mar_xyz
-
-
- if useDLC:
- dlc_fr_mar_xyz = np.load(session.dataArrayPath / "deepLabCut_3d.npy")
- dlcData_nCams_nFrames_nImgPts_XYC = np.load(session.dataArrayPath / "deepLabCutData_2d.npy")
-
- for mm in range(dlc_fr_mar_xyz.shape[1]):
- for dim in range(dlc_fr_mar_xyz.shape[2]):
- dlc_fr_mar_xyz[:,mm,dim] = savgol_filter(dlc_fr_mar_xyz[:,mm,dim], 11, 3)
-
- ballTailLen = 6
- if ballTailLen > startFrame:
- startFrame = ballTailLen+1 #gotta do this, or the tail will index negative frames (without requiring annoying checks later)
-
- dlc_trajectories = [dlc_fr_mar_xyz[:,markerNum,:] for markerNum in range(dlc_fr_mar_xyz.shape[1])]
- figure_data['dlc_trajectories|mar|fr_dim'] = dlc_trajectories
- figure_data['dlc_fr_mar_xyz'] = dlc_fr_mar_xyz
-
-
-
-
- def build_3d_segment_artist_dict(data_fr_mar_xyz,
- dict_of_list_of_segment_idxs,
- segColor = 'k',
- lineWidth = 1,
- lineStyle = '-',
- markerType = None,
- marSize = 12,
- markerEdgeColor = 'k',):
- """
- Builds a dictionary of line artists for each 3D body segment.
- """
- segNames = list(dict_of_list_of_segment_idxs)
-
-
-
- dict_of_artist_objects = dict()
- for segNum, segName in enumerate(segNames):
-
- #determine color of segment, based on class of 'segColor' input
- if isinstance(segColor, str):
- thisRGBA = segColor
- elif isinstance(segColor, np.ndarray):
- thisRGBA = segColor
- elif isinstance(segColor, dict):
- thisRGBA = segColor[segName]
- elif isinstance(segColor, list):
- try:
- thisRGBA = segColor[segNum]
- except:
- print('Not enough colors provided, using Black instead')
- thisRGBA = 'k'
- else:
- thisRGBA = 'k'
-
- if isinstance(segName, str):
- idxsOG = dict_of_list_of_segment_idxs[segName]
- else:
- idxsOG
-
- if isinstance(idxsOG, int) or isinstance(idxsOG, float):
- idxs = [idxsOG]
- elif isinstance(idxsOG, dict):
- idxs = idxsOG[0]
- else:
- idxs = idxsOG.copy()
-
-
- dict_of_artist_objects[segName] = ax3d.plot(
- data_fr_mar_xyz[startFrame, idxs ,0],
- data_fr_mar_xyz[startFrame, idxs ,1],
- data_fr_mar_xyz[startFrame, idxs ,2],
- linestyle=lineStyle,
- linewidth=lineWidth,
- markerSize = marSize,
- marker = markerType,
- color = thisRGBA,
- markeredgecolor = markerEdgeColor,
- )[0]
- return dict_of_artist_objects
-
-
-
- matplotlib_artist_objs = dict()
-
- if useOpenPose:
- matplotlib_artist_objs['op_body'] = build_3d_segment_artist_dict(openPose_skel_fr_mar_xyz, dict_of_openPoseSegmentIdx_dicts['op_body'], segColor = dict_of_op_skel_lineColor)
- matplotlib_artist_objs['op_rHand'] = build_3d_segment_artist_dict(openPose_skel_fr_mar_xyz, dict_of_openPoseSegmentIdx_dicts['op_rHand'], segColor=np.append(humon_red, 1), markerType='.', markerEdgeColor = humon_red, lineWidth=1, marSize = 2)
- matplotlib_artist_objs['op_lHand'] = build_3d_segment_artist_dict(openPose_skel_fr_mar_xyz, dict_of_openPoseSegmentIdx_dicts['op_lHand'], segColor=np.append(humon_blue, 1), markerType='.', markerEdgeColor = humon_blue, lineWidth=1, marSize = 2)
- matplotlib_artist_objs['op_face'] = build_3d_segment_artist_dict(openPose_skel_fr_mar_xyz, dict_of_openPoseSegmentIdx_dicts['op_face'], segColor='k', lineWidth=.5)
-
- if useMediaPipe:
- matplotlib_artist_objs['mp_body'] = build_3d_segment_artist_dict(mediaPipe_skel_fr_mar_xyz, dict_of_mediaPipeSegmentIdx_dicts['mp_body'], segColor = dict_of_mp_skel_lineColor)
- matplotlib_artist_objs['mp_rHand'] = build_3d_segment_artist_dict(mediaPipe_skel_fr_mar_xyz, dict_of_mediaPipeSegmentIdx_dicts['mp_rHand'], segColor=np.append(humon_red, 1), markerType='.', markerEdgeColor = humon_red, lineWidth=1, marSize = 2)
- matplotlib_artist_objs['mp_lHand'] = build_3d_segment_artist_dict(mediaPipe_skel_fr_mar_xyz, dict_of_mediaPipeSegmentIdx_dicts['mp_lHand'], segColor=np.append(humon_blue, 1), markerType='.', markerEdgeColor = humon_blue, lineWidth=1, marSize = 2)
-
- if useDLC:
- dict_of_dlcSegmentIdx_dicts = dict()
- dict_of_dlcSegmentIdx_dicts['pinkBall'] = {'pinkBall': [0]}
- dict_of_dlcSegmentIdx_dicts['greenBall'] = {'greenBall': [1]}
- dict_of_dlcSegmentIdx_dicts['redBall'] = {'redBall': [2]}
- dict_of_dlcSegmentIdx_dicts['wobbleBoard'] = {'wobbleboard':[3,4,5,6,3,7,5,4,7,6]}
- dict_of_dlcSegmentIdx_dicts['wobbleWheel'] = {'wobbleWheel':[8,9]}
-
-
- ballColor = ['darkviolet', 'forestgreen', 'xkcd:goldenrod']
- matplotlib_artist_objs['pinkBall'] = build_3d_segment_artist_dict(dlc_fr_mar_xyz, dict_of_dlcSegmentIdx_dicts['pinkBall'], segColor=ballColor[0], markerType = 'o', marSize = 6, markerEdgeColor = 'indigo')
- matplotlib_artist_objs['redBall'] = build_3d_segment_artist_dict(dlc_fr_mar_xyz, dict_of_dlcSegmentIdx_dicts['redBall'], segColor=ballColor[2], markerType = 'o', marSize = 6, markerEdgeColor ='orangered')
- matplotlib_artist_objs['greenBall'] = build_3d_segment_artist_dict(dlc_fr_mar_xyz, dict_of_dlcSegmentIdx_dicts['greenBall'], segColor=ballColor[1], markerType = 'o', marSize = 6, markerEdgeColor ='darkgreen')
-
- matplotlib_artist_objs['wobbleBoard'] = build_3d_segment_artist_dict(dlc_fr_mar_xyz, dict_of_dlcSegmentIdx_dicts['wobbleBoard'], segColor='k', lineWidth=1)
- matplotlib_artist_objs['wobbleWheel'] = build_3d_segment_artist_dict(dlc_fr_mar_xyz, dict_of_dlcSegmentIdx_dicts['wobbleWheel'], segColor='k', lineWidth=1)
-
- if useOpenPose:
- op_skel_dottos = []
- for mm in range(67): #getcher dottos off my face!
- thisTraj = openPose_skel_fr_mar_xyz[:, mm, :]
- if mm==15:
- col = 'r'
- markerSize = 2
- elif mm == 16:
- col = 'b'
- markerSize = 2
- else:
- col = 'k'
- markerSize = 1
-
- thisDotto =ax3d.plot(thisTraj[0, 0:1], thisTraj[1, 0:1], thisTraj[2, 0:1][0],'.', markersize=markerSize, color = col)
- op_skel_dottos.append(thisDotto[0])
-
- matplotlib_artist_objs['op_skel_dottos'] = op_skel_dottos
-
- if useMediaPipe:
- matplotlib_artist_objs['mp_skel_dottos'] = [ax3d.plot(thisTraj[0, 0:1], thisTraj[1, 0:1], thisTraj[2, 0:1],'m.', markersize=1)[0] for thisTraj in mediaPipe_trajectories]
-
- matplotlib_artist_objs['charuco_dottos'] = [ax3d.plot(thisTraj[0, 0:1], thisTraj[1, 0:1], thisTraj[2, 0:1],'m.', markersize=1)[0] for thisTraj in charuco_trajectories]
-
-
- if useDLC:
- matplotlib_artist_objs['dlc_dottos'] = [ax3d.plot(thisTraj[0, 0:1], thisTraj[1, 0:1], thisTraj[2, 0:1],'b.', markersize=1)[0] for thisTraj in dlc_trajectories]
-
- matplotlib_artist_objs['ball_tails'] = [ax3d.plot(
- dlc_trajectories[bb][startFrame-ballTailLen:startFrame, 0],
- dlc_trajectories[bb][startFrame-ballTailLen:startFrame, 1],
- dlc_trajectories[bb][startFrame-ballTailLen:startFrame, 2],
- '-', color=ballColor[bb])[0] for bb in range(3)]
-
-
- if useOpenPose:
- numFrames = openPose_skel_fr_mar_xyz.shape[0]
- mx = np.nanmean(openPose_skel_fr_mar_xyz[int(numFrames/2),:,0])
- my = np.nanmean(openPose_skel_fr_mar_xyz[int(numFrames/2),:,1])
- mz = np.nanmean(openPose_skel_fr_mar_xyz[int(numFrames/2),:,2])
-
- if useMediaPipe:
- numFrames = mediaPipe_skel_fr_mar_xyz.shape[0]
- mx = np.nanmean(mediaPipe_skel_fr_mar_xyz[int(numFrames/2),:,0])
- my = np.nanmean(mediaPipe_skel_fr_mar_xyz[int(numFrames/2),:,1])
- mz = np.nanmean(mediaPipe_skel_fr_mar_xyz[int(numFrames/2),:,2])
-
-
- if np.isnan(mx) or np.isnan(my) or np.isnan(mz):
- mx = 0
- my = 0
- mz = 0
- # groundX = np.arange(mx-100,mx+100)
- # groundZ = np.arange(my-100,my+100)
- # groundXX, groundZZ = np.meshgrid(groundX, groundZ)
- # groundYY = np.zeros_like(groundXX)
- # groundMesh = ax3d.plot_surface(groundXX, groundZZ, groundYY, color='k', alpha=.5)
-
- axRange = 1000#session.board.square_length * 10
-
- # Setting the axes properties
- ax3d.set_xlim3d([mx-axRange, mx+axRange])
- ax3d.set_ylim3d([my-axRange, my+axRange])
- ax3d.set_zlim3d([mz-axRange, mz+axRange])
-
- tit1 = fig.text(.5, .96, "The FreeMoCap Project", fontsize=15, horizontalalignment='center')
- tit2 = fig.text(.5, .92, "Session: {}".format(session.sessionID), fontsize=8, horizontalalignment='center')
-
-
-
- ax3d.view_init(azim=azimuth, elev=elevation)
-
-
-
- ###
- ###
- ### β–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ
- ### β–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ
- ### β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ
- ### β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ
- ### β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ
- ###
- ###
-
-
- syncedVidPathListAll = list(sorted(session.syncedVidPath.glob('*.mp4')))
- numVids = len(syncedVidPathListAll)
-
- syncedVidPathList = syncedVidPathListAll.copy()
-
- vidAxesList = []
- vidAristList = []
- vidCapObjList = []
-
- list_of_vidOpenPoseArtistdicts = []
- list_of_vidMediaPipeArtistdicts = []
-
- if useDLC: vidDLCArtistList = []
-
- def build_2d_segment_artist_dict(vidNum, data_nCams_nFrames_nImgPts_XYC, dict_of_list_of_segment_idxs, segColor = 'k', lineWidth = 1, lineStyle = '-'):
- """
- Builds a dictionary of line artists for each body 2d segment.
- """
- segNames = list(dict_of_list_of_segment_idxs)
-
- dict_of_artist_objects = dict()
- for segNum, segName in enumerate(segNames):
-
- #determine color of segment, based on class of 'segColor' input
- if isinstance(segColor, str):
- thisRGBA = segColor
- elif isinstance(segColor, np.ndarray):
- thisRGBA = segColor
- elif isinstance(segColor, dict):
- thisRGBA = segColor[segName].copy()
- thisRGBA[-1] = .75
- elif isinstance(segColor, list):
- try:
- thisRGBA = segColor[segNum]
- except:
- print('Not enough colors provided, using Black instead')
- thisRGBA = 'k'
- else:
- thisRGBA = 'k'
-
- xData = data_nCams_nFrames_nImgPts_XYC[vidNum, startFrame, dict_of_list_of_segment_idxs[segName],0]
- yData = data_nCams_nFrames_nImgPts_XYC[vidNum, startFrame, dict_of_list_of_segment_idxs[segName],1]
-
- # #make NaN's invisible (i thought they already would be but???!!!!)
- # thisRGBAall = np.tile(thisRGBA,(len(xData),1))
- # thisRGBAall[np.isnan(xData),3] = 0
-
- xDataMasked = np.ma.masked_where(xData, np.isnan(xData))
- yDataMasked = np.ma.masked_where(yData, np.isnan(yData))
-
- dict_of_artist_objects[segName] = thisVidAxis.plot(
- xDataMasked,
- yDataMasked,
- linestyle=lineStyle,
- linewidth=lineWidth,
- color = thisRGBA,
- )[0]
- return dict_of_artist_objects
-
- # vidImageGrid = ImageGrid(fig, [.45, 0.05, .54, .9], nrows_ncols = (2,2), axes_pad = 0.1) # https://matplotlib.org/stable/gallery/axes_grid1/simple_axesgrid.html
- if numVids < 4:
- numRows = numVids
- numCols = 1
- else:
- numRows = int(np.ceil(numVids/2))
- numCols = 2
-
-
- vidAxGridSpec = fig.add_gridspec(numRows, numCols, left=.55, bottom=.025, right=.9, top=.9, wspace=.1, hspace=.1)
-
-
- for thisVidNum, thisVidPath in enumerate(syncedVidPathList):
- #make subplot for figure (and set position)
-
- if numVids < 4:
- thisVidAxis = fig.add_subplot(vidAxGridSpec[thisVidNum])
- elif numVids %2 > 0: #if odd number videos plot the first vid across 2 spots
- if thisVidNum==0:
- thisVidAxis = fig.add_subplot(vidAxGridSpec[0,:])
- else:
- thisVidAxis = fig.add_subplot(vidAxGridSpec[thisVidNum+1])
- else:
- thisVidAxis = fig.add_subplot(vidAxGridSpec[thisVidNum])
-
-
- thisVidAxis.set_axis_off()
-
- vidAxesList.append(thisVidAxis)
-
- #create video capture object
- thisVidCap = cv2.VideoCapture(str(thisVidPath))
-
-
- #create artist object for each video
- success, image = thisVidCap.read()
-
- assert success==True, "{} - failed to load an image".format(thisVidPath.stem) #make sure we have a frame
-
- vidAristList.append(thisVidAxis.imshow(cv2.cvtColor(image, cv2.COLOR_BGR2RGB)))
- vidCapObjList.append(thisVidCap)
-
-
-
- if useOpenPose:
- vidOpenPoseArtist_dict = dict()
- vidOpenPoseArtist_dict['op_body'] = build_2d_segment_artist_dict(thisVidNum, openPose_nCams_nFrames_nImgPts_XYC, dict_of_openPoseSegmentIdx_dicts['op_body'], segColor = dict_of_op_skel_lineColor)
- vidOpenPoseArtist_dict['op_rHand'] = build_2d_segment_artist_dict(thisVidNum, openPose_nCams_nFrames_nImgPts_XYC, dict_of_openPoseSegmentIdx_dicts['op_rHand'], segColor=np.append(humon_red, .75), lineWidth=.5)
- vidOpenPoseArtist_dict['op_lHand'] = build_2d_segment_artist_dict(thisVidNum, openPose_nCams_nFrames_nImgPts_XYC, dict_of_openPoseSegmentIdx_dicts['op_lHand'], segColor=np.append(humon_blue, .75), lineWidth=.5)
- vidOpenPoseArtist_dict['op_face'] = build_2d_segment_artist_dict(thisVidNum, openPose_nCams_nFrames_nImgPts_XYC, dict_of_openPoseSegmentIdx_dicts['op_face'], segColor = np.array([1.,1.,1.,1]), lineWidth=.25)
- list_of_vidOpenPoseArtistdicts.append(vidOpenPoseArtist_dict)
-
- if useMediaPipe:
- vidMediaPipeArtist_dict = dict()
- vidMediaPipeArtist_dict['mp_body'] = build_2d_segment_artist_dict(thisVidNum, mediaPipe_nCams_nFrames_nImgPts_XYC, dict_of_mediaPipeSegmentIdx_dicts['mp_body'], segColor = 'g')
- vidMediaPipeArtist_dict['mp_rHand'] = build_2d_segment_artist_dict(thisVidNum, mediaPipe_nCams_nFrames_nImgPts_XYC, dict_of_mediaPipeSegmentIdx_dicts['mp_rHand'], segColor=np.append(humon_red, .75), lineWidth=.5)
- vidMediaPipeArtist_dict['mp_lHand'] = build_2d_segment_artist_dict(thisVidNum, mediaPipe_nCams_nFrames_nImgPts_XYC, dict_of_mediaPipeSegmentIdx_dicts['mp_lHand'], segColor=np.append(humon_blue, .75), lineWidth=.5)
- list_of_vidMediaPipeArtistdicts.append(vidMediaPipeArtist_dict)
-
-
- if useDLC:
-
- vidDLCArtistList.append(thisVidAxis.plot(
- dlcData_nCams_nFrames_nImgPts_XYC[thisVidNum,startFrame,:,0],
- dlcData_nCams_nFrames_nImgPts_XYC[thisVidNum,startFrame,:,1],
- linestyle='none',
- marker = '.',
- markersize = 1,
- color='w',
- markerfacecolor='none' ))
-
- ###
- ###
- ### β–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ
- ### β–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ
- ### β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ
- ### β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ
- ### β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ
- ###
- ###
-
-
- fps=30 #NOTE - This should be saved in the session Class some how
- timestamps = np.arange(0, numFrames)/fps
- if useMediaPipe:
- rHandIdx = 20
- lHandIdx = 19
- rHandX = mediaPipe_skel_fr_mar_xyz[:,rHandIdx,0]/1000 #convert mm to meters
- rHandY = -mediaPipe_skel_fr_mar_xyz[:,rHandIdx,1]/1000
- lHandX = mediaPipe_skel_fr_mar_xyz[:,lHandIdx,0]/1000
- lHandY = -mediaPipe_skel_fr_mar_xyz[:,lHandIdx,1]/1000
-
- if useOpenPose:
- rHandIdx = 4
- lHandIdx = 7
- rHandX = openPose_skel_fr_mar_xyz[:,rHandIdx,0]/1000 #convert mm to meters
- rHandY = -openPose_skel_fr_mar_xyz[:,rHandIdx,1]/1000
- lHandX = openPose_skel_fr_mar_xyz[:,lHandIdx,0]/1000
- lHandY = -openPose_skel_fr_mar_xyz[:,lHandIdx,1]/1000
-
-
- linePlotWidth = .45
- linePlotHeight = .14
-
- yTimeSeriesAx = fig.add_subplot(position=[.07, .225, linePlotWidth, linePlotHeight])
- yTimeSeriesAx.set_title('Hand Position vs Time', fontsize = 7, pad=2)
-
- yTimeSeriesAx.plot(timestamps, rHandY, color=humon_red, linewidth=.75, label='Right Hand')
- yTimeSeriesAx.plot(timestamps, lHandY, color=humon_blue, linewidth=.75, label='Left Hand')
-
- timeRange = 3
- ylimRange = .6
-
- yCurrTimeArtists = dict()
- yCurrTimeYdata = dict()
- yCurrTimeArtists['blackLine'] = yTimeSeriesAx.plot([startFrame/fps, startFrame/fps], [-ylimRange, ylimRange*2], color='k', linewidth=1)
-
- yCurrTimeArtists['rHandDot'] = yTimeSeriesAx.plot([startFrame/fps], [rHandY[startFrame]], markeredgecolor=humon_red, markerfacecolor = 'k',marker='o', markersize=3)
- yCurrTimeYdata['rHandDot'] = rHandY
- yCurrTimeArtists['lHandDot'] = yTimeSeriesAx.plot([startFrame/fps], [lHandY[startFrame]], markeredgecolor=humon_blue, markerfacecolor = 'k', marker='o', markersize=3)
- yCurrTimeYdata['lHandDot'] = lHandY
-
-
- yCurrTimeArtists['frameNumber'] = yTimeSeriesAx.text(startFrame/fps+3/fps, ylimRange*.7, "Frame# " + str(startFrame), fontsize=6)
-
- yTimeSeriesAx.tick_params(labelsize=6, direction='in', width=.5)
- yTimeSeriesAx.tick_params( pad=2)
-
-
- yTimeSeriesAx.set_ylabel('Vertical (m)', fontsize=7, labelpad=3)
- yTimeSeriesAx.set_ylim([-ylimRange, ylimRange])
- yTimeSeriesAx.set_xlim([(startFrame/fps)-timeRange, (startFrame/fps)+timeRange])
-
-
-
- for axis in ['top','bottom','left','right']:
- yTimeSeriesAx.spines[axis].set_linewidth(0.5)
-
-
-
- yTimeSeriesAx.legend(loc='upper left', fontsize=6)
-
-
-
- xTimeSeriesAx = fig.add_subplot(position=[.07, 0.05, linePlotWidth, linePlotHeight])
-
- xTimeSeriesAx.plot(timestamps, rHandX, color=humon_red, linewidth=.75, label='Right Hand')
- xTimeSeriesAx.plot(timestamps, lHandX, color=humon_blue, linewidth=.75, label='Left Hand')
-
-
-
- xCurrTimeArtists = dict()
- xCurrTimeYdata = dict()
- xCurrTimeArtists['blackLine'] = xTimeSeriesAx.plot([startFrame/fps, startFrame/fps], [-ylimRange, ylimRange], color='k', linewidth=1)
- xCurrTimeArtists['rHandDot'] = xTimeSeriesAx.plot([startFrame/fps], [rHandX[startFrame]], markeredgecolor=humon_red, markerfacecolor = 'k',marker='o', markersize=3)
- xCurrTimeYdata['rHandDot'] = rHandX
- xCurrTimeArtists['lHandDot'] = xTimeSeriesAx.plot([startFrame/fps], [lHandX[startFrame]], markeredgecolor=humon_blue, markerfacecolor = 'k', marker='o', markersize=3)
- xCurrTimeYdata['lHandDot'] = lHandX
-
-
-
- xTimeSeriesAx.tick_params(labelsize=6, direction='in', width=.5)
- xTimeSeriesAx.tick_params( pad=2)
-
- xTimeSeriesAx.set_ylabel('Left/Right (m)', fontsize=7, labelpad=0)
- xTimeSeriesAx.set_xlabel('Time(sec)', fontsize=8, labelpad=0)
-
- xTimeSeriesAx.set_ylim([-ylimRange, ylimRange])
-
- xTimeSeriesAx.set_xlim([(startFrame/fps)-timeRange, (startFrame/fps)+timeRange])
-
-
- for axis in ['top','bottom','left','right']:
- xTimeSeriesAx.spines[axis].set_linewidth(0.5)
-
-
-
- # #slider
- # axControls = fig.add_subplot(2,1,2)
- # axControls.set_position([0.25, 0.01, 0.6, 0.05])
- # animSlider = Slider(
- # ax=axControls,
- # label="FrameNum",
- # valmin=10,
- # valmax=numFrames,
- # valinit=10,
- # orientation="horizontal"
- # )
-
- # thisVidAxis.text(-565,1440, 'Music - artist: Neon Exdeath, song: Meowmaline, album: Jewel Tones',color=humon_green, fontsize=6)
- thisVidAxis.text(0,thisVidCap.get(cv2.CAP_PROP_FRAME_HEIGHT)*1.06, 'github.com/jonmatthis/freemocap || freemocap.org',color=humon_green, fontsize=6)
-
- logoAx = fig.add_subplot(position=[.85, .85, .15, .15])
- logoIm = cv2.imread(r'logo\fmc-logo-black-border-white-bkgd.png') #JSM NOTE - THis doesn't work, but SOMETIMES IT DOES?!
- if logoIm is not None: logoAx.imshow(cv2.cvtColor(logoIm, cv2.COLOR_BGR2RGB))
- logoAx.axis('off')
-
- # if recordVid:
- # animationFramePath = session.sessionPath / "animationFrames"
- # animationFramePath.mkdir(parents=True, exist_ok=True)
-
- # Creating the Animation object
- out_animation = animation.FuncAnimation(fig, update_figure, range(startFrame,numFrames), fargs=(),
- interval=1, blit=False)
-
-
-
- if recordVid:
- # vidSavePath = '{}_animVid.mp4'.format(str(session.sessionPath / session.sessionID))
- gifSavePath = '{}_animVid.gif'.format(str(session.sessionPath / session.sessionID)) #NOTE - saving as a gif first then converting to MP4, because saving directly to MP4 requires users to install ffmpeg (independently of the pip install)
- with console.status('Saving animation for {}'.format(session.sessionID)):
-
- # ffmpeg, not actually much faster :-/
- # tik = time.time()
- # vidSavePath = f'{str(session.sessionPath / session.sessionID)}_outVid.mp4'
- # video_writer = animation.FFMpegWriter(fps=fps)
- # out_animation.save(vidSavePath, writer=video_writer)
- # print(f'Done! Saved animation video to: {str(vidSavePath)}')
- # tok = time.time()-tik
- # print(f'Took {tok} seconds to save animation video wtih ffmpeg')
- # # # except:
-
- tik = time.time()
- Writer = animation.writers['pillow']
- writer = Writer(fps=fps, metadata=dict(artist='FreeMoCap'))#, bitrate=1800)
- out_animation.save(gifSavePath, writer = writer)
- gif_filepath = mp.VideoFileClip(gifSavePath)
- gif_filepath.write_videofile(gifSavePath.replace('.gif','.mp4'))
- os.remove(gifSavePath)
- tok = time.time()-tik
- print(f'Took {tok} seconds to save animation video wtih pillow')
-
-
-
-
- try:
- if showAnimation:
- with console.status('Playing Skeleton animation! Close the `matplotlib` window to continue...'):
- plt.pause(0.1)
- plt.draw()
- except:
- pass
-
-
-
-
-
-
- ###
- ###
- ### β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ
- ### β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ
- ### β–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ
- ### β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ
- ### β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ
- ###
- ###
-def formatOpenPoseStickIndices():
- """
- generate dictionary of arrays, each containing the 'connect-the-dots' order to draw a given body segment
-
- returns:
- openPoseBodySegmentIds= a dictionary of arrays containing indices of individual body segments (Note, a lot of markerless mocap comp sci types like to say 'pose' instead of 'body'. They also use 'pose' to refer to camera 6 DoF position sometimes. Comp sci is frustrating like that lol)
- openPoseHandIds = a dictionary of arrays containing indices of individual hand segments, along with offset to know where to start in the 'skel_fr_mar_xyz.shape[1]' part of the array
- dict_of_op_skel_lineColor = a dictionary of arrays, each containing the color (RGBA) to use for a given body segment
- """
- dict_of_openPoseSegmentIdx_dicts = dict()
-
- #make body dictionary
- openPoseBodySegmentIds = dict()
- openPoseBodySegmentIds['op_head'] = [17, 15, 0, 1,0, 16, 18, ]
- openPoseBodySegmentIds['op_spine'] = [1,8,5,1, 2, 12, 8, 9, 5, 1, 2, 8]
- openPoseBodySegmentIds['op_rArm'] = [1, 2, 3, 4, ]
- openPoseBodySegmentIds['op_lArm'] = [1, 5, 6, 7, ]
- openPoseBodySegmentIds['op_rLeg'] = [8, 9, 10, 11, 22, 23, 11, 24, ]
- openPoseBodySegmentIds['op_lLeg'] = [8,12, 13, 14, 19, 20, 14, 21,]
- dict_of_openPoseSegmentIdx_dicts['op_body'] = openPoseBodySegmentIds
-
-
- #make colors dictionary
- openPoseBodyColor = np.array([50, 89, 0])/255
- openPoseRightColor = np.array([230, 50, 0])/255
- openPoseLeftColor = np.array([0, 50, 230])/255
-
- dict_of_op_skel_lineColor = dict()
- dict_of_op_skel_lineColor['op_head'] = np.append(openPoseBodyColor, 0.5)
- dict_of_op_skel_lineColor['op_spine'] = np.append(openPoseBodyColor, 1)
- dict_of_op_skel_lineColor['op_rArm'] = np.append(openPoseRightColor, 1)
- dict_of_op_skel_lineColor['op_lArm'] = np.append(openPoseLeftColor, 1)
- dict_of_op_skel_lineColor['op_rLeg'] = np.append(openPoseRightColor, 1)
- dict_of_op_skel_lineColor['op_lLeg'] = np.append(openPoseLeftColor, 1)
-
-
- # Make some handy maps ;D
- openPoseHandIds = dict()
- rHandIDstart = 25
- lHandIDstart = rHandIDstart + 21
-
- openPoseHandIds['op_thumb'] = np.array([0, 1, 2, 3, 4, ])
- openPoseHandIds['op_index'] = np.array([0, 5, 6, 7, 8, ])
- openPoseHandIds['op_bird']= np.array([0, 9, 10, 11, 12, ])
- openPoseHandIds['op_ring']= np.array([0, 13, 14, 15, 16, ])
- openPoseHandIds['op_pinky'] = np.array([0, 17, 18, 19, 20, ])
-
-
- rHand_dict = copy.deepcopy(openPoseHandIds.copy()) #copy.deepcopy() is necessary to make sure the dicts are independent of each other
- lHand_dict = copy.deepcopy(rHand_dict)
-
- for key in rHand_dict:
- rHand_dict[key] += rHandIDstart
- lHand_dict[key] += lHandIDstart
-
- dict_of_openPoseSegmentIdx_dicts['op_rHand'] = rHand_dict
- dict_of_openPoseSegmentIdx_dicts['op_lHand'] = lHand_dict
-
-
- #how to face --> :D <--
- openPoseFaceIDs = dict()
- faceIDStart = 67
- #define face parts
- openPoseFaceIDs['op_jaw'] = np.arange(0,16) + faceIDStart
- openPoseFaceIDs['op_rBrow'] = np.arange(17,21) + faceIDStart
- openPoseFaceIDs['op_lBrow'] = np.arange(22,26) + faceIDStart
- openPoseFaceIDs['op_noseRidge'] = np.arange(27,30) + faceIDStart
- openPoseFaceIDs['op_noseBot'] = np.arange(31,35) + faceIDStart
- openPoseFaceIDs['op_rEye'] = np.concatenate((np.arange(36,41), [36])) + faceIDStart
- openPoseFaceIDs['op_lEye'] = np.concatenate((np.arange(42,47), [42])) + faceIDStart
- openPoseFaceIDs['op_upperLip'] = np.concatenate((np.arange(48,54), np.flip(np.arange(60, 64)), [48])) + faceIDStart
- openPoseFaceIDs['op_lowerLip'] = np.concatenate(([60], np.arange(64,67), np.arange(54, 59), [48], [60])) + faceIDStart
- openPoseFaceIDs['op_rPupil'] = np.array([68]) + faceIDStart
- openPoseFaceIDs['op_lPupil'] = np.array([69]) + faceIDStart #nice
-
- dict_of_openPoseSegmentIdx_dicts['op_face'] = openPoseFaceIDs
-
- return dict_of_openPoseSegmentIdx_dicts, dict_of_op_skel_lineColor
-
-
-
-###
-### β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ
-### β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ
-### β–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ
-### β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ
-### β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ
-###
-###
-def formatMediaPipeStickIndices():
- """
- generate dictionary of arrays, each containing the 'connect-the-dots' order to draw a given body segment
-
- returns:
- mediaPipeBodySegmentIds= a dictionary of arrays containing indices of individual body segments (Note, a lot of markerless mocap comp sci types like to say 'pose' instead of 'body'. They also use 'pose' to refer to camera 6 DoF position sometimes. Comp sci is frustrating like that lol)
- mediaPipeHandIds = a dictionary of arrays containing indices of individual hand segments, along with offset to know where to start in the 'skel_fr_mar_xyz.shape[1]' part of the array
- dict_of_mp_skel_lineColor = a dictionary of arrays, each containing the color (RGBA) to use for a given body segment
- """
- dict_of_mediaPipeSegmentIdx_dicts = dict()
-
- #make body dictionary
- mediaPipeBodySegmentIds = dict()
- mediaPipeBodySegmentIds['mp_head'] = [8, 6, 5, 4, 0, 10, 9, 0, 1, 2, 3, 7 ]
- mediaPipeBodySegmentIds['mp_tors'] = [12, 11, 24, 23, 12]
- mediaPipeBodySegmentIds['mp_rArm'] = [12, 14, 16, 18, 20, 16, 22 ]
- mediaPipeBodySegmentIds['mp_lArm'] = [11, 13, 15, 17, 19, 15, 21]
- mediaPipeBodySegmentIds['mp_rLeg'] = [24, 26, 28, 30, 32, 28, ]
- mediaPipeBodySegmentIds['mp_lLeg'] = [23, 25, 27, 29, 31, 27, ]
- dict_of_mediaPipeSegmentIdx_dicts['mp_body'] = mediaPipeBodySegmentIds
-
- #make colors dictionary
- mediaPipeBodyColor = np.array([125,106,0])/255
- mediaPipeRightColor = np.array([230, 0, 169])/255
- mediaPipeLeftColor = np.array([0, 176, 176])/255
- dict_of_mp_skel_lineColor = dict()
-
- dict_of_mp_skel_lineColor['mp_head'] = np.append(mediaPipeBodyColor, .5)
- dict_of_mp_skel_lineColor['mp_tors'] = np.append(mediaPipeBodyColor, 1)
- dict_of_mp_skel_lineColor['mp_rArm'] = np.append(mediaPipeRightColor, 1)
- dict_of_mp_skel_lineColor['mp_lArm'] = np.append(mediaPipeLeftColor, 1)
- dict_of_mp_skel_lineColor['mp_rLeg'] = np.append(mediaPipeRightColor, 1)
- dict_of_mp_skel_lineColor['mp_lLeg'] = np.append(mediaPipeLeftColor, 1)
-
-
- # Make some handy maps ;D
- mediaPipeHandIds = dict()
- rHandIDstart = 33
- lHandIDstart = rHandIDstart + 21
-
- mediaPipeHandIds['mp_thumb'] = np.array([0, 1, 2, 3, 4, ])
- mediaPipeHandIds['mp_index'] = np.array([0, 5, 6, 7, 8, ])
- mediaPipeHandIds['mp_bird']= np.array([0, 9, 10, 11, 12, ])
- mediaPipeHandIds['mp_ring']= np.array([0, 13, 14, 15, 16, ])
- mediaPipeHandIds['mp_pinky'] = np.array([0, 17, 18, 19, 20, ])
-
-
- rHand_dict = copy.deepcopy(mediaPipeHandIds.copy()) #copy.deepcopy() is necessary to make sure the dicts are independent of each other
- lHand_dict = copy.deepcopy(rHand_dict)
-
- for key in rHand_dict:
- rHand_dict[key] += rHandIDstart
- lHand_dict[key] += lHandIDstart
-
- dict_of_mediaPipeSegmentIdx_dicts['mp_rHand'] = rHand_dict
- dict_of_mediaPipeSegmentIdx_dicts['mp_lHand'] = lHand_dict
-
-
- # #how to face --> :D <--
- # mediaPipeFaceIDs = dict()
- # faceIDStart = 67
- # #define face parts
- # mediaPipeFaceIDs['mp_jaw'] = np.arange(0,16) + faceIDStart
- # mediaPipeFaceIDs['mp_rBrow'] = np.arange(17,21) + faceIDStart
- # mediaPipeFaceIDs['mp_lBrow'] = np.arange(22,26) + faceIDStart
- # mediaPipeFaceIDs['mp_noseRidge'] = np.arange(27,30) + faceIDStart
- # mediaPipeFaceIDs['mp_noseBot'] = np.arange(31,35) + faceIDStart
- # mediaPipeFaceIDs['mp_rEye'] = np.concatenate((np.arange(36,41), [36])) + faceIDStart
- # mediaPipeFaceIDs['mp_lEye'] = np.concatenate((np.arange(42,47), [42])) + faceIDStart
- # mediaPipeFaceIDs['mp_upperLip'] = np.concatenate((np.arange(48,54), np.flip(np.arange(60, 64)), [48])) + faceIDStart
- # mediaPipeFaceIDs['mp_lowerLip'] = np.concatenate(([60], np.arange(64,67), np.arange(54, 59), [48], [60])) + faceIDStart
- # mediaPipeFaceIDs['mp_rPupil'] = np.array([68]) + faceIDStart
- # mediaPipeFaceIDs['mp_lPupil'] = np.array([69]) + faceIDStart #nice
-
- # dict_of_mediaPipeSegmentIdx_dicts['mp_face'] = mediaPipeFaceIDs
-
- return dict_of_mediaPipeSegmentIdx_dicts, dict_of_mp_skel_lineColor
-
-
-if __name__ == '__main__':
- PlaySkeletonAnimation()
diff --git a/freemocap/playskeleton.py b/freemocap/playskeleton.py
deleted file mode 100644
index 57dc24e5..00000000
--- a/freemocap/playskeleton.py
+++ /dev/null
@@ -1,591 +0,0 @@
-# -*- coding: utf-8 -*-
-"""
-Created on Fri Feb 26 12:51:21 2021
-
-@author: Rontc
-"""
-
-import numpy as np
-
-# from mpl_toolkits.mplot3d import Axes3D
-import matplotlib.pyplot as plt
-import cv2
-from pathlib import Path
-import pyqtgraph as pg
-
-########################################################################################################################################
-########################################################################################################################################
-##
-## β–ˆβ–ˆβ–ˆβ€ β–ˆβ–ˆβ–ˆβ€ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ€ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ€β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ€ β–ˆβ–ˆβ€ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ€ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ€β–ˆβ–ˆβ€ β–ˆβ–ˆβ€β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ
-## β–ˆβ–ˆβ–ˆβ–ˆβ€ β–ˆβ–ˆβ–ˆβ–ˆβ€β–ˆβ–ˆβ€β€β€β–ˆβ–ˆβ€β€β€β€β–ˆβ–ˆβ€β€β€β€β–ˆβ–ˆβ€β€β€β–ˆβ–ˆβ€β–ˆβ–ˆβ€ β–ˆβ–ˆβ€β€β€β€β–ˆβ–ˆβ€β€β€β€β–ˆβ–ˆβ€β€β€β€β–ˆβ–ˆβ€ β–ˆβ–ˆβ€β–ˆβ–ˆβ€β€β€β–ˆβ–ˆ
-## β–ˆβ–ˆβ€β–ˆβ–ˆβ–ˆβ–ˆβ€β–ˆβ–ˆβ€β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ€ β–ˆβ–ˆβ€ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ€β€β–ˆβ–ˆβ€ β–ˆβ–ˆβ€ β–ˆβ–ˆβ€ β–ˆβ–ˆβ€ β–ˆβ–ˆβ€ β–ˆβ–ˆβ€β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ
-## β–ˆβ–ˆβ€β€β–ˆβ–ˆβ€β€β–ˆβ–ˆβ€β–ˆβ–ˆβ€β€β€β–ˆβ–ˆβ€ β–ˆβ–ˆβ€ β–ˆβ–ˆβ€β€β€β€β€ β–ˆβ–ˆβ€ β–ˆβ–ˆβ€ β–ˆβ–ˆβ€ β–ˆβ–ˆβ€ β–ˆβ–ˆβ€ β–ˆβ–ˆβ€β–ˆβ–ˆβ€β€β€β–ˆβ–ˆ
-## β–ˆβ–ˆβ€     β–ˆβ–ˆβ€β–ˆβ–ˆβ€ β–ˆβ–ˆβ€ β–ˆβ–ˆβ€ β–ˆβ–ˆβ€ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ€β€β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ€β€ β–ˆβ–ˆβ€ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ€β–ˆβ–ˆβ€β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ
-##
-########################################################################################################################################
-########################################################################################################################################
-
-
-def ReplaySkeleton_matplotlib(
- session,
- vidType=1,
- startFrame=40,
- azimuth=-90,
- elevation=-80,
- useOpenPose=True,
- useMediaPipe=False,
- useDLC=False,
-):
-
-
- mean_charuco_fr_mar_xyz = np.load(session.dataArrayPath/'charuco_3d_points.npy')
-
- if useOpenPose:
- skel_fr_mar_xyz = np.load(session.dataArrayPath / "openPoseSkel_3d.npy")
-
- if useMediaPipe:
- mediaPipe_skel_fr_mar_xyz = np.load(
- session.dataArrayPath / "mediaPipeSkel_3d.npy"
- )
-
- if useDLC:
- dlc_fr_mar_xyz = np.load(session.dataArrayPath / "deepLabCut_3d.npy")
- dlc0 = np.squeeze(dlc_fr_mar_xyz[:, 0, :])
- dlc1 = np.squeeze(dlc_fr_mar_xyz[:, 1, :])
- dlc2 = np.squeeze(dlc_fr_mar_xyz[:, 2, :])
- ballTrailLen = 4
-
- if useOpenPose:
- for camera_number in range(session.numCams):
- imgPathList = session.session_settings['openPose_imgPathList']
-
-
- camImgPathList = {}
- for cam in range(session.numCams):
- camImgPathList[cam] = list(sorted(Path(imgPathList[cam]).glob('*.png')))
- #session.numFrames = len(camImgPathList[cam]) #will need to perhaps put a check in on whether numFrames between cameras are the same
-
-
-# define Skeleton connections
-# head = [17, 15, 0, 16, 18]
- head = [ 15, 0, 16]
- spine = [0,1,8]
- rArm = [17, 15, 0, 16, 18]
- rArm = [4, 3, 2, 1]
- lArm = [1, 5, 6, 7]
- rLeg = [11, 10, 9, 8]
- lLeg = [14, 13, 12, 8]
- rFoot = [11, 23, 22, 11, 24]
- lFoot = [14, 20, 19, 14, 21]
-
- # Make some handy maps ;D
- rHandIDstart = 25
- lHandIDstart = rHandIDstart + 21
-
- thumb = np.array([0, 1, 2, 3, 4])
- index = np.array([0, 5, 6, 7, 8])
- bird = np.array([0, 9, 10, 11, 12])
- ring = np.array([0, 13, 14, 15, 16])
- pinky = np.array([0, 17, 18, 19, 20])
-
- fig = plt.figure(figsize=(11, 8))
-
- if vidType == 0:
- axMain = fig.add_subplot(111, projection="3d")
- elif vidType == 1:
- axMain = fig.add_subplot(121, projection="3d")
- axCam1 = fig.add_subplot(122)
-
- # fig.tight_layout(h_pad = 5)
- axMain.view_init(azim=azimuth, elev=elevation)
- plt.ion()
- for fr in range(startFrame, session.numFrames):
- fig.suptitle(["Frame# - ", str(fr)])
- axMain.cla()
-
- if vidType == 1:
- axCam1.cla()
-
- char_x = mean_charuco_fr_mar_xyz[:][:, 0]
- char_y = mean_charuco_fr_mar_xyz[:][:, 1]
- char_z = mean_charuco_fr_mar_xyz[:][:, 2]
-
- # plot skeleton (openPose by default)
-
- sk_x = skel_fr_mar_xyz[fr, :, 0] # skeleton x data
- sk_y = skel_fr_mar_xyz[fr, :, 1] # skeleton y data
- sk_z = skel_fr_mar_xyz[fr, :, 2] # skeleton z data
-
- axMain.scatter3D(sk_x, sk_y, sk_z, marker=".", color="k", s=4.0)
- axMain.plot(
- sk_x[head], sk_y[head], sk_z[head], linestyle="-", color="g", linewidth=1.0
- )
- axMain.plot(
- sk_x[spine],
- sk_y[spine],
- sk_z[spine],
- linestyle="-",
- color="g",
- linewidth=1.0,
- )
- axMain.plot(
- sk_x[rArm], sk_y[rArm], sk_z[rArm], linestyle="-", color="r", linewidth=1.0
- )
- axMain.plot(
- sk_x[lArm], sk_y[lArm], sk_z[lArm], linestyle="-", color="b", linewidth=1.0
- )
- axMain.plot(
- sk_x[rLeg], sk_y[rLeg], sk_z[rLeg], linestyle="-", color="r", linewidth=1.0
- )
- axMain.plot(
- sk_x[lLeg], sk_y[lLeg], sk_z[lLeg], linestyle="-", color="b", linewidth=1.0
- )
- axMain.plot(
- sk_x[rFoot],
- sk_y[rFoot],
- sk_z[rFoot],
- linestyle="-",
- color="r",
- linewidth=1.0,
- )
- axMain.plot(
- sk_x[lFoot],
- sk_y[lFoot],
- sk_z[lFoot],
- linestyle="-",
- color="b",
- linewidth=1.0,
- )
-
- # plot handybois
- # right hand
- axMain.plot(
- sk_x[thumb + rHandIDstart],
- sk_y[thumb + rHandIDstart],
- sk_z[thumb + rHandIDstart],
- linestyle="-",
- color="r",
- linewidth=1.0,
- )
- axMain.plot(
- sk_x[index + rHandIDstart],
- sk_y[index + rHandIDstart],
- sk_z[index + rHandIDstart],
- linestyle="-",
- color="r",
- linewidth=1.0,
- )
- axMain.plot(
- sk_x[bird + rHandIDstart],
- sk_y[bird + rHandIDstart],
- sk_z[bird + rHandIDstart],
- linestyle="-",
- color="r",
- linewidth=1.0,
- )
- axMain.plot(
- sk_x[ring + rHandIDstart],
- sk_y[ring + rHandIDstart],
- sk_z[ring + rHandIDstart],
- linestyle="-",
- color="r",
- linewidth=1.0,
- )
- axMain.plot(
- sk_x[pinky + rHandIDstart],
- sk_y[pinky + rHandIDstart],
- sk_z[pinky + rHandIDstart],
- linestyle="-",
- color="r",
- linewidth=1.0,
- )
-
- # left hand
- axMain.plot(
- sk_x[thumb + lHandIDstart],
- sk_y[thumb + lHandIDstart],
- sk_z[thumb + lHandIDstart],
- linestyle="-",
- color="b",
- linewidth=1.0,
- )
- axMain.plot(
- sk_x[index + lHandIDstart],
- sk_y[index + lHandIDstart],
- sk_z[index + lHandIDstart],
- linestyle="-",
- color="b",
- linewidth=1.0,
- )
- axMain.plot(
- sk_x[bird + lHandIDstart],
- sk_y[bird + lHandIDstart],
- sk_z[bird + lHandIDstart],
- linestyle="-",
- color="b",
- linewidth=1.0,
- )
- axMain.plot(
- sk_x[ring + lHandIDstart],
- sk_y[ring + lHandIDstart],
- sk_z[ring + lHandIDstart],
- linestyle="-",
- color="b",
- linewidth=1.0,
- )
- axMain.plot(
- sk_x[pinky + lHandIDstart],
- sk_y[pinky + lHandIDstart],
- sk_z[pinky + lHandIDstart],
- linestyle="-",
- color="b",
- linewidth=1.0,
- )
-
- # plot mediapipe
- mp_sk_x = mediaPipe_skel_fr_mar_xyz[fr, :, 0] # skeleton x data
- mp_sk_y = mediaPipe_skel_fr_mar_xyz[fr, :, 1] # skeleton y data
- mp_sk_z = mediaPipe_skel_fr_mar_xyz[fr, :, 2] # skeleton z data
- axMain.scatter3D(mp_sk_x, mp_sk_y, mp_sk_z, marker=".", color="g", s=8.0)
-
- # plot deeplabcut
-
- dlc_x = dlc_fr_mar_xyz[fr, :, 0]
- dlc_y = dlc_fr_mar_xyz[fr, :, 1]
- dlc_z = dlc_fr_mar_xyz[fr, :, 2]
-
- axMain.scatter3D(dlc_x, dlc_y, dlc_z, marker="o", color="r", s=24.0)
-
- # plot charuco grid
- axMain.scatter(char_x, char_y, char_z, marker="o")
-
- # #plot camera positions (I think...)
- # for camNum in range(len(session.cgroup.cameras)):
- # axMain.scatter(session.cgroup.cameras[camNum].tvec[0], session.cgroup.cameras[camNum].tvec[1], session.cgroup.cameras[camNum].tvec[2], marker = 'p')
- axRange = session.board.square_length * 10
- mx = np.nanmean(char_x)
- my = np.nanmean(char_y)
- mz = np.nanmean(char_z)
-
- axMain.set_xlim(mx - axRange, mx + axRange)
- axMain.set_ylim(my - axRange, my + axRange)
- axMain.set_zlim(mz - axRange, mz + axRange)
-
- axMain.set_xlabel("x")
- axMain.set_ylabel("y")
- axMain.set_zlabel("z")
-
- if vidType == 0:
- pass
- elif vidType == 1:
- axCam1.imshow(
- cv2.cvtColor(cv2.imread(str(camImgPathList[0][fr])), cv2.COLOR_BGR2RGB)
- )
- axCam1.axis("off")
-
- plt.pause(0.01)
- plt.show()
-
- frameName = str(fr).zfill(6)
- saveFrameName = "{}.png".format(frameName)
- saveFramePath = session.imOutPath / saveFrameName
- fig.savefig(saveFramePath)
-
-
-########################################################################################################################################
-########################################################################################################################################
-### β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ€ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ€ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ€β–ˆβ–ˆβ–ˆβ€ β–ˆβ–ˆβ€ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ€ β–ˆβ–ˆ
-### β–ˆβ–ˆβ€β€β€β€β–ˆβ–ˆβ€β–ˆβ–ˆβ€β€β€β–ˆβ–ˆβ€β–ˆβ–ˆβ€β€β€β€β€β€β–ˆβ–ˆβ–ˆβ–ˆβ€ β–ˆβ–ˆβ€ β–ˆβ–ˆβ€β€β€β€β€β€ β–ˆβ–ˆ
-### β–ˆβ–ˆβ€ β–ˆβ–ˆβ€β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ€β€β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ€ β–ˆβ–ˆβ€β–ˆβ–ˆβ€ β–ˆβ–ˆβ€ β–ˆβ–ˆβ€ β–ˆβ–ˆβ–ˆβ€β–ˆβ–ˆ
-### β–ˆβ–ˆβ€ β–ˆβ–ˆβ€β–ˆβ–ˆβ€β€β€β€β€ β–ˆβ–ˆβ€β€β€β€ β–ˆβ–ˆβ€β€β–ˆβ–ˆβ€β–ˆβ–ˆβ€ β–ˆβ–ˆβ€ β–ˆβ–ˆβ€β–ˆβ–ˆ
-### β€β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ€β€β–ˆβ–ˆβ€ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ€β–ˆβ–ˆβ€ β€β–ˆβ–ˆβ–ˆβ–ˆβ€ β€β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ€β€β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ
-########################################################################################################################################
-########################################################################################################################################
-
-
-
-def ReplaySkeleton_matplotlib( session,
- vidType=1,
- startFrame=40,
- azimuth=-90,
- elevation=-80,
- useOpenPose=True,
- useMediaPipe=False,
- useDLC=False):
-
- session.imOutPath.mkdir(exist_ok = True)
- mean_charuco_fr_mar_xyz = np.load(session.dataArrayPath/'charuco_3d_points.npy')
-
-
- if session.useMediaPipe:
- mediaPipe_skel_fr_mar_xyz = np.load(session.dataArrayPath/'mediaPipeSkel_3d.npy')
- imgPathList = session.session_settings['mediaPipe_imgPathList']
- #session.numCams = len(session.mediaPipe_imgPathList)
-
- if session.useOpenPose:
- skel_fr_mar_xyz = np.load(session.dataArrayPath/'openPoseSkel_3d.npy')
- imgPathList = session.session_settings['openPose_imgPathList']
- #session.numCams = len(session.openPose_imgPathList)
-
- if session.useDLC:
- dlc_fr_mar_xyz = np.load(session.dataArrayPath / "deepLabCut_3d.npy")
- dlc0 = np.squeeze(dlc_fr_mar_xyz[:, 0, :])
- dlc1 = np.squeeze(dlc_fr_mar_xyz[:, 1, :])
- dlc2 = np.squeeze(dlc_fr_mar_xyz[:, 2, :])
- ballTrailLen = 4
-
- camImgPathList = {}
- for cam in range(session.numCams):
- camImgPathList[cam] = list(sorted(Path(imgPathList[cam]).glob('*.png')))
- #session.numFrames = len(camImgPathList[cam]) #will need to perhaps put a check in on whether numFrames between cameras are the same
-
-
-# define Skeleton connections
-# head = [17, 15, 0, 16, 18]
- head = [ 15, 0, 16]
- spine = [0,1,8]
- rArm = [4 ,3 ,2 ,1]
- lArm = [1, 5, 6, 7]
- rLeg = [11, 10, 9, 8]
- lLeg = [14, 13, 12, 8]
- rFoot = [11, 23, 22, 11, 24]
- lFoot = [14, 20, 19, 14, 21]
-
- # Make some handy maps ;D
- rHandIDstart = 25
- lHandIDstart = rHandIDstart + 21
-
- thumb = np.array([0, 1, 2, 3, 4])
- index = np.array([0, 5, 6, 7, 8])
- bird = np.array([0, 9, 10, 11, 12])
- ring = np.array([0, 13, 14, 15, 16])
- pinky = np.array([0, 17, 18, 19, 20])
-
- fig = plt.figure(figsize=(11, 8))
-
- if vidType == 0:
- axMain = fig.add_subplot(111, projection="3d")
- elif vidType == 1:
- axMain = fig.add_subplot(121, projection="3d")
- axCam1 = fig.add_subplot(122)
-
- # fig.tight_layout(h_pad = 5)
- axMain.view_init(azim=azimuth, elev=elevation)
- plt.ion()
- for fr in range(startFrame, session.numFrames):
- fig.suptitle(["Frame# - ", str(fr)])
- axMain.cla()
-
- if vidType == 1:
- axCam1.cla()
-
- char_x = mean_charuco_fr_mar_xyz[:][:, 0]
- char_y = mean_charuco_fr_mar_xyz[:][:, 1]
- char_z = mean_charuco_fr_mar_xyz[:][:, 2]
-
- # plot skeleton (openPose by default)
- if session.useOpenPose:
- sk_x = skel_fr_mar_xyz[fr, :, 0] # skeleton x data
- sk_y = skel_fr_mar_xyz[fr, :, 1] # skeleton y data
- sk_z = skel_fr_mar_xyz[fr, :, 2] # skeleton z data
-
- axMain.scatter3D(sk_x, sk_y, sk_z, marker=".", color="k", s=4.0)
- axMain.plot(
- sk_x[head],
- sk_y[head],
- sk_z[head],
- linestyle="-",
- color="g",
- linewidth=1.0,
- )
- axMain.plot(
- sk_x[spine],
- sk_y[spine],
- sk_z[spine],
- linestyle="-",
- color="g",
- linewidth=1.0,
- )
- axMain.plot(
- sk_x[rArm],
- sk_y[rArm],
- sk_z[rArm],
- linestyle="-",
- color="r",
- linewidth=1.0,
- )
- axMain.plot(
- sk_x[lArm],
- sk_y[lArm],
- sk_z[lArm],
- linestyle="-",
- color="b",
- linewidth=1.0,
- )
- axMain.plot(
- sk_x[rLeg],
- sk_y[rLeg],
- sk_z[rLeg],
- linestyle="-",
- color="r",
- linewidth=1.0,
- )
- axMain.plot(
- sk_x[lLeg],
- sk_y[lLeg],
- sk_z[lLeg],
- linestyle="-",
- color="b",
- linewidth=1.0,
- )
- axMain.plot(
- sk_x[rFoot],
- sk_y[rFoot],
- sk_z[rFoot],
- linestyle="-",
- color="r",
- linewidth=1.0,
- )
- axMain.plot(
- sk_x[lFoot],
- sk_y[lFoot],
- sk_z[lFoot],
- linestyle="-",
- color="b",
- linewidth=1.0,
- )
-
- # plot handybois
- # right hand
- axMain.plot(
- sk_x[thumb + rHandIDstart],
- sk_y[thumb + rHandIDstart],
- sk_z[thumb + rHandIDstart],
- linestyle="-",
- color="r",
- linewidth=1.0,
- )
- axMain.plot(
- sk_x[index + rHandIDstart],
- sk_y[index + rHandIDstart],
- sk_z[index + rHandIDstart],
- linestyle="-",
- color="r",
- linewidth=1.0,
- )
- axMain.plot(
- sk_x[bird + rHandIDstart],
- sk_y[bird + rHandIDstart],
- sk_z[bird + rHandIDstart],
- linestyle="-",
- color="r",
- linewidth=1.0,
- )
- axMain.plot(
- sk_x[ring + rHandIDstart],
- sk_y[ring + rHandIDstart],
- sk_z[ring + rHandIDstart],
- linestyle="-",
- color="r",
- linewidth=1.0,
- )
- axMain.plot(
- sk_x[pinky + rHandIDstart],
- sk_y[pinky + rHandIDstart],
- sk_z[pinky + rHandIDstart],
- linestyle="-",
- color="r",
- linewidth=1.0,
- )
-
- # left hand
- axMain.plot(
- sk_x[thumb + lHandIDstart],
- sk_y[thumb + lHandIDstart],
- sk_z[thumb + lHandIDstart],
- linestyle="-",
- color="b",
- linewidth=1.0,
- )
- axMain.plot(
- sk_x[index + lHandIDstart],
- sk_y[index + lHandIDstart],
- sk_z[index + lHandIDstart],
- linestyle="-",
- color="b",
- linewidth=1.0,
- )
- axMain.plot(
- sk_x[bird + lHandIDstart],
- sk_y[bird + lHandIDstart],
- sk_z[bird + lHandIDstart],
- linestyle="-",
- color="b",
- linewidth=1.0,
- )
- axMain.plot(
- sk_x[ring + lHandIDstart],
- sk_y[ring + lHandIDstart],
- sk_z[ring + lHandIDstart],
- linestyle="-",
- color="b",
- linewidth=1.0,
- )
- axMain.plot(
- sk_x[pinky + lHandIDstart],
- sk_y[pinky + lHandIDstart],
- sk_z[pinky + lHandIDstart],
- linestyle="-",
- color="b",
- linewidth=1.0,
- )
-
- # plot mediapipe
- if session.useMediaPipe:
- mp_sk_x = mediaPipe_skel_fr_mar_xyz[fr, :, 0] # skeleton x data
- mp_sk_y = mediaPipe_skel_fr_mar_xyz[fr, :, 1] # skeleton y data
- mp_sk_z = mediaPipe_skel_fr_mar_xyz[fr, :, 2] # skeleton z data
- axMain.scatter3D(mp_sk_x, mp_sk_y, mp_sk_z, marker=".", color="g", s=8.0)
-
- # plot deeplabcut
- if session.useDLC:
- dlc_x = dlc_fr_mar_xyz[fr, :, 0]
- dlc_y = dlc_fr_mar_xyz[fr, :, 1]
- dlc_z = dlc_fr_mar_xyz[fr, :, 2]
-
- axMain.scatter3D(dlc_x, dlc_y, dlc_z, marker="o", color="r", s=24.0)
-
- # plot charuco grid
- axMain.scatter(char_x, char_y, char_z, marker="o")
-
- # #plot camera positions (I think...)
- # for camNum in range(len(session.cgroup.cameras)):
- # axMain.scatter(session.cgroup.cameras[camNum].tvec[0], session.cgroup.cameras[camNum].tvec[1], session.cgroup.cameras[camNum].tvec[2], marker = 'p')
- axRange = session.board.square_length * 10
- mx = np.nanmean(char_x)
- my = np.nanmean(char_y)
- mz = np.nanmean(char_z)
-
- axMain.set_xlim(mx - axRange, mx + axRange)
- axMain.set_ylim(my - axRange, my + axRange)
- axMain.set_zlim(mz - axRange, mz + axRange)
-
- axMain.set_xlabel("x")
- axMain.set_ylabel("y")
- axMain.set_zlabel("z")
-
- if vidType == 0:
- pass
- elif vidType == 1:
- axCam1.imshow(
- cv2.cvtColor(cv2.imread(str(camImgPathList[0][fr])), cv2.COLOR_BGR2RGB)
- )
- axCam1.axis("off")
-
- plt.pause(0.01)
- plt.show()
-
- frameName = str(fr).zfill(6)
- saveFrameName = "{}.png".format(frameName)
- saveFramePath = session.imOutPath / saveFrameName
- fig.savefig(saveFramePath)
diff --git a/freemocap/prod/README.md b/freemocap/prod/README.md
deleted file mode 100644
index 4a40fe2d..00000000
--- a/freemocap/prod/README.md
+++ /dev/null
@@ -1,5 +0,0 @@
-
-
-Installation instructions for Mac
-
-- brew install python-tk
\ No newline at end of file
diff --git a/freemocap/prod/__init__.py b/freemocap/prod/__init__.py
deleted file mode 100644
index e69de29b..00000000
diff --git a/freemocap/prod/cam/__init__.py b/freemocap/prod/cam/__init__.py
deleted file mode 100644
index e69de29b..00000000
diff --git a/freemocap/reconstruct3D.py b/freemocap/reconstruct3D.py
deleted file mode 100644
index 300703ba..00000000
--- a/freemocap/reconstruct3D.py
+++ /dev/null
@@ -1,66 +0,0 @@
-from freemocap import fmc_anipose
-import numpy as np
-from rich.console import Console
-console=Console()
-
-# from numba import jit
-
-# @jit(nopython=True)
-def reconstruct3D(session, data_nCams_nFrames_nImgPts_XYC, confidenceThreshold=0.3):
- """
- Take a specifically formatted data array, and based on the camera calibration yaml, reconstruct a 3D image
- """
-
- if (
- session.cgroup is None
- ): # load the calibration settings into the session class if it hasn't been already
- calibrationFile = "{}_calibration.toml".format(session.sessionID)
- session.cameraConfigFilePath = session.sessionPath / calibrationFile
- session.cgroup = fmc_anipose.CameraGroup.load(session.cameraConfigFilePath)
-
- nCams, nFrames, nImgPts, nDims = data_nCams_nFrames_nImgPts_XYC.shape
-
- if nDims == 3:
- dataOG = data_nCams_nFrames_nImgPts_XYC.copy()
-
- for camNum in range(nCams):
-
- thisCamX = data_nCams_nFrames_nImgPts_XYC[camNum, :, :,0 ]
- thisCamY = data_nCams_nFrames_nImgPts_XYC[camNum, :, :,1 ]
- thisCamConf = data_nCams_nFrames_nImgPts_XYC[camNum, :, :, 2]
-
- thisCamX[thisCamConf < confidenceThreshold] = np.nan
- thisCamY[thisCamConf < confidenceThreshold] = np.nan
-
- if session.debug:
- import matplotlib.pyplot as plt
- fig = plt.figure(8000+camNum)
- fig.suptitle("3d reconstruction Confidence thresholding - cam{}".format(camNum))
- axOG = fig.add_subplot(1,2,1)
- axOG.imshow(dataOG[0,:,:,0])
- axOG.set_title("Original Data")
- axTh = fig.add_subplot(1,2,2)
- axTh.imshow(thisCamX)
- axTh.set_title("Thresholded Data (there should be NEW and EXCITING gaps :O")
-
-
-
-
-
- if nDims == 2:
- data_nCams_nFrames_nImgPts_XY = data_nCams_nFrames_nImgPts_XYC
- elif nDims == 3:
- data_nCams_nFrames_nImgPts_XY = np.squeeze(data_nCams_nFrames_nImgPts_XYC[:, :, :, 0:2])
-
- dataFlat_nCams_nTotalPoints_XY = data_nCams_nFrames_nImgPts_XY.reshape(nCams, -1, 2) # reshape data to collapse across 'frames' so it becomes [numCams, numFrames*numPoints, XY]
-
- console.print('Reconstructing 3d points...')
- data3d_flat = session.cgroup.triangulate(dataFlat_nCams_nTotalPoints_XY, progress=True)
-
- dataReprojerr_flat = session.cgroup.reprojection_error( data3d_flat, dataFlat_nCams_nTotalPoints_XY, mean=True)
-
- ##return:
- data_fr_mar_xyz = data3d_flat.reshape(nFrames, nImgPts, 3)
- dataReprojErr = dataReprojerr_flat.reshape(nFrames, nImgPts)
-
- return data_fr_mar_xyz, dataReprojErr
diff --git a/freemocap/recordingconfig.py b/freemocap/recordingconfig.py
deleted file mode 100644
index 839e6989..00000000
--- a/freemocap/recordingconfig.py
+++ /dev/null
@@ -1,156 +0,0 @@
-# -*- coding: utf-8 -*-
-"""
-Created on Thu Mar 11 11:54:12 2021
-
-@author: Rontc
-"""
-
-from pathlib import Path
-
-
-dataFolder = 'FreeMocap_Data'
-
-
-folder_setup = ['RawVideos','SyncedVideos','CalVideos','DataArrays','DLCData','OpenPoseData','MediaPipeData','imOut']
-
-default_parameters = {'path_to_save': str(Path.home()),'dlc_config_paths':[], 'rotations':{},'parameters':{'exposure':-5,'resWidth':640,'resHeight':480,'framerate':25,'codec':'DIVX'}, 'blenderEXEpath':None}
-saved_parameters = default_parameters
-parameters_for_yaml = {'default':default_parameters,'saved':saved_parameters}
-
-
-
-
-# def createSession(session,filepath, existing_data = False):
-# #create file paths for the session, raw and synced videos
-
-# pathList = []
-
-# recordPath = filepath/'Data'
-# recordPath.mkdir(exist_ok= True)
-
-# session.sessionPath = recordPath/session.sessionID
-# #if existing_data:
-# #session.sessionPath.mkdir(exist_ok = True)
-# #else:
-# session.sessionPath.mkdir(exist_ok= True)
-# pathList.append(session.sessionPath)
-
-# session.rawVidPath = session.sessionPath/'RawVideos'
-# session.rawVidPath.mkdir(exist_ok = True)
-# pathList.append(session.rawVidPath)
-
-# session.syncedVidPath = session.sessionPath/'SyncedVideos'
-# session.syncedVidPath.mkdir(exist_ok = True)
-# pathList.append(session.syncedVidPath)
-
-# session.calVidPath = session.sessionPath/'CalVideos'
-# session.calVidPath.mkdir(exist_ok = True)
-# pathList.append(session.calVidPath)
-
-# session.openPoseDataPath = session.sessionPath/'OpenPoseData'
-# session.openPoseDataPath.mkdir(exist_ok = True)
-# pathList.append(session.openPoseDataPath)
-
-# session.mediaPipeDataPath = session.sessionPath/'MediaPipeData'
-# session.mediaPipeDataPath.mkdir(exist_ok = True)
-# pathList.append(session.mediaPipeDataPath)
-
-# session.dlcDataPath = session.sessionPath / 'DLCdata'
-# session.dlcDataPath.mkdir(exist_ok = True, parents = True)
-# pathList.append(session.dlcDataPath)
-
-# session.imOutPath = session.sessionPath / 'imOut'
-# session.imOutPath.mkdir(exist_ok=True)
-# pathList.append(session.imOutPath)
-
-# session.dataArrayPath = session.sessionPath/'Data Arrays'
-# session.dataArrayPath.mkdir(exist_ok=True)
-# pathList.append(session.dataArrayPath)
-
-# #create a list of paths that is passed to the recording script
-# #pathList = [session.sessionPath,session.rawVidPath,session.syncedVidPath,session.openPoseDataPath,session.dlcDataPath,session.imOutPath, session.dataArrayPath]
-
-
-# config_settings,config_yaml = create_config_yaml()
-# session.config_settings = config_settings
-
-# yaml_name = session.sessionPath/'{}_config.yaml'.format(session.sessionID)
-# session.yamlPath = yaml_name
-# # print(yaml_name)
-# write_config_yaml(session,config_settings,config_yaml,pathList,yaml_name)
-
-# return yaml_name
-
-# def createSessionTxt(session,paramDict,rotDict):
-# #create a text file listing recording parameters
-# parameter_text = session.sessionPath/'sessionSettings.txt'
-# text = open(parameter_text, 'w')
-# text.write("Session ID = %s\n" %(session.sessionID))
-# text.write("%s = %s\n" %("Parameters", paramDict))
-# text.write("%s = %s\n" %("Rotations", rotDict))
-# text.close()
-
-
-
-
-# def create_config_yaml():
-
-# def create_config_yaml():
-
-# yaml_str = """\
-# # Camera Inputs
-# CamInputs:
-# RotationInputs:
-# ParameterDict:
-
-# # Paths
-# Paths:
-# sessionPath:
-# rawVidPath:
-# syncedVidPath:
-# calVidPath:
-# openPoseDataPath:
-# mediaPipeDataPath:
-# dlcDataPath:
-# imOutPath:
-# dataArrayPath:
-# \n
-# """
-# config_yaml = YAML()
-# config_settings = config_yaml.load(yaml_str)
-
-# return config_settings,config_yaml
-
-# def write_config_yaml(session, config_settings, config_yaml, pathList, yaml_name):
-
-# def write_config_yaml(session,config_settings,config_yaml,pathList,yaml_name):
-
-# for count,key in enumerate(config_settings['Paths'].keys()):
-# config_settings['Paths'][key] = str(pathList[count])
-
-# config_settings['CamInputs']['RotationInputs'] = session.rotationInputs
-# config_settings['CamInputs']['ParameterDict'] = session.parameterDictionary
-
-
-# #yamlPath = sessionPath/'config_yaml'
-# #print(config_settings,yaml_name)
-# with open(yaml_name, 'w') as outfile:
-# config_yaml.dump(config_settings, outfile)
-
-
-# def load_config_yaml(yaml_path):
-# config_yaml = YAML()
-# with open(yaml_path,'r') as fp:
-# config_settings = config_yaml.load(fp)
-# return config_settings
-
-# def load_session_paths(session,config_settings):
-# configPaths = config_settings['Paths']
-# session.rawVidPath = Path(configPaths['rawVidPath'])
-# session.syncedVidPath = Path(configPaths['syncedVidPath'])
-# session.calVidPath = Path(configPaths['calVidPath'])
-# session.mediaPipeDataPath = Path(configPaths['mediaPipeDataPath'])
-# session.openPoseDataPath = Path(configPaths['openPoseDataPath'])
-# session.dlcDataPath = Path(configPaths['dlcDataPath'])
-# session.imOutPath = Path(configPaths['imOutPath'])
-# session.dataArrayPath = Path(configPaths['dataArrayPath'])
diff --git a/freemocap/rich_gui.py b/freemocap/rich_gui.py
deleted file mode 100644
index e5775ac4..00000000
--- a/freemocap/rich_gui.py
+++ /dev/null
@@ -1,22 +0,0 @@
-from rich.console import Console
-from rich.layout import Layout
-
-console = Console()
-layout = Layout()
-
-# Divide the "screen" in to three parts
-layout.split(
- Layout(name="header", size=3),
- Layout(ratio=1, name="main"),
- Layout(size=10, name="footer"),
-)
-# Divide the "main" layout in to "side" and "body"
-layout["main"].split(
- Layout(name="side"),
- Layout(name="body", ratio=2),
- direction="horizontal"
-)
-# Divide the "side" layout in to two
-layout["side"].split(Layout(), Layout())
-
-console.print(layout)
\ No newline at end of file
diff --git a/freemocap/runcams.py b/freemocap/runcams.py
deleted file mode 100644
index 4d25c2d7..00000000
--- a/freemocap/runcams.py
+++ /dev/null
@@ -1,142 +0,0 @@
-from freemocap.webcam import startcamrecording, timesync, videotrim
-
-from pathlib import Path
-import time
-import pickle
-import pandas as pd
-import numpy as np
-from tkinter import Tk
-
-
-def RecordCams(session,camInputs,parameterDictionary,rotationInputs):
- """
- Determines the number of cameras, assigns them IDs, and then starts a threaded cam recording process. Accesses the pickle file of timestamps
- saved during recording, makes a dataframe from it and saves it to a CSV file. Updates the session class at the end with numCam variable
- """
- #Create RawVideos folder
- session.rawVidPath.mkdir(exist_ok = True)
-
- #%% Setting up recordings
- beginTime = time.time()
- session.beginTime = beginTime
- numCams = len(camInputs) # number of cameras
- numCamRange = range(numCams) # a range for the number of cameras that we have
- vidNames = []
- camIDs = []
- unix_camIDs = []
- for x in numCamRange: # create names for each of the initial untrimmed videos
- singleCamID = "Cam{}".format(x + 1)
- camIDs.append(
- singleCamID
- ) # creates IDs for each camera based on the number of cameras entered
-
- unix_camID = singleCamID + '_unix_timestamps'
- unix_camIDs.append(unix_camID)
-
- singleVidName = "raw_cam{}.mp4".format(x + 1)
- vidNames.append(singleVidName)
-
- #%% Starting the thread recordings for each camera
- threads = []
- for n in numCamRange: # starts recording video, opens threads for each camera
- camRecordings = startcamrecording.CamRecordingThread(
- session,
- camIDs[n],
- unix_camIDs[n],
- camInputs[n],
- vidNames[n],
- session.rawVidPath,
- beginTime,
- parameterDictionary,
- )
- camRecordings.start()
-
- threads.append(camRecordings)
-
- for camRecordings in threads:
- camRecordings.join() # make sure that one thread ending doesn't immediately end all the others (before they can dump data in a pickle file)
-
- print("finished recordings")
-
- timeStampList = []
- unix_timeStampList = []
-
- for (
- e
- ) in (
- numCamRange
- ): # open the saved pickle file for each camera, and add the timestamps to the dataList list
- with open(session.rawVidPath/camIDs[e], "rb") as f:
- camTimeList = pickle.load(f)
- timeStampList.append(camTimeList)
- with open(session.rawVidPath/unix_camIDs[e], "rb") as g:
- unix_camTimeList = pickle.load(g)
- unix_timeStampList.append(unix_camTimeList)
-
- timeDictionary = {}
- unix_timeDictionary = {}
-
- id_and_time = zip(camIDs, timeStampList)
-
- for cam, data in id_and_time:
- timeDictionary[cam] = np.array(
- data
- ) # create a dictionary that holds the timestamps for each camera
- df = pd.DataFrame.from_dict(
- timeDictionary, orient="index"
- ) # create a data frame from this dictionary
- timeStampData = df.transpose()
- csvName = session.sessionID + "_timestamps.csv"
- csvPath = session.rawVidPath / csvName
- timeStampData.to_csv(csvPath) # turn dataframe into a CSV
-
- id_and_unix_time = zip(unix_camIDs,unix_timeStampList)
-
- for cam_unix, data_unix in id_and_unix_time:
- unix_timeDictionary[cam_unix] = np.array(data_unix)
- df_unix = pd.DataFrame.from_dict(
- unix_timeDictionary, orient="index"
- ) # create a data frame from this dictionary
- unix_timeStampData = df_unix.transpose()
- unix_csvName = session.sessionID + "_unix_timestamps.csv"
- unix_csvPath = session.rawVidPath / unix_csvName
- unix_timeStampData.to_csv(unix_csvPath)
-
- session.numCams = numCams
- session.session_settings['recording_parameters'].update({'numCams':session.numCams})
- session.timeStampData = timeStampData
- session.camIDs = camIDs
- session.numCamRange = numCamRange
- session.vidNames = vidNames
-
-
-def SyncCams(session, timeStampData,numCamRange,vidNames,camIDs):
- """
- Runs the time-syncing process. Accesses saved timestamps, runs the time-syncing GUI, and on user-permission, proceeds to create
- synced videos
- """
- session.syncedVidPath.mkdir(exist_ok = True)
-
- #start the timesync process
- frameTable,timeTable,unix_synced_timeTable,frameRate,resultsTable,plots = timesync.TimeSync(session,timeStampData,numCamRange,camIDs)
-
- #this message shows you your percentages and asks if you would like to continue or not. shuts down the program if no
- root = Tk()
- proceed = timesync.proceedGUI(
- root, resultsTable, plots
- ) # create a GUI instance called proceed
- root.mainloop()
-
- if session.get_synced_unix_timestamps == True:
- unix_synced_timestamps_csvName = 'unix_synced_timestamps.csv'
- unix_synced_timestamps_csvPath = session.sessionPath/unix_synced_timestamps_csvName
- unix_synced_timeTable.to_csv(unix_synced_timestamps_csvPath)
-
- if proceed.proceed == True:
- print()
- print('Starting editing')
- videotrim.VideoTrim(session,vidNames,frameTable,session.parameterDictionary,session.rotationInputs,numCamRange)
- session.session_settings['recording_parameters'].update({'numFrames':session.numFrames})
- #videotrim.createCalibrationVideos(session,60,parameterDictionary)
- print('all done')
-
diff --git a/freemocap/session.py b/freemocap/session.py
deleted file mode 100644
index eaf415f5..00000000
--- a/freemocap/session.py
+++ /dev/null
@@ -1,284 +0,0 @@
-from pathlib import Path
-from ruamel.yaml import YAML
-
-from freemocap import recordingconfig
-from freemocap.webcam import timesync
-
-import cv2
-
-class Session: #self like "recording self"
- def __init__(self):
-
- self.numCams = None
- self.numFrames = None
- self.numTrackedPoints = None
-
- self.basePath = Path.cwd()
-
- self.sessionID = '' #The sessionID tag will be used to generate files names and whatnot
- self.sessionPath = '' #The folder where the to-be-processed videos live (in a folder called "synced Vids")
- #self.numCams = ''#The number of cameras used in this recording self
- self.openPoseDataPath = ''#Where the open pose data lives
- self.dlcDataPath = ''#Where the DLC data lives
- self.openPoseExePath = r'C:\openpose'
-
- self.cam_inputs = None
- self.parameterDictionary = None
- self.rotationInputs = None
-
- self.cgroup = None
-
- self.mean_charuco_fr_mar_xyz = None
- self.skel_fr_mar_xyz = None
-
- self.mediaPipe_imgPathList = None
- self.openPose_imgPathList = None
-
- def start_session(self,paramDict,rotDict):
- """
- When starting a session from stage 1, create all the file paths necessary, and create a session dictionary to save settings.
- Calls the create_session_paths and create_session_dictionary function
- """
- #dataFolderPath = self.basePath/self.dataFolderName
-
-
- if self.basePath.stem == self.dataFolderName: #don't recursively craete 'FreeMoCap_Data' folders!
- dataFolderPath = self.basePath
- else:
- dataFolderPath = self.basePath/self.dataFolderName
-
- dataFolderPath.mkdir(exist_ok= True)
-
-
-
- self.sessionPath = dataFolderPath/self.sessionID
- self.sessionPath.mkdir(exist_ok=True)
-
- #create all the session filepaths and settings - create and load them into a dictionary
- self.pathList = self.create_session_paths()
- self.session_settings = self.create_session_dictionary()
- self.create_session_txt(paramDict,rotDict)
-
- self.save_session()
-
-
-
- def create_session_paths(self):
- """
- Creates Path objects to each folder created in a recording self and adds them all to the pathList variable
- folders for these paths are created at the start of each stage where they are needed
- """
- pathList = []
-
- self.rawVidPath = self.sessionPath/'RawVideos'
- pathList.append(self.rawVidPath)
-
- self.syncedVidPath = self.sessionPath/'SyncedVideos'
- pathList.append(self.syncedVidPath)
-
- self.calVidPath = self.sessionPath/'CalVideos'
- pathList.append(self.calVidPath)
-
- self.dataArrayPath = self.sessionPath/'DataArrays'
- pathList.append(self.dataArrayPath)
-
- self.dlcDataPath = self.sessionPath/'DLCData'
- pathList.append(self.dlcDataPath)
-
- self.openPoseDataPath = self.sessionPath/'OpenPoseData'
- pathList.append(self.openPoseDataPath)
-
- self.mediaPipeDataPath = self.sessionPath/'MediaPipeData'
- pathList.append(self.mediaPipeDataPath)
-
- self.imOutPath = self.sessionPath/'imOut'
- pathList.append(self.imOutPath)
-
- return pathList
-
- def create_session_dictionary(self):
- """
- Creates a dictionary of settings that should be saved into a YAML through each session
- """
-
-
- recording_parameters = {'numCams': self.numCams, 'numFrames': self.numFrames, 'numTrackedPoints': self.numTrackedPoints}
-
- #create a dictionary with the folder names (taken from the recordingconfig.py file) and the folder paths from pathList
- #NOTE AC- 6/30/21 - as of right now, the order of folder names in the recordingconfig.folder_setup list needs to match the
- # the order of folder paths in the pathList
- session_paths = {}
-
- for foldername, folderpath in zip(recordingconfig.folder_setup,self.pathList):
- session_paths[foldername] = folderpath
-
- session_settings_dictionary = {'recording_parameters':recording_parameters, 'session_paths':session_paths}
-
- return session_settings_dictionary
-
-
- def create_session_txt(self,paramDict,rotDict):
- """
- Create a text file listing recording parameters
- """
- parameter_text = self.sessionPath/'sessionSettings.txt'
- text = open(parameter_text, 'w')
- text.write("Session ID = %s\n" %(self.sessionID))
- text.write("%s = %s\n" %("Parameters", paramDict))
- text.write("%s = %s\n" %("Rotations", rotDict))
- text.close()
-
- def save_session(self):
- """
- Save the settings needed to rerun the session at a later point into a dictionary, and then save it into a YAML
- """
-
- session_dictionary_to_save = self.session_settings
-
- for key,value in session_dictionary_to_save['session_paths'].items():
- session_dictionary_to_save['session_paths'][key] = str(value)
-
- self.session_yaml_path = self.sessionPath/'{}_config.yaml'.format(self.sessionID)
-
- session_yaml = YAML()
-
-
- with open(self.session_yaml_path,'w') as outfile:
- session_yaml.dump(session_dictionary_to_save,outfile)
-
-
- def initialize(self,stage):
- """
- When starting a session from Stage 3 onwards, modify the current session class instance with all necessary
- attributes needed to run the rest of the pipeline
- """
- #load all session settings back into the session class for this run-through of the code
-
- #recordPath = self.basePath/'Data' #create a Data folder in the filepath if none exists yet
- #recordPath.mkdir(exist_ok= True)
-
- self.sessionPath = self.dataFolderPath/self.sessionID
- self.sessionPath.mkdir(exist_ok=True)
-
-
-
- self.session_yaml_path = self.sessionPath/'{}_config.yaml'.format(self.sessionID)
-
- # if stage == 3:
- # #this is for the case of GoPro recordings/external recordings - if no config file exists, create one
- # if self.session_yaml_path.is_file():
- # self.session_settings = self.load_session()
- # else:
- # self.start_session({},{})
- # #run a check to make sure all the frame numbers are the same
- # a_sync_vid_path = list(self.syncedVidPath.glob('*.mp4'))
- # frames_per_cam = {}
-
- # for vid in a_sync_vid_path:
- # temp_cap = cv2.VideoCapture(str(vid))
- # thisCamFrames = temp_cap.get(cv2.CAP_PROP_FRAME_COUNT)
- # frames_per_cam[str(vid)] = thisCamFrames
- # temp_cap.release()
- # frame_check = len(list(set(list(frames_per_cam.values())))) == 1 # using set() to remove duplicates and check for values count
-
-
- # if frame_check:
- # self.numFrames = int(thisCamFrames)
- # self.session_settings['recording_parameters'].update({'numFrames':self.numFrames})
- # self.numCams = len(a_sync_vid_path)
- # else:
- # print('The number of frames in each video are not equal. Frame counts are: ' + frames_per_cam)
- # else:
- # self.session_settings = self.load_session()
-
- if self.session_yaml_path.is_file():
- self.session_settings = self.load_session() #if a yaml exists, load it in (this is the case for a webcam recording, or an external recording that's been processed already)
- else: #if a session yaml doesn't exist, as is the case of an external recording
- self.start_session({},{})
- #run a check to make sure all the frame numbers are the same
- a_sync_vid_path = list(self.syncedVidPath.glob('*.mp4'))
- frames_per_cam = {}
-
- for vid in a_sync_vid_path:
- temp_cap = cv2.VideoCapture(str(vid))
- thisCamFrames = temp_cap.get(cv2.CAP_PROP_FRAME_COUNT)
- frames_per_cam[str(vid)] = thisCamFrames
- temp_cap.release()
- frame_check = len(list(set(list(frames_per_cam.values())))) == 1 # using set() to remove duplicates and check for values count
-
-
- if frame_check:
- self.numFrames = int(thisCamFrames)
- self.session_settings['recording_parameters'].update({'numFrames':self.numFrames})
- self.numCams = len(a_sync_vid_path)
- self.session_settings['recording_parameters'].update({'numCams':self.numCams})
- self.save_session()
- else:
- raise ValueError('The number of frames in each video are not equal. Frame counts per video are are: ' + str(frames_per_cam))
-
-
-
-
- def load_session(self):
- """
- Called by the self.initialize function - reads the session yaml and loads the number of cameras and frames, and then
- creates all necessary session paths
- """
-
- #session_yaml_path = self.sessionPath/'{}_config.yaml'.format(self.sessionID)
- session_yaml = YAML(typ='safe', pure=True)
-
- with open(self.session_yaml_path,'r') as fp:
- session_dictionary_to_load = session_yaml.load(fp)
-
- session_settings_dictionary = session_dictionary_to_load #create a copy of the loaded dictionary
-
- for key,value in session_settings_dictionary['session_paths'].items():
- session_settings_dictionary['session_paths'][key] = Path(value)
-
- #self.load_session_paths(session_settings_dictionary)
- self.create_session_paths()
- self.numCams = session_settings_dictionary['recording_parameters']['numCams']
- self.numFrames = session_settings_dictionary['recording_parameters']['numFrames']
- self.numTrackedPoints = session_settings_dictionary['recording_parameters']['numTrackedPoints']
-
- return session_settings_dictionary
- f = 2
-
- # def load_session_paths(self, session_settings_dict):
-
- # session_paths = session_settings_dict['session_paths']
-
- # self.rawVidPath = session_paths['RawVideos']
- # self.syncedVidPath = session_paths['SyncedVideos']
- # self.calVidPath = session_paths['CalVideos']
- # self.mediaPipeDataPath = session_paths['MediaPipeData']
- # self.openPoseDataPath = session_paths['OpenPoseData']
- # self.dlcDataPath = session_paths['DLCData']
- # self.imOutPath = session_paths['imOut']
- # self.dataArrayPath = session_paths['DataArrays']
-
-
- def save_user_preferences(self,preferences):
- preferences_yaml = YAML()
- preferences_yaml.dump(preferences,self.preferences_path)
-
-
-
- f = 2
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/freemocap/tests/__init__.py b/freemocap/tests/__init__.py
deleted file mode 100644
index e69de29b..00000000
diff --git a/freemocap/tests/conftest.py b/freemocap/tests/conftest.py
deleted file mode 100644
index e69de29b..00000000
diff --git a/freemocap/tests/test_examples.py b/freemocap/tests/test_examples.py
deleted file mode 100644
index ba8d618f..00000000
--- a/freemocap/tests/test_examples.py
+++ /dev/null
@@ -1,3 +0,0 @@
-def test_one_plus_one_is_two():
- "Check that one and one are indeed two."
- assert 1 + 1 == 2
diff --git a/freemocap/webcam/__init__.py b/freemocap/webcam/__init__.py
deleted file mode 100644
index 9059c793..00000000
--- a/freemocap/webcam/__init__.py
+++ /dev/null
@@ -1,6 +0,0 @@
-# -*- coding: utf-8 -*-
-"""
-Created on Mon Mar 1 13:39:34 2021
-
-@author: Rontc
-"""
diff --git a/freemocap/webcam/camera_settings.py b/freemocap/webcam/camera_settings.py
deleted file mode 100644
index 6296664e..00000000
--- a/freemocap/webcam/camera_settings.py
+++ /dev/null
@@ -1,129 +0,0 @@
-from pathlib import Path
-import datetime
-import sys
-import pandas as pd
-import numpy as np
-
-from freemocap.webcam import recordGUI, camsetup
-from freemocap import recordingconfig, fmc_anipose
-from rich.console import Console
-
-console = Console()
-
-def initialize(session, stage, board):
- """
- Runs the initialization needed to start a new recording from scratch (Stage 1)
- Create a new sessionID and attempt to load previous recording parameters (camera settings/rotations/save locations),
- and use default values if previous parameters are not found. Ask user to select preferences using a series of GUIs, runs the Setup option if
- chosen by the user, and ultimately sets a bool that dictates whether we should proceed to start the actual Stage 1 recording. Also saves parameters
- into the session class, which gets saved into the user_preferences yaml
-
- """
-
- console.rule(style="color({})".format(13))
- console.rule('Finding available webcams',style="color({})".format(13))
- console.rule(style="color({})".format(13))
-
- # if stage == 1:
- filepath = Path.cwd()
-
- session.board = board
-
- # %% Stage One Initialization
-
-
- # create session ID
- sessionID_in = datetime.datetime.now().strftime("sesh_%Y-%m-%d_%H_%M_%S")
- session.sessionID = sessionID_in
-
-#load the parameters YAML and extract the saved parameters if possible, and the default otherwise
- #here = Path(__file__).parent
- # parameter_path = here/'user_preferences.yaml'
- # parameters_yaml = YAML()
- # if parameter_path.exists():
- # parameters = parameters_yaml.load(parameter_path)
- # else:
- # parameters = recordingconfig.parameters_for_yaml
- # with open(parameter_path,'w') as outfile:
- # parameters_yaml.dump(parameters, outfile)
-
-
-
-
- proceedToRecording = False #create this boolean, set it to false, and if the user wants to record
- #later in the pipeline, it will be set to true
-
-#run the GUI to get the tasks, the cams chosen, the camera settings, and the session ID
- cam_inputs, task = recordGUI.RunChoiceGUI()
- restartSetup = True
-
- while restartSetup == True:
-
- try:
- rotation_entry = session.preferences["saved"]["rotations"]
- parameter_entry = session.preferences["saved"]["parameters"]
- except:
- print("Could not load saved parameters, using default parameters")
- rotation_entry = session.preferences['default']['rotations']
- parameter_entry = session.preferences['default']['parameters']
-
-
- try:
- current_path_to_save = session.preferences['saved']['path_to_save']
- except:
- current_path_to_save = session.preferences['default']['path_to_save']
- rotDict, paramDict, session.sessionID,savepath, mediaPipeOverlay = recordGUI.RunParametersGUI(sessionID_in, rotation_entry, parameter_entry, current_path_to_save, cam_inputs, task)
-
- #update the saved parameters in the YAML
- #recordingconfig.rotation_settings['saved'] = rotDict
- #recordingconfig.camera_session.preferences['saved'] = paramDict
- session.preferences['saved']['rotations'] = rotDict
- session.preferences['saved']['parameters'] = paramDict
- if savepath is not None:
- session.preferences['saved']['path_to_save'] = savepath
-
- session.save_user_preferences(session.preferences)
-
- #save recording parameters to the config yaml
-
-
- #create a list from the rotation dictionary to be used in running webcams
- rotation_input = list(rotDict.values())
-
- if task == "setup":
- # run setup processes, and then check if th user wants to proceed to recording
- camsetup.RunSetup(cam_inputs, rotation_input, paramDict,mediaPipeOverlay)
- proceedToRecording, restartSetup, session.sessionID, savepath = recordGUI.RunProceedtoRecordGUI(
- sessionID_in,current_path_to_save
- )
- session.preferences['saved']['path_to_save'] = savepath
- session.save_user_preferences(session.preferences)
- elif task == "record":
- proceedToRecording = True
- restartSetup = False
-
- if proceedToRecording:
- # create these session properties to be used later in the pipeline
- session.cam_inputs = cam_inputs
- session.parameterDictionary = paramDict
- session.rotationInputs = rotation_input
- session.basePath = Path(savepath)
-
- #create a config yaml and text file for this session
- session.start_session(session.parameterDictionary,session.rotationInputs)
- session.session_settings['recording_parameters']['RotationInputs'] = rotDict
- session.session_settings['recording_parameters']['ParameterDict'] = paramDict
- #configyaml = YAML()
- #sessionsettings = configyaml.load(session.session_yaml_path)
- #sessionsettings['recording_parameters']['RotationInputs'] = rotDict
- #sessionsettings['recording_parameters']['ParameterDict'] = paramDict
- #configyaml.dump(sessionsettings, session.session_yaml_path)
- #print(sessionsettings)
- #config_yaml_path = recordingconfig.createSession(session,filepath)
- #recordingconfig.createSessionTxt(session,paramDict,rotDict)
-
- print('Proceeding to Stage One')
-
- else:
-
- sys.exit('Recording Canceled')
diff --git a/freemocap/webcam/camsetup.py b/freemocap/webcam/camsetup.py
deleted file mode 100644
index 94df02a5..00000000
--- a/freemocap/webcam/camsetup.py
+++ /dev/null
@@ -1,314 +0,0 @@
-import threading
-import cv2
-import imutils
-import os
-import platform
-import time
-
-import mediapipe as mp
-import numpy as np
-
-
-mp_drawing = mp.solutions.drawing_utils
-mp_drawing_styles = mp.solutions.drawing_styles
-mp_holistic = mp.solutions.holistic
-
-class VideoSetup(threading.Thread):
- """
- Class to run and thread webcams for preview purposes
- """
- def __init__(self, camID, parameterDictionary, rotNum):
- self.camID = camID
- self.parameterDictionary = parameterDictionary
- self.rotNum = rotNum
- threading.Thread.__init__(self)
-
- def run(self):
- # print("Starting " + self.previewName)
- self.record(self.parameterDictionary, self.rotNum)
-
- def record(self, parameterDictionary, rotNum):
- exposure = parameterDictionary.get("exposure")
- resWidth = parameterDictionary.get("resWidth")
- resHeight = parameterDictionary.get("resHeight")
- camWindowName = "Camera" + str(self.camID)+' Preview - Press ESC to exit Setup'
- cv2.namedWindow(camWindowName)
-
- if platform.system() == 'Windows':
- cap = cv2.VideoCapture(self.camID, cv2.CAP_DSHOW)
- else:
- cap = cv2.VideoCapture(self.camID, cv2.CAP_ANY)
-
-
- cap.set(cv2.CAP_PROP_FRAME_WIDTH, resWidth)
- cap.set(cv2.CAP_PROP_FRAME_HEIGHT, resHeight)
- cap.set(cv2.CAP_PROP_EXPOSURE, exposure)
- cap.set(cv2.CAP_PROP_FOURCC, cv2.VideoWriter_fourcc('M', 'J', 'P', 'G'))
-
- # showing values of the properties
- print("__________________________________________")
- print("cv2::videocapture properties for Camera# {}".format(self.camID))
- print("CV_CAP_PROP_FRAME_WIDTH: '{}'".format(cap.get(cv2.CAP_PROP_FRAME_WIDTH)))
- print("CV_CAP_PROP_FRAME_HEIGHT : '{}'".format(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)))
- print("CAP_PROP_FPS : '{}'".format(cap.get(cv2.CAP_PROP_FPS)))
- print("CAP_PROP_EXPOSURE : '{}'".format(cap.get(cv2.CAP_PROP_EXPOSURE)))
- print("CAP_PROP_POS_MSEC : '{}'".format(cap.get(cv2.CAP_PROP_POS_MSEC)))
- print("CAP_PROP_FRAME_COUNT : '{}'".format(cap.get(cv2.CAP_PROP_FRAME_COUNT)))
- print("CAP_PROP_BRIGHTNESS : '{}'".format(cap.get(cv2.CAP_PROP_BRIGHTNESS)))
- print("CAP_PROP_CONTRAST : '{}'".format(cap.get(cv2.CAP_PROP_CONTRAST)))
- print("CAP_PROP_SATURATION : '{}'".format(cap.get(cv2.CAP_PROP_SATURATION)))
- print("CAP_PROP_HUE : '{}'".format(cap.get(cv2.CAP_PROP_HUE)))
- print("CAP_PROP_GAIN : '{}'".format(cap.get(cv2.CAP_PROP_GAIN)))
- print("CAP_PROP_CONVERT_RGB : '{}'".format(cap.get(cv2.CAP_PROP_CONVERT_RGB)))
- print("__________________________________________")
-
- while True:
- ret1, frame1 = cap.read()
- charuco_corners, charuco_ids, aruco_square_corners, aruco_square_ids = detect_charuco_board(frame1)
- annotate_image_with_charuco_data(frame1, charuco_corners, charuco_ids)
-
- if ret1 == True:
- if rotNum is not None:
- frame1 = imutils.rotate_bound(frame1, angle=rotNum)
-
- cv2.imshow(camWindowName, frame1)
- if cv2.waitKey(1) & 0xFF == 27:
- # == ord('q') for q
- break
-
- else:
- break
- cv2.destroyWindow(camWindowName)
-
-class MediaPipeVideoSetup(threading.Thread):
- """
- Class to run and thread webcams for preview purposes
- """
- def __init__(self, camID, parameterDictionary, rotNum):
- self.camID = camID
- self.parameterDictionary = parameterDictionary
- self.rotNum = rotNum
- threading.Thread.__init__(self)
-
- def run(self):
- # print("Starting " + self.previewName)
- self.record(self.parameterDictionary, self.rotNum)
-
- def record(self, parameterDictionary, rotNum):
- exposure = parameterDictionary.get("exposure")
- resWidth = parameterDictionary.get("resWidth")
- resHeight = parameterDictionary.get("resHeight")
- camWindowName = "Camera" + str(self.camID)+' - Press ESC to exit'
-
- cv2.namedWindow(camWindowName)
-
- if platform.system() == 'Windows':
- cap = cv2.VideoCapture(self.camID, cv2.CAP_DSHOW)
- else:
- cap = cv2.VideoCapture(self.camID, cv2.CAP_ANY)
-
- with mp_holistic.Holistic(
- static_image_mode=False,
- model_complexity=0,
- enable_segmentation=True) as holistic:
-
- cap.set(cv2.CAP_PROP_FRAME_WIDTH, resWidth)
- cap.set(cv2.CAP_PROP_FRAME_HEIGHT, resHeight)
- cap.set(cv2.CAP_PROP_EXPOSURE, exposure)
- cap.set(cv2.CAP_PROP_FOURCC, cv2.VideoWriter_fourcc('M', 'J', 'P', 'G'))
-
- # showing values of the properties
- print("__________________________________________")
- print("cv2::videocapture properties for Camera# {}".format(self.camID))
- print("CV_CAP_PROP_FRAME_WIDTH: '{}'".format(cap.get(cv2.CAP_PROP_FRAME_WIDTH)))
- print("CV_CAP_PROP_FRAME_HEIGHT : '{}'".format(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)))
- print("CAP_PROP_FPS : '{}'".format(cap.get(cv2.CAP_PROP_FPS)))
- print("CAP_PROP_EXPOSURE : '{}'".format(cap.get(cv2.CAP_PROP_EXPOSURE)))
- print("CAP_PROP_POS_MSEC : '{}'".format(cap.get(cv2.CAP_PROP_POS_MSEC)))
- print("CAP_PROP_FRAME_COUNT : '{}'".format(cap.get(cv2.CAP_PROP_FRAME_COUNT)))
- print("CAP_PROP_BRIGHTNESS : '{}'".format(cap.get(cv2.CAP_PROP_BRIGHTNESS)))
- print("CAP_PROP_CONTRAST : '{}'".format(cap.get(cv2.CAP_PROP_CONTRAST)))
- print("CAP_PROP_SATURATION : '{}'".format(cap.get(cv2.CAP_PROP_SATURATION)))
- print("CAP_PROP_HUE : '{}'".format(cap.get(cv2.CAP_PROP_HUE)))
- print("CAP_PROP_GAIN : '{}'".format(cap.get(cv2.CAP_PROP_GAIN)))
- print("CAP_PROP_CONVERT_RGB : '{}'".format(cap.get(cv2.CAP_PROP_CONVERT_RGB)))
- print("__________________________________________")
- timestamps = []
- while True:
- ret1, frame1 = cap.read()
- timestamps.append(time.time())
-
- #print(f"mean fps for cam {self.camID} is {1/np.mean(np.diff(timestamps))}")
-
- if ret1 == True:
-
- charuco_corners, charuco_ids, aruco_square_corners, aruco_square_ids = detect_charuco_board(frame1)
- try:
- results = holistic.process(cv2.cvtColor(frame1, cv2.COLOR_BGR2RGB))
- except Exception as e:
- print(e)
-
- annotate_image_with_charuco_data(frame1, charuco_corners, charuco_ids)
-
- frame1.flags.writeable = False
- try:
- results = holistic.process(cv2.cvtColor(frame1, cv2.COLOR_BGR2RGB))
- except Exception as e:
- print(e)
- mp_drawing.draw_landmarks(
- frame1,
- results.face_landmarks,
- mp_holistic.FACEMESH_CONTOURS,
- landmark_drawing_spec=None,
- connection_drawing_spec=mp_drawing_styles
- .get_default_face_mesh_contours_style())
- mp_drawing.draw_landmarks(
- frame1,
- results.pose_landmarks,
- mp_holistic.POSE_CONNECTIONS,
- landmark_drawing_spec=mp_drawing_styles
- .get_default_pose_landmarks_style())
- mp_drawing.draw_landmarks(
- frame1,
- results.left_hand_landmarks,
- mp_holistic.HAND_CONNECTIONS,
- landmark_drawing_spec=mp_drawing_styles
- .get_default_hand_landmarks_style())
- mp_drawing.draw_landmarks(
- frame1,
- results.right_hand_landmarks,
- mp_holistic.HAND_CONNECTIONS,
- landmark_drawing_spec=mp_drawing_styles
- .get_default_hand_landmarks_style())
- if rotNum is not None:
- frame1 = imutils.rotate_bound(frame1, angle=rotNum)
-
-
-
-
- cv2.imshow(camWindowName, frame1)
- if cv2.waitKey(1) & 0xFF == 27:
- # == ord('q') for q
- break
-
- else:
- break
- cv2.destroyWindow(camWindowName)
-
-
-
-def RunSetup(cam_inputs, rotation_input, paramDict,mediaPipeOverlay):
- """
- Start video setup by threading instances of the VideoSetup class
- """
- if not cam_inputs:
- raise ValueError("Camera input list (cam_inputs) is empty")
-
- ulist = []
-
- for cam_input, cam_rotation in zip(cam_inputs, rotation_input):
- if mediaPipeOverlay == True:
- u = MediaPipeVideoSetup(cam_input, paramDict, cam_rotation)
- else:
- u = VideoSetup(cam_input, paramDict, cam_rotation)
- u.start()
- ulist.append(u)
-
- for k in ulist:
- k.join()
-
-
-
-
-
-def detect_charuco_board(image, annotate_image=True):
- """
- Charuco base pose estimation.
- more-or-less copied from - https://mecaruco2.readthedocs.io/en/latest/notebooks_rst/Aruco
- /sandbox/ludovic/aruco_calibration_rotation.html
- """
- charuco_corners = []
- charuco_ids = []
-
- aruco_dict = cv2.aruco.Dictionary_get(cv2.aruco.DICT_4X4_250)
- charuco_length = 7
- charuco_width = 5
-
- board = cv2.aruco.CharucoBoard_create(charuco_length, charuco_width, 1, .8, aruco_dict)
- global num_charuco_corners
- num_charuco_corners = (charuco_length-1) * (charuco_width-1)
-
-
- # SUB PIXEL CORNER DETECTION CRITERION
- criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 100, 0.00001)
-
- gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
- aruco_square_corners, aruco_square_ids, rejectedImgPoints = cv2.aruco.detectMarkers(gray,
- aruco_dict)
-
- if len(aruco_square_corners) > 0:
- # SUB PIXEL DETECTION
- for this_corner in aruco_square_corners:
- cv2.cornerSubPix(gray, this_corner,
- winSize=(3, 3),
- zeroZone=(-1, -1),
- criteria=criteria)
- res2 = cv2.aruco.interpolateCornersCharuco(aruco_square_corners, aruco_square_ids, gray,
- board)
-
- if res2[1] is not None and res2[2] is not None and len(res2[1]) > 3:
- charuco_corners = res2[1]
- charuco_ids = res2[2]
-
-
- return charuco_corners, charuco_ids, aruco_square_corners, aruco_square_ids
-
-def annotate_image_with_charuco_data(image, charuco_corners, charuco_ids)->bool:
-
- full_charuco_detected_on_this_frame = False
- if len(charuco_ids) == num_charuco_corners:
- full_charuco_detected_on_this_frame = True
-
- image_w_markers = cv2.aruco.drawDetectedCornersCharuco(image,
- np.array(charuco_corners),
- np.array(charuco_ids),
- (200,100,200,255)) #I think cv2 uses BGR instead of RGB?
-
-
- text_to_write_on_this_camera = ''
- current_cam_corner_count_str = str(
- len(charuco_ids)) + " of " + str(
- num_charuco_corners) + " ChAruco Corner Points detected | Full Board Detected: " + str(
- full_charuco_detected_on_this_frame)
- # TODO - Determine 'shared views' (i.e. frames in which a full board is detected by 2 cameras)
- # TODO - self.determine_shared_charuco_board_views()
- # this_cam_shared_views_str = " | Shared Views: " + str(
- # each_cameras_shared_board_view_count_total)
- text_to_write_on_this_camera = current_cam_corner_count_str
-
- position = (10, 50)
- cv2.putText(
- image_w_markers, # numpy array on which text is written
- text_to_write_on_this_camera, # text
- position, # position at which writing has to start
- cv2.FONT_HERSHEY_SIMPLEX, # font family
- .5, # font size
- (0, 10, 0, 255), # font color
- 4) # font stroke (draw a darker heavier font beneath a lighter/thinner copy for readability)
-
- cv2.putText(
- image_w_markers, # numpy array on which text is written
- text_to_write_on_this_camera, # text
- position, # position at which writing has to start
- cv2.FONT_HERSHEY_SIMPLEX, # font family (very limited selection, i think there's some interesting CV history here...)
- .5, # font size
- (209, 180, 0, 255), # font color
- 2 ) # font stroke
-
- if full_charuco_detected_on_this_frame:
- cv2.polylines(image_w_markers, np.int32([charuco_corners]), True, (0, 255, 255), 4)
- # for these_corners in charuco_points_from_previous_frames:
- # if len(these_corners)>0:
- # cv2.polylines(image_w_markers, np.int32([these_corners]), True, (0,100,255,255/2), 2)
-
- return True
\ No newline at end of file
diff --git a/freemocap/webcam/checkcams.py b/freemocap/webcam/checkcams.py
deleted file mode 100644
index 86653a3a..00000000
--- a/freemocap/webcam/checkcams.py
+++ /dev/null
@@ -1,44 +0,0 @@
-from tqdm import tqdm
-import cv2
-import os
-import platform
-
-def TestDevice(source):
- """
- Checks to see if there is a camera available at the input
- """
- if platform.system() == 'Windows':
- cap = cv2.VideoCapture(source, cv2.CAP_DSHOW)
- else:
- cap = cv2.VideoCapture(source, cv2.CAP_ANY)
-
- # if cap is None or not cap.isOpened():
- # print('Warning: unable to open video source: ', source)
-
- if cap.isOpened():
- success, image = cap.read()
- if success:
- # print('Opened: ',source)
- # print('Exposure: '+ str(cap.get(cv2.CAP_PROP_EXPOSURE)))
- # time.sleep(3)
- cap.release()
- cv2.destroyAllWindows()
- open_cam = source
- return open_cam
- else:
- return None
- else:
- return None
-
-
-def CreateAvailableCamList():
- """
- Loops through the first 20 ports (this number is overkill, really) and creates a list of ports that have a camera available on them
- """
- openCamList = []
- for x in tqdm(range(20)): # range 20 right now to be safe
- openCamera = TestDevice(x)
- if openCamera is not None:
- openCamList.append(openCamera)
-
- return openCamList
diff --git a/freemocap/webcam/recordGUI.py b/freemocap/webcam/recordGUI.py
deleted file mode 100644
index dc9cbe87..00000000
--- a/freemocap/webcam/recordGUI.py
+++ /dev/null
@@ -1,381 +0,0 @@
-# -*- coding: utf-8 -*-
-"""
-Created on Wed Mar 3 12:18:46 2021
-
-@author: Rontc
-"""
-import tkinter as tk
-from tkinter import Tk, Label, Button, Frame, Listbox, Entry, filedialog
-from freemocap.webcam import checkcams
-import pickle
-import datetime
-from pathlib import Path
-import sys
-
-
-class recordGUI:
- # this GUI detects how many cameras you have available and presents them in
- # a listbox, and allows you to pick a task for the cameras
- def __init__(self, master):
- self.master = master
- self.refresh = False
- # Detect how many inputs you have available
- available_inputs = checkcams.CreateAvailableCamList()
- number_of_cams = len(available_inputs)
- cam_statement = (
- "You have "
- + str(number_of_cams)
- + " cameras available at inputs "
- + str(available_inputs)
- )
-
- self.master.title("Choose Your Cameras/Task")
- bottom_frame = Frame(self.master, height=100)
- bottom_frame.pack(side=tk.BOTTOM)
- # ---creates a listbox with all the available camera choices
- self.list_box = Listbox(self.master, selectmode="multiple")
- for i in available_inputs:
- self.list_box.insert(i, str(i))
-
- # ---setting up the task radiobutton
- # creates the different options and the values associated with them
- options = [("Setup", "setup"), ("Record", "record")]
-
- # initializes currentTask as a string variable and defaults it to setup
- self.currentTask = tk.StringVar()
- self.currentTask.set("setup")
-
- # ---display the detection results
- tk.Label(self.master, text=cam_statement, justify=tk.RIGHT).pack()
- tk.Label(self.master, text="Select Your Cameras", justify=tk.RIGHT).pack()
- self.list_box.pack()
-
- # ---create the task radiobutton
- tk.Label(
- self.master, text="""Select 'Setup' to preview cameras \n or \n 'Record' to create recording""", justify=tk.CENTER
- ).pack()
-
- for option, val in options:
- tk.Radiobutton(
- self.master, text=option, padx=20, variable=self.currentTask, value=val
- ).pack(anchor=tk.W)
-
- self.refresh_button = Button(bottom_frame, text="Re-detect Cameras", command=self.Refresh)
- self.refresh_button.pack(side=tk.RIGHT)
-
-
- self.sub_button = Button(bottom_frame, text="Submit", command=self.Submit)
- self.sub_button.pack(side=tk.RIGHT)
-
-
- def Submit(self):
- self.taskChoice = self.currentTask.get()
- self.selected = [
- int(self.list_box.get(pos)) for pos in self.list_box.curselection()
- ]
- self.refresh = False
- self.master.destroy()
-
- def Refresh(self):
- self.refresh = True
- self.master.destroy()
-
-
-
-class SettingsGUI:
- def __init__(
- self,
- master,
- cam_inputs,
- parameter_dictionary,
- rotation_dictionary,
- sessionID_in,
- task,
- current_path_to_save,
- ):
- self.master = master
- self.cam_inputs = cam_inputs
- self.parameter_dictionary = parameter_dictionary
- self.rotation_dictionary = rotation_dictionary
- self.sessionID_in = sessionID_in
- self.task = task
- self.currentPath = current_path_to_save
- self.mediaPipeOverlay = False
- # check if any previous parameters exist
- if self.parameter_dictionary is not None:
- existing_parameters = True
- else:
- existing_parameters = False
-
- # check to see if there are any stored rotations for the cameras chosen
- rotationValues = self.RotationRetrieval(cam_inputs, rotation_dictionary)
-
- # create frames to organize rotation inputs, resolution inputs, and parameter inputs
- topFrame = Frame(self.master)
- topFrame.pack(side=tk.TOP)
- if self.task == 'record':
- recordingSettingsFrame = Frame(self.master)
- recordingSettingsFrame.pack()
- rotLabelFrame = Frame(self.master)
- rotLabelFrame.pack()
- resFrame = Frame(self.master)
- resFrame.pack()
- parametersFrame = Frame(self.master)
- parametersFrame.pack()
- bottomFrame = Frame(self.master).pack(side=tk.BOTTOM)
-
-
-
- taskText = "Current Task: " + self.task
- taskLabel = Label(topFrame, text=taskText, font="bold")
- taskLabel.pack()
- # ---Rotation Options. Dynamically creates radio button options depending
- # ---on how many cameras there are
- rotation_options = [
- ("rotate 0", 0),
- ("rotate 90", 90),
- ("rotate 180", 180),
- ("rotate 270", 270),
- ]
- # radVar = tk.IntVar() #Radio Button Variable
- self.rotation_list = []
- rotationRadioButton = {}
- # creates radio buttons for each cam and stores the chosen rotation degree in a list
- for cam, rotDegree in zip(self.cam_inputs, rotationValues):
- current_rotation = tk.IntVar()
- current_rotation.set(rotDegree)
- self.rotation_list.append(current_rotation)
- tk.Label(rotLabelFrame, text="Choose rotation for Cam " + str(cam)).pack()
- for option, degree in rotation_options:
- rotationRadioButton[cam] = tk.Radiobutton(
- rotLabelFrame, text=option, value=degree, variable=current_rotation
- ).pack()
-
- # ---Resolution Height and Resolution Width entry
- widthLabel = Label(resFrame, text="Resolution Width").pack(side="left")
- self.resWidthEntry = Entry(resFrame)
- self.resWidthEntry.pack(side="left")
- heightLabel = Label(resFrame, text="Resolution Height").pack(side="left")
- self.resHeightEntry = Entry(resFrame)
- self.resHeightEntry.pack(side="left")
-
- # ---Exposure,FPS, and codec entry
- exposureLabel = Label(parametersFrame, text="Exposure").pack(side="left")
- self.exposureEntry = Entry(parametersFrame)
- self.exposureEntry.pack(side="left")
- FPSLabel = Label(parametersFrame, text="FPS").pack(side="left")
- self.FPSEntry = Entry(parametersFrame)
- self.FPSEntry.pack(side="left")
- codecLabel = Label(parametersFrame, text="codec").pack(side="left")
- self.codecEntry = Entry(parametersFrame)
- self.codecEntry.pack(side="left")
-
- if self.task == "setup":
- self.var1 = tk.IntVar()
- c1 = tk.Checkbutton(parametersFrame, text='Mediapipe Overlay',variable=self.var1, onvalue=1, offvalue=0)
- c1.pack(side = 'right')
-
- # ---SessionID entry- default is the date/time
- if self.task == "record":
- sessionText = "Change SessionID if desired"
- sessionLabel = Label(recordingSettingsFrame, text=sessionText)
- sessionLabel.pack()
-
- self.sessionIDEntry = Entry(recordingSettingsFrame)
- self.sessionIDEntry.pack()
- self.sessionIDEntry.insert(0, self.sessionID_in)
-
- pathText = 'Choose where to create your Freemocap_Data folder:'
- pathLabel = Label(recordingSettingsFrame, text=pathText)
- pathLabel.pack()
-
- text = 'Current file path: ' + self.currentPath
- self.currentPathText = tk.StringVar()
- self.currentPathText.set(text)
- currentPathLabel = Label(recordingSettingsFrame,textvariable = self.currentPathText)
- currentPathLabel.pack()
-
- self.path_changed = False #will be set to True if the user changes the path with the file dialog
-
- changepath_button = Button(recordingSettingsFrame,text = 'Change File Path',command = self.openFileDialog)
- changepath_button.pack(side = 'left')
-
- #savedefault_button = Button(recordingSettingsFrame,text = 'Save as Default Path')
- #savedefault_button.pack(side = 'left')
-
- # ---If previous parameters were recieved, insert them into the entry boxes
- if existing_parameters == True:
-
- self.exposureEntry.insert(0, parameter_dictionary["exposure"])
- self.resWidthEntry.insert(0, parameter_dictionary["resWidth"])
- self.resHeightEntry.insert(0, parameter_dictionary["resHeight"])
- self.codecEntry.insert(0, parameter_dictionary["codec"])
- self.FPSEntry.insert(0, parameter_dictionary["framerate"])
-
- # ---Submit button to hit when things are finalized
- self.sub_button = Button(bottomFrame, text="Submit - Start Cameras", command=self.Submit)
- self.sub_button.pack(side=tk.BOTTOM)
-
- def openFileDialog(self):
- self.currentPath = filedialog.askdirectory(
- title='Open a file',
- initialdir= Path.cwd())
- self.currentPathText.set('Current file path: ' + self.currentPath)
-
-
- def Submit(self):
- # get the final entries for all parameters
- # get the rotations for each camera and save them as values of a dictionary
- self.rotation_output = {}
- for count, cam in enumerate(self.cam_inputs):
- self.rotation_output[cam] = self.rotation_list[count].get()
-
- # built a parameter dictionary by .get()-ing the values from each entry
- self.paramDict = {
- "exposure": int(self.exposureEntry.get()),
- "resWidth": int(self.resWidthEntry.get()),
- "resHeight": int(self.resHeightEntry.get()),
- "framerate": int(self.FPSEntry.get()),
- "codec": str(self.codecEntry.get()),
- }
-
- if self.task == "setup":
- if self.var1.get()==1:
- self.mediaPipeOverlay=True
-
- # spit out the sessionID
- if self.task == "record":
- self.sessionID_out = self.sessionIDEntry.get()
- self.save_path = self.currentPath
- self.master.destroy()
-
- def RotationRetrieval(self, cam_inputs, rotation_dictionary):
- # takes the input cameras and compares them to the dictionary of
- # rotation values from the last session. For any matching cameras,
- # grab the rotation values. Otherwise, the rotation value is None
- rotationValues = []
- for cam in cam_inputs:
- if cam in rotation_dictionary.keys():
- rotationValues.append(rotation_dictionary[cam])
- else:
- rotationValues.append(0)
- return rotationValues
-
-
-
-
-
-
-class ProceedToRecordGUI:
- def __init__(self, master, sessionID_in, current_path_to_save):
- self.master = master
- self.restart_setup = False
- self.sessionID_in = sessionID_in
- self.continueToRecording = ""
- self.sessionID_out = ""
- self.currentPath = current_path_to_save
-
- sessionText = "Proceed to recording? \n sessionID:"
- sessionLabel = Label(master, text=sessionText)
- sessionLabel.pack(side="top")
-
- self.sessionIDEntry = Entry(master)
- self.sessionIDEntry.pack()
- self.sessionIDEntry.insert(0, self.sessionID_in)
-
-
- pathText = 'Choose where to create your data folder:'
- pathLabel = Label(master,text=pathText)
- pathLabel.pack()
-
- text = 'Current file path: ' + self.currentPath
- self.currentPathText = tk.StringVar()
- self.currentPathText.set(text)
- currentPathLabel = Label(master,textvariable = self.currentPathText)
- currentPathLabel.pack()
-
- changepath_button = Button(master,text = 'Change Folder Path',command = self.openFileDialog)
- changepath_button.pack(side = 'left')
-
- # master.title("Proceed to Recording?")
- self.proceed_button = Button(text="Begin Recording!", command=self.proceed)
- self.change_button = Button(text = "Change Parameters", command = self.change_params)
- self.stop_button = Button(text="Quit", command=self.stop)
- self.stop_button.pack(side=tk.RIGHT)
- self.change_button.pack(side = tk.LEFT)
- self.proceed_button.pack(side=tk.RIGHT)
-
-
- def openFileDialog(self):
- self.currentPath = filedialog.askdirectory(
- title='Open a file',
- initialdir= Path.cwd())
- self.currentPathText.set('Current file path: ' + self.currentPath)
-
-
- def stop(self):
- self.master.destroy()
- sys.exit("Quitting Program")
-
- def change_params(self):
- self.restart_setup = True
- self.sessionID_out = self.sessionIDEntry.get()
- self.save_path = self.currentPath
- self.master.destroy()
-
-
- def proceed(self):
- self.continueToRecording = True
- self.sessionID_out = self.sessionIDEntry.get()
- self.save_path = self.currentPath
- self.master.destroy()
-
-
-
-def RunChoiceGUI():
-
- # ---Get the camera inputs and the task
- refresh = True
- while refresh:
- root = tk.Tk()
- camera_choice = recordGUI(root)
- root.mainloop()
- refresh = camera_choice.refresh
-
- cam_inputs = camera_choice.selected
- if not cam_inputs:
- raise ValueError("No camera inputs selected")
- task = camera_choice.taskChoice
-
- return cam_inputs,task
-
-
-def RunParametersGUI(sessionID_in, rotation_entry, parameter_entry,current_path_to_save,cam_inputs,task):
- # ---Get all the necessary parameters
- root = tk.Tk()
- recording_settings = SettingsGUI(
- root, cam_inputs, parameter_entry, rotation_entry, sessionID_in, task, current_path_to_save
- )
- root.mainloop()
-
- # ---Create the parameters we'll need to run the records
- # rotation_input = list(test.rotation_output.values())
-
- paramDict = recording_settings.paramDict
-
- if task == "record":
- sessionID = recording_settings.sessionID_out
- savepath = recording_settings.save_path
- else:
- sessionID = None
- savepath = None
-
- return recording_settings.rotation_output, paramDict, sessionID,savepath, recording_settings.mediaPipeOverlay
-
-
-def RunProceedtoRecordGUI(sessionID_in,current_path_to_save):
- root = tk.Tk()
- goToRecording = ProceedToRecordGUI(root, sessionID_in,current_path_to_save)
- root.mainloop()
-
- return goToRecording.continueToRecording, goToRecording.restart_setup,goToRecording.sessionID_out, goToRecording.save_path
diff --git a/freemocap/webcam/startcamrecording.py b/freemocap/webcam/startcamrecording.py
deleted file mode 100644
index e700a2ef..00000000
--- a/freemocap/webcam/startcamrecording.py
+++ /dev/null
@@ -1,128 +0,0 @@
-import threading
-import cv2
-import time
-import pickle
-import os
-import platform
-
-class CamRecordingThread(threading.Thread):
- def __init__(
- self, session, camID, unix_camID, camInput, videoName, rawVidPath, beginTime, parameterDictionary
- ):
- threading.Thread.__init__(self)
- self.camID = camID
- self.unix_camID = unix_camID
- self.camInput = camInput
- self.videoName = videoName
- self.rawVidPath = rawVidPath
- self.beginTime = beginTime
- self.parameterDictionary = parameterDictionary
- self.session = session
-
- def run(self):
- print("Starting " + self.camID)
- self.timeStamps = CamRecording(
- self.session,
- self.camID,
- self.unix_camID,
- self.camInput,
- self.videoName,
- self.rawVidPath,
- self.beginTime,
- self.parameterDictionary,
- )
-
- def getStamps(self):
- return self.timeStamps
-
-
-# the recording function that each threaded camera object runs
-def CamRecording(
- session, camID, unix_camID, camInput, videoName, rawVidPath, beginTime, parameterDictionary
-):
- """
- Runs the recording process for each threaded camera instance. Saves a video to the RawVideos folder.
- Saves a timestamp for each frame into a pickle file. Checks for whether the global variable 'flag'
- has been set to True to end the recording (the first camera to end sets the flag to True, which
- means the rest of the cameras will quit in short order)
- """
- # the flag is triggered when the user shuts down one webcam to shut down the rest.
- # normally I'd try to avoid global variables, but in this case it's
- # necessary, since each webcam runs as it's own object.
- global flag
- flag = False
- camWindowName = "RECORDING - " + str(camID)+' - Press ESC to exit'
- cv2.namedWindow(camWindowName) # name the preview window for the camera its showing
-
- if platform.system() == 'Windows':
- cam = cv2.VideoCapture(camInput, cv2.CAP_DSHOW)
- else:
- cam = cv2.VideoCapture(camInput, cv2.CAP_ANY)
-
-
- # if not cam.isOpened():
- # raise RuntimeError('No camera found at input '+ str(camID))
- # pulling out all the dictionary paramters
- exposure = parameterDictionary.get("exposure")
- resWidth = parameterDictionary.get("resWidth")
- resHeight = parameterDictionary.get("resHeight")
- framerate = parameterDictionary.get("framerate")
- codec = parameterDictionary.get("codec")
-
-
-
-
- cam.set(cv2.CAP_PROP_FRAME_WIDTH, resWidth)
- cam.set(cv2.CAP_PROP_FRAME_HEIGHT, resHeight)
- cam.set(cv2.CAP_PROP_EXPOSURE, exposure)
- cam.set(cv2.CAP_PROP_FOURCC, cv2.VideoWriter_fourcc('M', 'J', 'P', 'G'))
- fourcc = cv2.VideoWriter_fourcc(*codec)
- # rawPath = filepath/'RawVideos' #creating a RawVideos folder
- # rawPath.mkdir(parents = True, exist_ok = True)
- width = cam.get(cv2.CAP_PROP_FRAME_WIDTH)
- height = cam.get(cv2.CAP_PROP_FRAME_HEIGHT)
- print("width:", width, "height:", height)
- saveRawVidPath = str(rawVidPath / videoName) # create a save path for each video to the RawVideos folders
-
- out = cv2.VideoWriter(saveRawVidPath, fourcc, framerate, (resWidth, resHeight))
- timeStamps = [] # holds the timestamps
- timeStamps_unix = []
- timeStamps_unix.append(beginTime) #the first timestamp for each camera in the unix CSV will always be the begin time
-
- if cam.isOpened():
- success, frame = cam.read()
- else:
- success = False
-
- while (success): # while the camera is opened, record the data until the escape button is hit
- if flag: # when the flag is triggered, stop recording and dump the data
- with open(session.rawVidPath/camID, "wb") as f:
- pickle.dump(timeStamps, f)
-
- with open(session.rawVidPath/unix_camID,"wb") as g:
- pickle.dump(timeStamps_unix,g)
- break
- success, frame = cam.read()
-
-
- cv2.imshow(camWindowName, frame)
- frame_sized = cv2.resize(frame, (resWidth, resHeight))
- frame_sized = frame
- out.write(frame)
- timeStamps.append(time.time() - beginTime) # add each timestamp to the list
- timeStamps_unix.append(time.time())
-
-
- key = cv2.waitKey(20)
- if key == 27: # exit on ESC
- flag = True # set flag to true to shut down all other webcams
- with open(session.rawVidPath/camID, "wb") as f:
- pickle.dump(timeStamps, f) # dump the data
- with open(session.rawVidPath/unix_camID,"wb") as g:
- pickle.dump(timeStamps_unix,g)
- break
- cv2.destroyWindow(camWindowName)
- return timeStamps,timeStamps_unix
-
-
-# this is how we sync our time frames, based on our recorded timestamps
diff --git a/freemocap/webcam/timesync.py b/freemocap/webcam/timesync.py
deleted file mode 100644
index d80de80e..00000000
--- a/freemocap/webcam/timesync.py
+++ /dev/null
@@ -1,301 +0,0 @@
-import numpy as np
-import pandas as pd
-import sys
-from matplotlib.figure import Figure
-from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
-import tkinter as tk
-from tkinter import Tk, Label, Button, Frame
-
-def TimeSync(session,timeStampData,numCamRange,camNames):
- """
- First creates a master timeline from the average frame length interval across all cameras. Then proceeds to compare timepoints in master timeline
- to timestamps in each camera and find the closest matching timestamp in a camera to a point on the master timeline and create a list of
- frame numbers.
-
- Then loop through the list of frame numbers from each camera. Update counts for missing frames and duplicated frames. Create a table with these counts
- and plots of statistics related to the recording
- """
- def CloseNeighb(camera,point):
- """
- Find the timestamp in the camera timestamp list that most closely matches the input pointin the master timeline
- """
- closestPoint = (np.abs(camera - point)).argmin()
- return closestPoint
-
- # this section auto-finds the start and end points for our master timeline to the nearest second
- masterTimelineBegin = np.ceil(max(timeStampData.iloc[0]))
- lastPoints = []
- for name in camNames:
- cameraLastPoint = timeStampData[name][
- timeStampData[name].last_valid_index()
- ] # find the last non-nan value in each camera
- lastPoints.append(cameraLastPoint)
-
- masterTimelineEnd = np.floor(min(lastPoints)) #find where the fastest camera ended, round down, use that as the end point
-
-
- #print('end',endList)
- print('intervals:',masterTimelineBegin,masterTimelineEnd)
-
- preSyncTotalNumFrames = []
- totalFrameIntvl= [] #list for storing frame rates for each camera
-
-
- n = 0; #counter for going through camera names
- for x in numCamRange:
- currentCam = timeStampData[camNames[x]]
- #finds the closest point in each camera to the start and end points of our timeline
- currentCamStart = CloseNeighb(currentCam,masterTimelineBegin)
- currentCamEnd = CloseNeighb(currentCam,masterTimelineEnd)
-
-
- print("using frames:", currentCamStart,"-",currentCamEnd,"for",camNames[n])
- n +=1
- currentCamTimeline = currentCam[currentCamStart:currentCamEnd] #grab the times from start to finish for each camera
-
- currentCamNumFrames = len(currentCamTimeline)
-
- currentCamFrameInterval = np.mean(np.diff(currentCamTimeline)) #calculate the interval between each frame and take the mean
-
- totalFrameIntvl.append(currentCamFrameInterval) #add interval to list
- preSyncTotalNumFrames.append(currentCamNumFrames)
- #print(camNames[x],currentCamStart,currentCamEnd)
-
- #print(preSyncTotalNumFrames, 'presync')
- #assert preSyncTotalNumFrames.count(preSyncTotalNumFrames[0]) == len(preSyncTotalNumFrames), "Number of frames sliced for each camera pre-syncing is not the same"
-
- totalAverageIntvl = np.mean(totalFrameIntvl) #find the total average interval across all cameras
- masterTimeline = np.arange(masterTimelineBegin,masterTimelineEnd,totalAverageIntvl) #build a master timeline with the average interval
-
- #now we start the syncing process
-
- frameList = masterTimeline #start a list of frames, with the first row being our master timeline
- timeList = masterTimeline #start a list of timestamps,with the first row being our master timeline
-
- unix_converted_timeList = range(len(masterTimeline)) #keep a record of unix timestamps before they're normalized to fit the master timeline
- delNum= []; #stores number of deleted frames/camera
- bufNum= []; #stores number of buffered frames/camera
- bufPercentList = []; #stores percentage of deleted frames/camera
- delPercentList = []; #stores percentage of buffered frames/camera
-
- count = 0 #Keeps track of what frame we're on (I think?)
- n = 0; #I don't remember why I did this but I'm sure I'll figure it out later
-
-
- postSyncTotalNumFrames = []
- for y in numCamRange:
- thisCam = timeStampData[camNames[y]]
- camTimes = []
- original_camTimes = []
- # stored times
- camFrames = []
- # stored frames
-
- count += 1
- # --------------Adjust each camera to start at the first point in the master timeline
- beginFrame = CloseNeighb(thisCam, masterTimeline[0])
- timeDif = masterTimeline[0] - thisCam[beginFrame]
- thisCam = thisCam + timeDif
-
- for z in masterTimeline: #for each point in the master timeline
- closestFrame = CloseNeighb(thisCam, z) #find the closest frame in this camera to each point of the master timeline
- camFrames.append(closestFrame) #add that frame to the list
- camTimes.append(thisCam[closestFrame]) #find the time corresponding to this frame
-
- print("starting detection:",camNames[n]) #now to start finding deleted/buffered slides
- frameList = np.column_stack((frameList,camFrames)) #update our framelist with our new frames
- timeList = np.column_stack((timeList,camTimes)) #update our timelist
-
- original_camTimes = camTimes - timeDif
- if session.get_synced_unix_timestamps == True: #this is bad coding please forgive me -
- unix_converted_original_camTimes = original_camTimes + session.beginTime
- unix_converted_timeList = np.column_stack((unix_converted_timeList,unix_converted_original_camTimes))
- else:
- unix_converted_original_camTimes = original_camTimes
- unix_converted_timeList = np.column_stack((unix_converted_timeList,unix_converted_original_camTimes))
-
-
- #start counters for the number of buffered and deleted slides
- bufCount = 0
- delCount = 0
-
- thisCamNumFrames = len(camFrames)
- postSyncTotalNumFrames.append(thisCamNumFrames)
-
- for i in range(0,len(camFrames)-1):
- distanceBetweenFrames = camFrames[i+1] - camFrames[i] #find the distance between adjacent frames
- if distanceBetweenFrames == 1: #these frames are consecutive, do nothing
- None
- elif distanceBetweenFrames == 0: #we have a buffered slide
- bufCount += 1
- # this section looks at our two timepoints, and finds the which point on the master timeline is closest
- frame1 = abs(masterTimeline[i] - camTimes[i])
- frame2 = abs(masterTimeline[i + 1] - camTimes[i])
- # finds which frame is closest, and sets the other frame as a buffer (indicated by the -1)
- if frame1 > frame2:
- frameList[i, count] = -1
- timeList[i, count] = -1
- unix_converted_timeList[i,count] = -1
- else:
- frameList[i + 1, count] = -1
- timeList[i + 1, count] = -1
- unix_converted_timeList[i+1,count] = -1
- elif distanceBetweenFrames > 1: # deletion
- delCount += 1
- else:
-
- print("something else happened")
- #update and calculate our percentages and numbers for buffers/deletions
- delNum.append(round(delCount,1))
- bufNum.append(round(bufCount,1))
- #print(bufCount,len(frameList))
- bufPercent = (bufCount/len(frameList))*100
- delPercent = (delCount/len(frameList))*100
- bufPercentList.append(round(bufPercent,2))
- delPercentList.append(round(delPercent,2))
-
- #print(delNum,bufNum,bufPercentList,delPercentList)
- #print("deleted frames:",delCount)
- #print("buffered frames:",bufCount)
- n +=1
-
- #print(postSyncTotalNumFrames, 'post-sync')
- assert postSyncTotalNumFrames.count(postSyncTotalNumFrames[0]) == len(postSyncTotalNumFrames), "Number of frames sliced for each camera post-syncing is not the same"
-
- session.postSyncNumFrames = postSyncTotalNumFrames[0]
-
- #create our data frame for both times and frames
- frameTable = pd.DataFrame(frameList)
- columnNames = ['Master Timeline'] + camNames
- frameTable.columns = columnNames
- timeTable = pd.DataFrame(timeList)
- timeTable.columns = columnNames
-
- unix_synced_timeTable = pd.DataFrame(unix_converted_timeList)
- unix_synced_table_columnNames = ['Frame'] + camNames
- unix_synced_timeTable.columns = unix_synced_table_columnNames
-
- totalFrameRate = [round(1 / intvl, 1) for intvl in totalFrameIntvl]
- frameRate = 1 / totalAverageIntvl # calculates our framerate
- results = {
- "Cam": camNames,
- "#Del": delNum,
- "%Del": delPercentList,
- "#Buf": bufNum,
- "%Buf": bufPercentList,
- "FPS": totalFrameRate,
- }
- resultTable = pd.DataFrame(
- results, columns=["Cam", "#Del", "%Del", "#Buf", "%Buf", "FPS"]
- )
-
- # ============================================== plot data
- differenceFrame = timeStampData.diff(axis=0)
- fpsFrame = differenceFrame.pow(-1)
- fig = Figure(figsize=[10, 10])
- fig.patch.set_facecolor("#F0F0F0")
- a = fig.add_subplot(221)
- a.set_xlabel("Frame")
- a.set_ylabel("Time(s)")
- timeStampData.plot(ax=a, title="Camera timestamps")
- b = fig.add_subplot(222)
- b.set_xlabel("Frame")
- b.set_ylabel("Frame duration (s)")
- differenceFrame.plot(
- ax=b, marker=".", linestyle="none", title="Camera frame duration"
- )
- c = fig.add_subplot(223)
- c.set_xlabel("Time (s)")
- differenceFrame.plot.hist(
- ax=c, bins=6, alpha=0.5, xlim=[0, 0.1], title="Frame interval distribution (s)"
- )
- d = fig.add_subplot(224)
- d.set_xlabel("Frames per second")
- fpsFrame.plot.hist(
- ax=d, bins=6, alpha=0.5, xlim=[0, 40], title="Frames per second distribution"
- )
- return frameTable, timeTable, unix_synced_timeTable,frameRate, resultTable, fig
-
-
-# function to trim our videos
-
-
-class proceedGUI:
- """
- GUI that displays all statistics from recording, and then asks for user input on whether to proceed with the rest of the pipeline
- """
- def __init__(self, master, results, figure):
- self.master = master
- self.results = results
- self.figure = figure
- self.proceed = ""
- master.title("Choose File Path")
-
- bottom_frame = Frame(self.master, height=1000)
- bottom_frame.pack(side=tk.LEFT)
- self.label = Label(bottom_frame, text=results.to_string(index=False))
- self.label.pack(side=tk.TOP)
- self.go_button = Button(bottom_frame, text="Proceed", command=self.destroy)
- self.stop_button = Button(bottom_frame, text="Quit", command=self.stop)
-
- self.canvas = FigureCanvasTkAgg(self.figure, master=self.master)
- self.canvas.draw()
- self.canvas.get_tk_widget().pack(side=tk.LEFT, fill="both", expand=1)
-
- self.stop_button.pack(side=tk.RIGHT)
- self.go_button.pack(side=tk.RIGHT)
-
- def stop(self):
- self.master.destroy()
- sys.exit("Quitting Program")
-
- def destroy(self):
- self.proceed = True
- self.master.destroy()
-
-
-
-
-def time_sync_initialize(session):
- """
- Initialize settings specific to the time syncing stage if running stage 2
- """
- #from the config settings add the camera input parameters to parameter dictionary
- session.initialize(stage = 2)
- session.parameterDictionary = session.session_settings['recording_parameters']['ParameterDict']
- rotationDict = session.session_settings['recording_parameters']['RotationInputs']
- session.rotationInputs = list(rotationDict.values())
- #initialize the path to the timestamp csv
- csvName = session.sessionID + '_timestamps.csv'
- csvPath = session.rawVidPath/csvName
-
- #read CSV data, turn it into a data frame
- timeStampData = pd.read_csv (csvPath)
- timeStampData = timeStampData.iloc[:,1:]
-
- #get the camIDs and number of cameras (numCamRange) from the dataframe
- camIDs = list(timeStampData.columns)
- numCams = len(camIDs)
- numCamRange = range(len(camIDs))
-
- #create names for each of the raw videos
- vidNames = []
- for x in numCamRange:
- singleVidName = 'raw_cam{}.mp4'.format(x+1)
- vidNames.append(singleVidName)
-
- if session.get_synced_unix_timestamps == True:
- unix_timestamp_csvName = session.sessionID + "_unix_timestamps.csv"
- unixTimeStampDataPath = session.rawVidPath/unix_timestamp_csvName
- cam_to_search_for_begin_time = camIDs[0] + '_unix_timestamps'
- unix_timestamp_data = pd.read_csv(unixTimeStampDataPath)
- unix_timestamp_data = unix_timestamp_data.iloc[:,1:]
- beginTime = unix_timestamp_data[cam_to_search_for_begin_time][0]
- session.beginTime = beginTime
- #initialize all the session variables we'll need to run the rest of the pipeline
- session.timeStampData = timeStampData
- session.camIDs = camIDs
- session.numCamRange = numCamRange
- session.vidNames = vidNames
- session.numCams = numCams
-
diff --git a/freemocap/webcam/videotrim.py b/freemocap/webcam/videotrim.py
deleted file mode 100644
index b79ae330..00000000
--- a/freemocap/webcam/videotrim.py
+++ /dev/null
@@ -1,116 +0,0 @@
-from rich.progress import track
-import cv2
-import imutils
-import numpy as np
-import os
-
-
-def VideoTrim(session, vidList, ft, parameterDictionary, rotationState, numCamRange):
- """
- From the list of saved frames from the time-syncing function, create synced videos by pulling those specific
- frames from the original raw videos into new videos, replacing any duplicate frames with a black 'buffer' slide
- """
- camList = list(
- ft.columns[1 : len(vidList) + 1]
- ) # grab the camera identifiers from the data frame
- resWidth = parameterDictionary.get("resWidth")
- resHeight = parameterDictionary.get("resHeight")
- framerate = parameterDictionary.get("framerate")
- trueWidth = resWidth # creating true resWidth and resHeight in case we need to rotate our images
- trueHeight = resHeight
- codec = parameterDictionary.get("codec")
- postTrimmingTotalNumFrames = []
-
- for vid,cam,camNum in zip(vidList,camList,numCamRange): #iterate in parallel through camera identifiers and matching videos
- this_vid_path = session.rawVidPath/vid
- print('synchronizing video at - ' + str(this_vid_path))
- cap = cv2.VideoCapture(str(this_vid_path)) #initialize OpenCV capture
- frameTable = ft[cam] #grab the frames needed for that camera
- success, image = cap.read() #start reading frames
- prev_image=image.copy()
- fourcc = cv2.VideoWriter_fourcc(*codec)
- saveName = session.sessionID + "_synced_" + cam + ".mp4"
-
- saveSyncedVidPath = str(
- session.syncedVidPath / saveName
- ) # create an output path for the function
- if rotationState[camNum] == 90 or rotationState[camNum] == 270:
- # if we are rotating to these angles, we need to temporarily swap our resWidth and resHeight
- tempHeight = resHeight
- resHeight = resWidth
- resWidth = tempHeight
-
- out = cv2.VideoWriter(
- saveSyncedVidPath, fourcc, framerate, (resWidth, resHeight)
- ) # change resolution as needed
- count = 0
- for frame in track(frameTable): # start looking through the frames we need
- if frame == -1: # this is a buffer frame
- blankFrame = np.zeros_like(image) # create a blank frame
- if rotationState[camNum] is not None:
- blankFrame = imutils.rotate_bound(
- blankFrame, angle=rotationState[camNum]
- )
- blankFrame = cv2.resize(blankFrame, (resWidth, resHeight))
- out.write(prev_image) # write that frame to the video
- count += 1
- else:
- cap.set(
- cv2.CAP_PROP_POS_FRAMES, frame
- ) # set the video to the frame that we need
- success, image = cap.read()
- if rotationState[camNum] is not None:
- image = imutils.rotate_bound(image, angle=rotationState[camNum])
- image = cv2.resize(image, (resWidth, resHeight))
- out.write(image)
- prev_image=image.copy()
-
- resWidth = trueWidth
- resHeight = trueHeight
- cap.release()
- out.release()
- frame_length_cap = cv2.VideoCapture(saveSyncedVidPath)
- thisCamNumFrame = int(frame_length_cap.get(cv2.CAP_PROP_FRAME_COUNT))
- postTrimmingTotalNumFrames.append(thisCamNumFrame)
- print('Saved '+ saveSyncedVidPath)
- print()
-
- assert postTrimmingTotalNumFrames.count(postTrimmingTotalNumFrames[0]) == len(postTrimmingTotalNumFrames), "Number of frames in each synced video is not the same"
- session.postTrimmingNumFrames = postTrimmingTotalNumFrames[0]
- session.numFrames = postTrimmingTotalNumFrames[0]
-
-
-def createCalibrationVideos(session,calVideoFrameLength,parameterDictionary):
-
- vidList = os.listdir(session.syncedVidPath)
- framelist = list(range(calVideoFrameLength))
- codec = parameterDictionary.get("codec")
- for count, vid in enumerate(vidList, start=1):
- cam_name = "Cam{}".format(count)
- cap = cv2.VideoCapture(str(session.syncedVidPath / vid))
- fourcc = cv2.VideoWriter_fourcc(*codec)
-
- # grab resolution parameters from the videos
- resWidth = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
- resHeight = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
- framerate = int(cap.get(cv2.CAP_PROP_FPS))
-
- saveName = (
- session.sessionID + "_trimmed_" + cam_name + ".mp4"
- ) # create a name for the trimmed video
- saveCalVidPath = str(
- session.calVidPath / saveName
- ) # create an output path for the function
-
- success, image = cap.read() # start reading frames
-
- out = cv2.VideoWriter(saveCalVidPath, fourcc, framerate, (resWidth, resHeight))
- print("Trimming " + cam_name)
- for frame in track(framelist):
- cap.set(
- cv2.CAP_PROP_POS_FRAMES, frame
- ) # set the video to the frame that we need
- success, image = cap.read()
- out.write(image)
- cap.release()
- out.release()
diff --git a/freemocap_blender_addon/freemocap_blendARmocap_not_so_megascript.py b/freemocap_blender_addon/freemocap_blendARmocap_not_so_megascript.py
deleted file mode 100644
index d7082e85..00000000
--- a/freemocap_blender_addon/freemocap_blendARmocap_not_so_megascript.py
+++ /dev/null
@@ -1,4 +0,0 @@
-# based on `blendAr_mocap` blender add-on by CG-Tinker
-# https://github.com/cgtinker/BlendArMocap\
-#pulls from `github-@jonmatthis`'s forkl of `cgtinker`'s original repository
-
diff --git a/freemocap_blender_addon/freemocap_blender_addon/__init__.py b/freemocap_blender_addon/freemocap_blender_addon/__init__.py
deleted file mode 100644
index 6f36379a..00000000
--- a/freemocap_blender_addon/freemocap_blender_addon/__init__.py
+++ /dev/null
@@ -1,43 +0,0 @@
-# This program is free software; you can redistribute it and/or modify
-# it under the terms of the GNU General Public License as published by
-# the Free Software Foundation; either version 3 of the License, or
-# (at your option) any later version.
-#
-# This program is distributed in the hope that it will be useful, but
-# WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTIBILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-# General Public License for more details.
-#
-# You should have received a copy of the GNU General Public License
-# along with this program. If not, see <http://www.gnu.org/licenses/>.
-
-bl_info = {
- "name" : "FreeMoCap",
- "author" : "Jonathan Samir Matthis",
- "description" : "",
- "blender" : (2, 80, 0),
- "version" : (0, 0, 1),
- "location" : "",
- "warning" : "",
- "category" : "fmc"
-}
-
-import bpy
-from . import auto_load
-
-auto_load.init()
-
-def register():
-
- #define 'custom properties' - https://youtu.be/9fuFDHR-UkE
-
- bpy.types.Scene.fmc_session_path = bpy.props.StringProperty(
- name = 'FMC Session Path',
- subtype= 'FILE_PATH'
- )
-
- auto_load.register()
- print('registering FreeMoCap Addon')
-
-def unregister():
- auto_load.unregister()
diff --git a/freemocap_blender_addon/freemocap_blender_addon/auto_load.py b/freemocap_blender_addon/freemocap_blender_addon/auto_load.py
deleted file mode 100644
index c7674ed9..00000000
--- a/freemocap_blender_addon/freemocap_blender_addon/auto_load.py
+++ /dev/null
@@ -1,158 +0,0 @@
-import os
-import bpy
-import sys
-import typing
-import inspect
-import pkgutil
-import importlib
-from pathlib import Path
-
-__all__ = (
- "init",
- "register",
- "unregister",
-)
-
-blender_version = bpy.app.version
-
-modules = None
-ordered_classes = None
-
-def init():
- global modules
- global ordered_classes
-
- modules = get_all_submodules(Path(__file__).parent)
- ordered_classes = get_ordered_classes_to_register(modules)
-
-def register():
- for cls in ordered_classes:
- bpy.utils.register_class(cls)
-
- for module in modules:
- if module.__name__ == __name__:
- continue
- if hasattr(module, "register"):
- print(f'registering module: {module.__name__}')
- module.register()
-
-def unregister():
- for cls in reversed(ordered_classes):
- bpy.utils.unregister_class(cls)
-
- for module in modules:
- if module.__name__ == __name__:
- continue
- if hasattr(module, "unregister"):
- module.unregister()
-
-
-# Import modules
-#################################################
-
-def get_all_submodules(directory):
- return list(iter_submodules(directory, directory.name))
-
-def iter_submodules(path, package_name):
- for name in sorted(iter_submodule_names(path)):
- yield importlib.import_module("." + name, package_name)
-
-def iter_submodule_names(path, root=""):
- for _, module_name, is_package in pkgutil.iter_modules([str(path)]):
- if is_package:
- sub_path = path / module_name
- sub_root = root + module_name + "."
- yield from iter_submodule_names(sub_path, sub_root)
- else:
- yield root + module_name
-
-
-# Find classes to register
-#################################################
-
-def get_ordered_classes_to_register(modules):
- return toposort(get_register_deps_dict(modules))
-
-def get_register_deps_dict(modules):
- my_classes = set(iter_my_classes(modules))
- my_classes_by_idname = {cls.bl_idname : cls for cls in my_classes if hasattr(cls, "bl_idname")}
-
- deps_dict = {}
- for cls in my_classes:
- deps_dict[cls] = set(iter_my_register_deps(cls, my_classes, my_classes_by_idname))
- return deps_dict
-
-def iter_my_register_deps(cls, my_classes, my_classes_by_idname):
- yield from iter_my_deps_from_annotations(cls, my_classes)
- yield from iter_my_deps_from_parent_id(cls, my_classes_by_idname)
-
-def iter_my_deps_from_annotations(cls, my_classes):
- for value in typing.get_type_hints(cls, {}, {}).values():
- dependency = get_dependency_from_annotation(value)
- if dependency is not None:
- if dependency in my_classes:
- yield dependency
-
-def get_dependency_from_annotation(value):
- if blender_version >= (2, 93):
- if isinstance(value, bpy.props._PropertyDeferred):
- return value.keywords.get("type")
- else:
- if isinstance(value, tuple) and len(value) == 2:
- if value[0] in (bpy.props.PointerProperty, bpy.props.CollectionProperty):
- return value[1]["type"]
- return None
-
-def iter_my_deps_from_parent_id(cls, my_classes_by_idname):
- if bpy.types.Panel in cls.__bases__:
- parent_idname = getattr(cls, "bl_parent_id", None)
- if parent_idname is not None:
- parent_cls = my_classes_by_idname.get(parent_idname)
- if parent_cls is not None:
- yield parent_cls
-
-def iter_my_classes(modules):
- base_types = get_register_base_types()
- for cls in get_classes_in_modules(modules):
- if any(base in base_types for base in cls.__bases__):
- if not getattr(cls, "is_registered", False):
- yield cls
-
-def get_classes_in_modules(modules):
- classes = set()
- for module in modules:
- for cls in iter_classes_in_module(module):
- classes.add(cls)
- return classes
-
-def iter_classes_in_module(module):
- for value in module.__dict__.values():
- if inspect.isclass(value):
- yield value
-
-def get_register_base_types():
- return set(getattr(bpy.types, name) for name in [
- "Panel", "Operator", "PropertyGroup",
- "AddonPreferences", "Header", "Menu",
- "Node", "NodeSocket", "NodeTree",
- "UIList", "RenderEngine",
- "Gizmo", "GizmoGroup",
- ])
-
-
-# Find order to register to solve dependencies
-#################################################
-
-def toposort(deps_dict):
- sorted_list = []
- sorted_values = set()
- while len(deps_dict) > 0:
- unsorted = []
- for value, deps in deps_dict.items():
- if len(deps) == 0:
- sorted_list.append(value)
- sorted_values.add(value)
- else:
- unsorted.append(value)
- deps_dict = {value : deps_dict[value] - sorted_values for value in unsorted}
- return sorted_list
diff --git a/freemocap_blender_addon/freemocap_blender_addon/build_armature_from_raw_mocap_data.py b/freemocap_blender_addon/freemocap_blender_addon/build_armature_from_raw_mocap_data.py
deleted file mode 100644
index fd9871a6..00000000
--- a/freemocap_blender_addon/freemocap_blender_addon/build_armature_from_raw_mocap_data.py
+++ /dev/null
@@ -1,547 +0,0 @@
-
-#this is copied more or less straight from jallex's `freemocap/fmc_blender` script. It needs some work, but it does do the job!
-
-import bpy
-import numpy as np
-from pathlib import Path
-import math
-from mathutils import Vector
-
-class FMC_OT_build_armature_from_raw_mocap_data(bpy.types.Operator): #setting the type as "FMC" for "FreeMoCap"
- """ Load marker data via FMC yaml config and place empties in Blender scene """
- bl_idname = "fmc.build_armature_from_raw_mocap_data"
- bl_label = "Build an armature from raw mocap data (in development)"
- bl_options = {'REGISTER', 'UNDO'}
-
-
- def execute(self, context):
- session_path = Path(context.scene.fmc_session_path)
-
- if not session_path.is_dir():
- session_path = session_path.parent
-
- input_npy = session_path / 'DataArrays' / 'mediaPipeSkel_3d.npy'
- ##########
- #### Begin Copy for fmc_blender
- ##########
-
- #the path of the npy build data file
- build_data = Path(__file__).parent.resolve() / "build_data.npy"
-
- #3D array holding [[[x, y, z], [x, y, z]], [[x, y, z], [x, y, z]]]
- arr = np.load(input_npy)
-
- # Saved clean frame where all points are visible and not NANs
- markers_list = np.load(build_data)
-
- #a list containing empty objects
- order_of_markers = []
-
- #frame rate
- bpy.context.scene.render.fps = 30
-
- #dictionary corresponding to marker numbers and body parts
- body_dict = {
- 0:"head1",
- 11:"shoulder_L",
- 12:"shoulder_R",
- 13:"elbow_L",
- 14:"elbow_R",
- 23:"hip_L",
- 24:"hip_R",
- 25:"knee_L",
- 26:"knee_R",
- 27:"ankle_L",
- 28:"ankle_R",
- 29:"heel_L",
- 30:"heel_R",
- 31:"toe_L",
- 32:"toe_R" }
-
- #-----------------------------------------------------------------------------------
-
- # set project unit
- bpy.context.scene.unit_settings.length_unit = 'METERS'
- #iterate through arr and create an empty object at that location for each element
- for index, col in enumerate(markers_list):
- # parse string float value into floats, create Vector, set position to Vector
-
- if math.isnan(col[0]):
- col[0] = 0.0
- if math.isnan(col[1]):
- col[1] = 0.0
- if math.isnan(col[2]):
- col[2] = 0.0
- coord = Vector(((float(col[0])*0.001), (float(col[2])*0.001), (float(col[1]))* -0.001))
-
- #empties
- bpy.ops.object.add(type='EMPTY', location=coord)
- mt = bpy.context.active_object
- mt.name = "mt_" + str(index)
- if index in body_dict.keys():
- mt.name += "_" + str(body_dict[index])
- order_of_markers.append(mt)
- #link empty to scene
- bpy.context.scene.collection.objects.link( mt )
- #set location
- mt.location = coord
- #set the display size of the empty
- mt.empty_display_size = 0.02
-
- #--------------------------------------------------------------
- #Virtual Markers!
-
- # marker relationships:
-
- # - "weight": the weighted average of multiple markers. the virtual_markers[x] contains the
- #list of markers that affect this virtual one. the weights[x] contains their corresponding weights in order.
-
- bpy.ops.object.mode_set(mode='OBJECT', toggle=False)
-
- #Create virtual marker where parameters are the name of the marker, the markers that affect its position, and each of their weights.
- def create_marker_weight(name, markers, weighted):
- center = Vector((0, 0, 0))
- weight_iter = 0
- for x in markers:
- center += x.location*weighted[weight_iter]
- weight_iter += 1
- coord = Vector((float(center[0]), float(center[1]), float(center[2])))
- bpy.ops.object.add(type='EMPTY', location=coord)
- mt = bpy.context.active_object
- mt.name = name
- bpy.context.scene.collection.objects.link( mt )
- mt.location = coord
- mt.empty_display_size = 0.02
- virtual_markers.append(mt)
-
- #Keeping track of virtual marker info using arrays, where each marker is an index in each array
- v_relationship = []
- virtual_markers = []
- surrounding_markers = []
- weights = []
-
- #updates data and creates virtual marker
- def update_virtual_data(relationship, surrounding, vweights, vname):
- v_relationship.append(relationship)
- surrounding_markers.append(surrounding)
- weights.append(vweights)
- create_marker_weight(vname, surrounding, vweights)
-
- #-----------------------------------------------------------------
- #Define relationships and create virtual markers
-
- #Neck Base: Halfway between order_of_markers[12] shoulder_L and order_of_markers[12] shoulder_R
- l0 = [order_of_markers[12], order_of_markers[11]]
- w0 = [0.5, 0.5]
- update_virtual_data("weight", l0, w0, "m_neck")
-
- #Waist Base: Halfway between order_of_markers[24] and order_of_markers[23]
- l0 = [order_of_markers[24], order_of_markers[23]]
- w0 = [0.5, 0.5]
- update_virtual_data("weight", l0, w0, "m_neck")
-
- #Update the location of virtual markers on each frame
- def update_virtual_marker(index):
- if(v_relationship[index] == "weight"):
- center = Vector((0, 0, 0))
- weight_iter = 0
- for x in surrounding_markers[index]:
- center += x.location*weights[index][weight_iter]
- weight_iter += 1
- coord = Vector((float(center[0]), float(center[1]), float(center[2])))
- virtual_markers[index].location = coord
-
- #-----------------------------------------------------------------------------------
- # Bones!
-
- #adds child bone given corresponding parent and empty
- #bone tail will appear at the location of empty
- def add_child_bone(bone_name, empty1, empty2):
- #Set armature selected
- armature_data.select_set(state=True)
- #Set edit mode
- bpy.ops.object.mode_set(mode='EDIT', toggle=False)
- #Create a new bone
- new_bone = armature_data.data.edit_bones.new(bone_name)
- #Set bone's size
- new_bone.head = (0,0,0)
- new_bone.tail = (0,0.1,0)
- #Set bone's location to wheel
- new_bone.matrix = empty2.matrix_world
- #set location of bone head
- new_bone.head = empty1.location
- #set location of bone tail
- new_bone.tail = empty2.location
- return new_bone
-
- #Create armature object
- armature = bpy.data.armatures.new('Armature')
- armature_object = bpy.data.objects.new('Armature', armature)
- #Link armature object to our scene
- bpy.context.collection.objects.link(armature_object)
- #Make armature variable
- armature_data = bpy.data.objects[armature_object.name]
- #Set armature active
- bpy.context.view_layer.objects.active = armature_data
- #Set armature selected
- armature_data.select_set(state=True)
- #Set edit mode
- bpy.ops.object.mode_set(mode='EDIT', toggle=False)
- #Set bones in front and show axis
- armature_data.show_in_front = True
- #True to show axis orientation of bones and false to hide it
- armature_data.data.show_axes = False
-
- #get armature object
- def get_armature():
- for ob in bpy.data.objects:
- if ob.type == 'ARMATURE':
- armature = ob
- break
- return armature
-
- armature = get_armature()
-
- #a list of tuples where each element represents the info for one bone, and
- #the tuple contains the bone name, the marker of the head, and the marker of the tail
- list_of_bones_order = [('upper_arm_L', order_of_markers[11], order_of_markers[13]),
- ('upper_arm_R', order_of_markers[12], order_of_markers[14]),
- ('lower_arm_L', order_of_markers[13], order_of_markers[15]),
- ('lower_arm_R', order_of_markers[14], order_of_markers[16]),
- ('upper_leg_L', order_of_markers[23], order_of_markers[25]),
- ('upper_leg_R', order_of_markers[24], order_of_markers[26]),
- ('lower_leg_L', order_of_markers[25], order_of_markers[27]),
- ('lower_leg_R', order_of_markers[26], order_of_markers[28]),
- ('heel_L', order_of_markers[27], order_of_markers[29]),
- ('heel_R', order_of_markers[28], order_of_markers[30]),
- ('foot_L', order_of_markers[29], order_of_markers[31]),
- ('foot_R', order_of_markers[30], order_of_markers[32]),
- ('neck', order_of_markers[0], virtual_markers[0]),
- ('eye_L', order_of_markers[0], order_of_markers[2]),
- ('ear_L', order_of_markers[2], order_of_markers[7]),
- ('eye_R', order_of_markers[0], order_of_markers[5]),
- ('ear_R', order_of_markers[5], order_of_markers[8]),
- ('shoulder_L', virtual_markers[0], order_of_markers[11]),
- ('shoulder_R', virtual_markers[0], order_of_markers[12]),
- ('torso', virtual_markers[1], virtual_markers[0]),
- ('hip_L', virtual_markers[1], order_of_markers[23]),
- ('hip_R', virtual_markers[1], order_of_markers[24]),
- ]
-
- #based on marker # from order_of_markers array add bones for hands:
- left_hand_offset = 54
- left_hand = [('handL0', order_of_markers[0+left_hand_offset], order_of_markers[1+left_hand_offset]),
- ('handL1', order_of_markers[1+left_hand_offset], order_of_markers[2+left_hand_offset]),
- ('handL2', order_of_markers[2+left_hand_offset], order_of_markers[3+left_hand_offset]),
- ('handL3', order_of_markers[3+left_hand_offset], order_of_markers[4+left_hand_offset]),
- ('handL5', order_of_markers[1+left_hand_offset], order_of_markers[5+left_hand_offset]),
- ('handL6', order_of_markers[5+left_hand_offset], order_of_markers[6+left_hand_offset]),
- ('handL7', order_of_markers[6+left_hand_offset], order_of_markers[7+left_hand_offset]),
- ('handL8', order_of_markers[7+left_hand_offset], order_of_markers[8+left_hand_offset]),
- ('handL9', order_of_markers[5+left_hand_offset], order_of_markers[9+left_hand_offset]),
- ('handL10', order_of_markers[9+left_hand_offset], order_of_markers[10+left_hand_offset]),
- ('handL11', order_of_markers[10+left_hand_offset], order_of_markers[11+left_hand_offset]),
- ('handL12', order_of_markers[11+left_hand_offset], order_of_markers[12+left_hand_offset]),
- ('handL13', order_of_markers[9+left_hand_offset], order_of_markers[13+left_hand_offset]),
- ('handL14', order_of_markers[13+left_hand_offset], order_of_markers[14+left_hand_offset]),
- ('handL15', order_of_markers[14+left_hand_offset], order_of_markers[15+left_hand_offset]),
- ('handL16', order_of_markers[15+left_hand_offset], order_of_markers[16+left_hand_offset]),
- ('handL17', order_of_markers[13+left_hand_offset], order_of_markers[0+left_hand_offset]),
- ('handL18', order_of_markers[0+left_hand_offset], order_of_markers[17+left_hand_offset]),
- ('handL19', order_of_markers[17+left_hand_offset], order_of_markers[18+left_hand_offset]),
- ('handL20', order_of_markers[18+left_hand_offset], order_of_markers[19+left_hand_offset]),
- ('wristL', order_of_markers[15], order_of_markers[0+left_hand_offset]),
- ('handL21', order_of_markers[19+left_hand_offset], order_of_markers[20+left_hand_offset]),]
-
- right_hand_offset = 33
-
- right_hand = [('handR0', order_of_markers[18], order_of_markers[1+right_hand_offset]),
- ('handR1', order_of_markers[1+right_hand_offset], order_of_markers[2+right_hand_offset]),
- ('handR2', order_of_markers[2+right_hand_offset], order_of_markers[3+right_hand_offset]),
- ('handR3', order_of_markers[3+right_hand_offset], order_of_markers[4+right_hand_offset]),
- ('handR5', order_of_markers[1+right_hand_offset], order_of_markers[5+right_hand_offset]),
- ('handR6', order_of_markers[5+right_hand_offset], order_of_markers[6+right_hand_offset]),
- ('handR7', order_of_markers[6+right_hand_offset], order_of_markers[7+right_hand_offset]),
- ('handR8', order_of_markers[7+right_hand_offset], order_of_markers[8+right_hand_offset]),
- ('handR9', order_of_markers[5+right_hand_offset], order_of_markers[9+right_hand_offset]),
- ('handR10', order_of_markers[9+right_hand_offset], order_of_markers[10+right_hand_offset]),
- ('handR11', order_of_markers[10+right_hand_offset], order_of_markers[11+right_hand_offset]),
- ('handR12', order_of_markers[11+right_hand_offset], order_of_markers[12+right_hand_offset]),
- ('handR13', order_of_markers[9+right_hand_offset], order_of_markers[13+right_hand_offset]),
- ('handR14', order_of_markers[13+right_hand_offset], order_of_markers[14+right_hand_offset]),
- ('handR15', order_of_markers[14+right_hand_offset], order_of_markers[15+right_hand_offset]),
- ('handR16', order_of_markers[15+right_hand_offset], order_of_markers[16+right_hand_offset]),
- ('handR17', order_of_markers[18], order_of_markers[13+right_hand_offset]),
- ('handR18', order_of_markers[18], order_of_markers[17+right_hand_offset]),
- ('handR19', order_of_markers[17+right_hand_offset], order_of_markers[18+right_hand_offset]),
- ('handR20', order_of_markers[18+right_hand_offset], order_of_markers[19+right_hand_offset]),
- ('wristR', order_of_markers[16], order_of_markers[18]),
- ('handR21', order_of_markers[19+right_hand_offset], order_of_markers[20+right_hand_offset]),]
-
- #helper to create armature from list of tuples
- def tuple_to_armature(bones):
- for bone_name, bone_head, bone_tail in bones:
- add_child_bone(bone_name, bone_head, bone_tail)
-
- #Set armature selected
- armature_data.select_set(state=True)
- #Set edit mode
- bpy.ops.object.mode_set(mode='EDIT', toggle=False)
-
- #create all bones for skeleton body and hands
- tuple_to_armature(list_of_bones_order)
- tuple_to_armature(right_hand)
- tuple_to_armature(left_hand)
-
- #parent heads and tails to empties
- #use bone constraints
- def parent_to_empties(bone_name, head, tail):
- #enter pose mode
- bpy.ops.object.posemode_toggle()
- marker = armature.data.bones[bone_name]
- #Set marker selected
- marker.select = True
- #Set marker active
- bpy.context.object.data.bones.active = marker
- bone = bpy.context.object.pose.bones[bone_name]
- #Copy Location Pose constraint: makes the bone's head follow the given empty
- bpy.ops.pose.constraint_add(type='COPY_LOCATION')
- bone.constraints["Copy Location"].target = head
- #Stretch To Pose constraint: makes the bone's tail follow the given empty
- #stretches the bones to reach the tail to that empty so head location is not affected
- bpy.ops.pose.constraint_add(type='STRETCH_TO')
- bone.constraints["Stretch To"].target = tail
- #exit pose mode
- bpy.ops.object.posemode_toggle()
-
- #set parents of heads and tails for each bone
- def tuple_to_parented(bones):
- for bone_name, bone_head, bone_tail in bones:
- parent_to_empties(bone_name, bone_head, bone_tail)
-
- tuple_to_parented(list_of_bones_order)
- tuple_to_parented(right_hand)
- tuple_to_parented(left_hand)
-
- #-----------------------------------------------------------------------------------
- # Animate!
- #find number of frames in animation
- num_frames = len(arr)
-
- #change start frame of animation
- bpy.context.scene.frame_start = 1
- #change end frame of animation
- bpy.context.scene.frame_end = num_frames - 1
-
- #create a new handler to change empty positions every frame
- def my_handler(scene):
- bpy.ops.object.mode_set(mode='OBJECT')
- #keep track of current_marker
- current_marker = 0
- #find the current frame number
- frame = scene.frame_current
- #get the list of marker points from the current frame
- markers_list = arr[frame]
- #iterate through list of markers in this frame
- for col in markers_list:
- frame = scene.frame_current
- if math.isnan(col[0]):
- col[0] = 0.0
- if math.isnan(col[1]):
- col[1] = 0.0
- if math.isnan(col[2]):
- col[2] = 0.0
- coord = Vector(((float(col[0])*0.001), (float(col[2])*0.001), (float(col[1]))* -0.001))
- if len(order_of_markers) > 0:
- empty = order_of_markers[current_marker]
- empty.location = coord
- current_marker += 1
- for index in range(len(virtual_markers)):
- update_virtual_marker(index)
-
-
- #keyframe bones
- #Goes through each bone
- for editBone in get_armature().data.edit_bones:
- boneName = editBone.name
- poseBone = arm.pose.bones[boneName]
- poseBone.keyframe_insert('rotation_euler', frame=scene.frame_current)
- poseBone.keyframe_insert('location', frame=scene.frame_current)
- poseBone.keyframe_insert('scale', frame=scene.frame_current)
-
- #-----------------------------------------------------------------------------------
- #script to create a mesh of the armature
- def CreateMesh():
- obj = get_armature()
-
- if obj == None:
- print( "No selection" )
- elif obj.type != 'ARMATURE':
- print( "Armature expected" )
- else:
- return processArmature( bpy.context, obj )
-
- #Use armature to create base object
- def armToMesh( arm ):
- name = arm.name + "_mesh"
- dataMesh = bpy.data.meshes.new( name + "Data" )
- mesh = bpy.data.objects.new( name, dataMesh )
- mesh.matrix_world = arm.matrix_world.copy()
- return mesh
-
- #Make vertices and faces
- def boneGeometry( l1, l2, x, z, baseSize, l1Size, l2Size, base ):
- x1 = x * baseSize * l1Size * 0.8
- z1 = z * baseSize * l2Size * 0.8
-
- x2 = Vector( (0, 0, 0) )
- z2 = Vector( (0, 0, 0) )
-
- verts = [
- l1 - x1 + z1,
- l1 + x1 + z1,
- l1 - x1 - z1,
- l1 + x1 - z1,
- l2 - x2 + z2,
- l2 + x2 + z2,
- l2 - x2 - z2,
- l2 + x2 - z2
- ]
-
- faces = [
- (base+3, base+1, base+0, base+2),
- (base+6, base+4, base+5, base+7),
- (base+4, base+0, base+1, base+5),
- (base+7, base+3, base+2, base+6),
- (base+5, base+1, base+3, base+7),
- (base+6, base+2, base+0, base+4)
- ]
-
- return verts, faces
-
- #Process the armature, goes through its bones and creates the mesh
- def processArmature(context, arm, genVertexGroups = True):
- print("processing armature {0}".format(arm.name))
-
- #Creates the mesh object
- meshObj = armToMesh( arm )
- context.collection.objects.link( meshObj )
-
- verts = []
- edges = []
- faces = []
- vertexGroups = {}
-
- bpy.ops.object.mode_set(mode='EDIT')
-
- try:
- #Goes through each bone
- for editBone in get_armature().data.edit_bones:
- boneName = editBone.name
- if boneName == "":
- editBone.name = "bone"
- boneName = "bone"
- poseBone = arm.pose.bones[boneName]
-
- #Gets edit bone informations
- editBoneHead = editBone.head
- editBoneTail = editBone.tail
- editBoneVector = editBoneTail - editBoneHead
- editBoneSize = editBoneVector.dot( editBoneVector )
- editBoneRoll = editBone.roll
- editBoneX = editBone.x_axis
- editBoneZ = editBone.z_axis
- editBoneHeadRadius = editBone.head_radius
- editBoneTailRadius = editBone.tail_radius
-
- #Creates the mesh data for the bone
- baseIndex = len(verts)
- baseSize = math.sqrt( editBoneSize )
- newVerts, newFaces = boneGeometry( editBoneHead, editBoneTail, editBoneX, editBoneZ, baseSize, editBoneHeadRadius, editBoneTailRadius, baseIndex )
- verts.extend( newVerts )
- faces.extend( newFaces )
-
- #Creates the weights for the vertex groups
- vertexGroups[boneName] = [(x, 1.0) for x in range(baseIndex, len(verts))]
- #Assigns the geometry to the mesh
- meshObj.data.from_pydata(verts, edges, faces)
-
- except:
- bpy.ops.object.mode_set(mode='OBJECT')
- else:
- bpy.ops.object.mode_set(mode='OBJECT')
- #Assigns the vertex groups
- if genVertexGroups:
- for name1, vertexGroup in vertexGroups.items():
- groupObject = meshObj.vertex_groups.new(name = name1)
- for (index, weight) in vertexGroup:
- groupObject.add([index], weight, 'REPLACE')
-
- #Creates the armature modifier
- modifier = meshObj.modifiers.new('ArmatureMod', 'ARMATURE')
- modifier.object = arm
- modifier.use_bone_envelopes = False
- modifier.use_vertex_groups = True
-
- meshObj.data.update()
-
- return meshObj
-
- mesh_obob = CreateMesh()
-
- #-----------------------------------------------------------------------------------
- # Clean up the mesh by removing duplicate vertices, make sure all faces are quads, etc
-
- checked = set()
- for selected_object in bpy.data.objects:
- if selected_object.type != 'MESH':
- continue
- meshdata = selected_object.data
- if meshdata in checked:
- continue
- else:
- checked.add(meshdata)
- bpy.context.view_layer.objects.active = selected_object
- bpy.ops.object.editmode_toggle()
- bpy.ops.mesh.select_all(action='SELECT')
- bpy.ops.mesh.remove_doubles()
- bpy.ops.mesh.tris_convert_to_quads()
- bpy.ops.mesh.normals_make_consistent()
- bpy.ops.object.editmode_toggle()
- #Set armature active
- bpy.context.view_layer.objects.active = armature_data
- #Set armature selected
- armature_data.select_set(state=True)
- #-----------------------------------------------------------------------------------
- #function to register custom handler
- bpy.app.handlers.frame_change_post.clear()
- def register():
- bpy.app.handlers.frame_change_post.append(my_handler)
-
- def unregister():
- bpy.app.handlers.frame_change_post.remove(my_handler)
-
- register()
-
- scene = bpy.context.scene
-
- bpy.ops.object.mode_set(mode='OBJECT')
-
- #set keyframes for whole animation
- for frame in range(scene.frame_start, scene.frame_end):
- scene.frame_set(frame)
-
- #Select objects to export
- col = bpy.data.collections.get("Collection")
- if col:
- for obj in col.objects:
- if "Armature" == obj.name:
- obj.select_set(True)
-
-
- ##########
- #### end Copy for fmc_blender ^^^
- ##########
-
- return{'FINISHED'}
-
diff --git a/freemocap_blender_addon/freemocap_blender_addon/build_data.npy b/freemocap_blender_addon/freemocap_blender_addon/build_data.npy
deleted file mode 100644
index 5b00b0b3..00000000
Binary files a/freemocap_blender_addon/freemocap_blender_addon/build_data.npy and /dev/null differ
diff --git a/freemocap_blender_addon/freemocap_blender_addon/import_freemocap_config.py b/freemocap_blender_addon/freemocap_blender_addon/import_freemocap_config.py
deleted file mode 100644
index 99625309..00000000
--- a/freemocap_blender_addon/freemocap_blender_addon/import_freemocap_config.py
+++ /dev/null
@@ -1,26 +0,0 @@
-
-# from pathlib import Path
-# import bpy
-
-# def get_session_path(scene) -> Path:
-# abspath = bpy.path.abspath(scene.fmc_session_path) #absolute path to this omc session's data
-# pathStringParts = abspath.split('\\') #split the absolute path at the \\'s
-# scene.fmc_session_id = pathStringParts[-2] #the 2nd to last element is the 'sessionID'
-# return Path(abspath)
-
-# class IMPORT_SCENE_OT_session_config_load(bpy.types.Operator):
-# bl_idname = 'fmc.load_session_config'
-# bl_label = 'Load Session Config.yaml'
-
-# def execute(self, context):
-# #find congif.yaml file for this session
-# import_path = get_session_path(context.scene)
-
-# iter = -1
-# for import_fpath in import_path.glob('*_config.yaml'):
-# iter +=1
-# assert iter < 1, 'Found Multiple *_config.yaml files, and thats not supposed to happen!'
-# bpy.types.Scene.fmc_session_path = import_fpath #path to the config gile
-# bpy.types.Scene.fmc_session_ID = import_fpath.name #name of the session
-# return{'FINISHED'}
-
diff --git a/freemocap_blender_addon/freemocap_blender_addon/load_freemocap_data_as_empties_script.py b/freemocap_blender_addon/freemocap_blender_addon/load_freemocap_data_as_empties_script.py
deleted file mode 100644
index 0ddbe7ce..00000000
--- a/freemocap_blender_addon/freemocap_blender_addon/load_freemocap_data_as_empties_script.py
+++ /dev/null
@@ -1,8 +0,0 @@
-import numpy as np
-import bpy
-
-from pathlib import Path
-
-from rich import print, inspect
-
-
diff --git a/freemocap_blender_addon/freemocap_blender_addon/load_marker_empties.py b/freemocap_blender_addon/freemocap_blender_addon/load_marker_empties.py
deleted file mode 100644
index 7adfa141..00000000
--- a/freemocap_blender_addon/freemocap_blender_addon/load_marker_empties.py
+++ /dev/null
@@ -1,194 +0,0 @@
-import bpy
-import numpy as np
-from pathlib import Path
-
-class FMC_OT_loadMarkerEmpties(bpy.types.Operator): #setting the type as "FMC" for "OpenMoCap"
- """ Load marker data via FMC yaml config and place empties in Blender scene """
- bl_idname = "fmc.load_marker_empties"
- bl_label = "Load Marker Empties"
- bl_options = {'REGISTER', 'UNDO'}
-
- emptyType: bpy.props.StringProperty(
- name = 'Empty Type',
- description = 'Type of empty to draw at marker locations (just `sphere` for now)',
- default = 'SPHERE',
- )
-
- emptySize: bpy.props.FloatProperty(
- name = 'Empty size',
- description = 'Size of the empty markers',
- default = .01,
- min = 0, soft_max =1,
- )
-
- def execute(self, context):
- configPath = Path(context.scene.fmc_session_path)
- sessionPath = configPath.parent
-
- try:
- openpose_3d_data_path = sessionPath / 'DataArrays' / 'openPoseSkel_3d.npy'
- openpose_skel_fr_mar_xyz = np.load(str(openpose_3d_data_path))
- #convert to meters
- openpose_skel_fr_mar_xyz = openpose_skel_fr_mar_xyz/1000
- #names of markers
- openpose_skel_marker_names = ["Nose", "Neck", "RShoulder", "RElbow", "RWrist", "LShoulder",
- "LElbow", "LWrist", "MidHip", "RHip", "RKnee", "RAnkle", "LHip", "LKnee",
- "LAnkle", "REye", "LEye", "REar", "LEar", "LBigToe", "LSmallToe", "LHeel",
- "RBigToe", "RSmallToe", "RHeel"]
- openpose_bool = True
- except:
- openpose_bool = False
- print('No OpenPose Data Found')
-
- try:
- mediapipe_3d_data_path = sessionPath / 'DataArrays' / 'mediapipeSkel_3d.npy'
- mediapipe_skel_fr_mar_xyz = np.load(str(mediapipe_3d_data_path))
- #convert to meters
- mediapipe_skel_fr_mar_xyz = mediapipe_skel_fr_mar_xyz/1000
- #names of markers
- mediapipe_skel_marker_names = [ "nose",
-
- "left_eye_inner",
- "left_eye",
- "left_eye_outer",
-
- "right_eye_inner",
- "right_eye",
- "right_eye_outer",
-
- "left_ear",
- "right_ear",
-
- "mouth_left",
- "mouth_right",
-
- "left_shoulder",
- "right_shoulder",
-
- "left_elbow",
- "right_elbow",
-
- "left_wrist",
- "right_wrist",
-
- "left_pinky",
- "right_pinky",
-
- "left_index",
- "right_index",
-
- "left_thumb",
- "right_thumb",
-
- "left_hip",
- "right_hip",
-
- "left_knee",
- "right_knee",
-
- "left_ankle",
- "right_ankle",
-
- "left_heel",
- "right_heel",
-
- "left_foot_index",
- "right_foot_index",
- ]
- mediapipe_hand_marker_names = ["wrist",
- "thumb_cmc",
- "thumb_mcp",
- "thumb_ip",
- "thumb_tip",
-
- "index_finger_cmc",
- "index_finger_mcp",
- "index_finger_ip",
- "index_finger_tip",
-
- "middle_finger_cmc",
- "middle_finger_mcp",
- "middle_finger_ip",
- "middle_finger_tip",
-
- "ring_finger_cmc",
- "ring_finger_mcp",
- "ring_finger_ip",
- "ring_finger_tip",
-
- "pinky_cmc",
- "pinky_mcp",
- "pinky_ip",
- "pinky_tip",
-
-
- ]
- mediapipe_bool = True
- except:
- mediapipe_bool = False
- print('No mediapipe Data Found')
-
-
- startFr = 0
- numFrames = mediapipe_skel_fr_mar_xyz.shape[0]-1
-
- bpy.context.scene.frame_end = numFrames
-
- #%% _______________________________________________________________________
- # Skreleton data!
- print('Loading Skeleton Markers!')
- face_iter = 0
-
- for marNum in range(len(mediapipe_skel_fr_mar_xyz[startFr,:,0])):
-
-
-
- thisMarLoc = mediapipe_skel_fr_mar_xyz[startFr,marNum,:]
-
- #these will define the size of teh body, hand, and face markers
- bms = self.emptySize
- hms = bms *.5
- fms = bms *.5
-
- emptyType = self.emptyType
-
- bpy.ops.object.empty_add(type=self.emptyType, align='WORLD', location=thisMarLoc, scale=(bms, bms, bms))
- thisMarker = context.active_object
-
- #get names of body markers from name array "skel_markerID" (and build hand and face names from there)
- if marNum < len(mediapipe_skel_marker_names) :
- thisMarker.name = mediapipe_skel_marker_names[marNum]
- thisMarker.scale = (bms, bms, bms)
- elif marNum < len(mediapipe_skel_marker_names) + 2*len(mediapipe_hand_marker_names):
-
- if marNum < len(mediapipe_skel_marker_names) +len(mediapipe_hand_marker_names):
- this_hand_prefix = 'right_hand_'
- this_hand_prefix = 'right_hand_'
- marker_num_offset = len(mediapipe_skel_marker_names)
- else:
- this_hand_prefix = 'left_hand_'
- marker_num_offset = len(mediapipe_skel_marker_names) + len(mediapipe_hand_marker_names)
-
- try:
- print('this hand marnum is ' + str(marNum-marker_num_offset))
- thisMarker.name = this_hand_prefix + mediapipe_hand_marker_names[marNum-marker_num_offset]
- except:
- print('something weired in hand town for marker num' + str(marNum))
- f=9
-
- thisMarker.scale=(hms, hms, hms)
-
- else:
- thisMarker.name = 'face_'+str(face_iter).zfill(4)
- face_iter += 1
- thisMarker.scale=(fms, fms, fms)
-
- #loop through each frame (after the first [0th] frame) to set the keyframes for this marker
- for fr in range(1, numFrames):
- thisMarker.location = mediapipe_skel_fr_mar_xyz[fr,marNum,:]
- thisMarker.keyframe_insert(data_path="location", frame=fr)
- print('loaded marker: '+ thisMarker.name)
-
- print('Done!')
- return{'FINISHED'}
-
diff --git a/freemocap_blender_addon/freemocap_blender_addon/load_nsynched_videos.py b/freemocap_blender_addon/freemocap_blender_addon/load_nsynched_videos.py
deleted file mode 100644
index 37f0ae03..00000000
--- a/freemocap_blender_addon/freemocap_blender_addon/load_nsynched_videos.py
+++ /dev/null
@@ -1,62 +0,0 @@
-import bpy
-import pickle
-
-from pathlib import Path
-
-class FMC_OT_loadVideos(bpy.types.Operator):
- """load in each of the nSynced Vidoes (n= numCams) as planes and place in 3d scene"""
- bl_idname = 'fmc.load_nsynced_videos'
- bl_label = "Load nSynched Videos"
- bl_options = {'REGISTER', 'UNDO'}
-
- def execute(self, context):
- session_path = Path(context.scene.fmc_session_path)
-
- if not session_path.is_dir():
- session_path = session_path.parent
-
-
- camera_calibration_pickle_path = session_path / (session_path.name + '_calibration.pickle')
-
- vidFolderPath = session_path / 'SyncedVideos'
-
-
-
- with open(camera_calibration_pickle_path, 'rb') as camera_calib_pickle:
- camera_calibration_dict = pickle.load(camera_calib_pickle)
-
- camera_translations = []
- camera_rotations = []
- for this_cam_calib_info in camera_calibration_dict:
- camera_translations.append(this_cam_calib_info['translation'])
- camera_rotations.append(this_cam_calib_info['rotation'])
-
-
-
- for vid_number, thisVidPath, in enumerate(vidFolderPath.glob('*.mp4')):
-
- this_camera_tx = camera_translations[vid_number][0]/1000 #convert to meters from millimeters
- this_camera_ty = camera_translations[vid_number][1]/1000
- this_camera_tz = camera_translations[vid_number][2]/1000
-
- this_camera_rx = camera_rotations[vid_number][0]
- this_camera_ry = camera_rotations[vid_number][1]
- this_camera_rz = camera_rotations[vid_number][2]
-
- #create camera object on Z-axis pointing down at origin
- bpy.ops.object.camera_add(align='WORLD')
- thisCam = context.active_object
- thisCam.location = (this_camera_tx,this_camera_ty,this_camera_tz)
- thisCam.rotation_euler = (this_camera_rx, this_camera_ry, this_camera_rz)
- # thisCam.scale = (5, 5, 5)
- thisCam.name = 'Cam' + str(iter)
-
- # use 'images as planes' add on to load in the video files as planes
- bpy.ops.import_image.to_plane(files=[{"name":thisVidPath.name}], directory=str(thisVidPath.parent), )
- thisVidPlane = context.active_object
- thisVidPlane.parent = thisCam #parent this image_plane to camera object
- thisVidPlane.location[2] -= 2 #bump it down a bit for aesthetics
-
- # context.active_object.location = (iter,iter,iter) #bump this image_plane over a bit so they don't over lap
-
- return {'FINISHED'}
\ No newline at end of file
diff --git a/freemocap_blender_addon/freemocap_blender_addon/load_raw_mocap_data_as_bones.py b/freemocap_blender_addon/freemocap_blender_addon/load_raw_mocap_data_as_bones.py
deleted file mode 100644
index 56a7da15..00000000
--- a/freemocap_blender_addon/freemocap_blender_addon/load_raw_mocap_data_as_bones.py
+++ /dev/null
@@ -1,183 +0,0 @@
-import bpy
-import numpy as np
-from pathlib import Path
-
-class FMC_OT_load_raw_mocap_data_as_bones(bpy.types.Operator): #setting the type as "FMC" for "FreeMoCap"
- """ Load marker data via FMC yaml config and place empties in Blender scene """
- bl_idname = "fmc.load_raw_mocap_data_as_bones"
- bl_label = "Load raw motion capture data as bones"
- bl_options = {'REGISTER', 'UNDO'}
-
- bone_size: bpy.props.FloatProperty(
- name = 'Bone size',
- description = 'Size of the bones',
- default = .2,
- min = 0, soft_max =1,
- )
-
- def execute(self, context):
- configPath = Path(context.scene.fmc_session_path)
- sessionPath = configPath.parent
-
- try:
- openpose_3d_data_path = sessionPath / 'DataArrays' / 'openPoseSkel_3d.npy'
- openpose_skel_fr_mar_xyz = np.load(str(openpose_3d_data_path))
- #convert to meters
- openpose_skel_fr_mar_xyz = openpose_skel_fr_mar_xyz/1000
- #names of markers
- openpose_skel_marker_names = ["Nose", "Neck", "RShoulder", "RElbow", "RWrist", "LShoulder",
- "LElbow", "LWrist", "MidHip", "RHip", "RKnee", "RAnkle", "LHip", "LKnee",
- "LAnkle", "REye", "LEye", "REar", "LEar", "LBigToe", "LSmallToe", "LHeel",
- "RBigToe", "RSmallToe", "RHeel"]
- openpose_bool = True
- except:
- openpose_bool = False
- print('No OpenPose Data Found')
-
- try:
- mediapipe_3d_data_path = sessionPath / 'DataArrays' / 'mediapipeSkel_3d.npy'
- mediapipe_skel_fr_mar_xyz = np.load(str(mediapipe_3d_data_path))
- #convert to meters
- mediapipe_skel_fr_mar_xyz = mediapipe_skel_fr_mar_xyz/1000
- #names of markers
- mediapipe_skel_marker_names = [ "nose",
-
- "left_eye_inner",
- "left_eye",
- "left_eye_outer",
-
- "right_eye_inner",
- "right_eye",
- "right_eye_outer",
-
- "left_ear",
- "right_ear",
-
- "mouth_left",
- "mouth_right",
-
- "left_shoulder",
- "right_shoulder",
-
- "left_elbow",
- "right_elbow",
-
- "left_wrist",
- "right_wrist",
-
- "left_pinky",
- "right_pinky",
-
- "left_index",
- "right_index",
-
- "left_thumb",
- "right_thumb",
-
- "left_hip",
- "right_hip",
-
- "left_knee",
- "right_knee",
-
- "left_ankle",
- "right_ankle",
-
- "left_heel",
- "right_heel",
-
- "left_foot_index",
- "right_foot_index",
- ]
- mediapipe_hand_marker_names = ["wrist",
- "thumb_cmc",
- "thumb_mcp",
- "thumb_ip",
- "thumb_tip",
-
- "index_finger_cmc",
- "index_finger_mcp",
- "index_finger_ip",
- "index_finger_tip",
-
- "middle_finger_cmc",
- "middle_finger_mcp",
- "middle_finger_ip",
- "middle_finger_tip",
-
- "ring_finger_cmc",
- "ring_finger_mcp",
- "ring_finger_ip",
- "ring_finger_tip",
-
- "pinky_cmc",
- "pinky_mcp",
- "pinky_ip",
- "pinky_tip",
-
-
- ]
- mediapipe_bool = True
- except:
- mediapipe_bool = False
- print('No mediapipe Data Found')
-
-
- startFr = 0
- numFrames = mediapipe_skel_fr_mar_xyz.shape[0]-1
-
- bpy.context.scene.frame_end = numFrames
-
- #%% _______________________________________________________________________
- # Skreleton data!
- print('Loading raw motion capture data as bones!')
- face_iter = 0
-
- # for marNum in range(len(mediapipe_skel_fr_mar_xyz[startFr,:,0])): #all dottos
- for marNum in range(len(mediapipe_skel_marker_names)): #only the body
-
- thisMarLoc = mediapipe_skel_fr_mar_xyz[startFr,marNum,:]
-
- #these will define the size of teh body, hand, and face markers
- bms = self.bone_size
- hms = bms *.5
- fms = bms *.5
-
-
-
- bpy.ops.object.armature_add(align='WORLD', location=thisMarLoc, scale=(bms, bms, bms))
- this_bone = context.active_object
-
-
- if marNum < len(mediapipe_skel_marker_names) : #body
- this_bone.name = mediapipe_skel_marker_names[marNum]
- this_bone.scale = (bms, bms, bms)
-
- elif marNum < len(mediapipe_skel_marker_names) + 2*len(mediapipe_hand_marker_names): #hands
-
- if marNum < len(mediapipe_skel_marker_names) +len(mediapipe_hand_marker_names):
- this_hand_prefix = 'right_hand_'
- this_hand_prefix = 'right_hand_'
- marker_num_offset = len(mediapipe_skel_marker_names)
- else:
- this_hand_prefix = 'left_hand_'
- marker_num_offset = len(mediapipe_skel_marker_names) + len(mediapipe_hand_marker_names)
-
- this_bone.name = this_hand_prefix + mediapipe_hand_marker_names[marNum-marker_num_offset]
-
- this_bone.scale=(hms, hms, hms)
-
- else: #face
- this_bone.name = 'face_'+str(face_iter).zfill(4)
- face_iter += 1
- this_bone.scale=(fms, fms, fms)
-
- #loop through each frame (after the first [0th] frame) to set the keyframes for this marker
- for fr in range(1, numFrames):
- this_bone.location = mediapipe_skel_fr_mar_xyz[fr,marNum,:]
- this_bone.keyframe_insert(data_path="location", frame=fr)
- print('loaded marker: '+ this_bone.name)
-
- print('Done!')
- return{'FINISHED'}
-
diff --git a/freemocap_blender_addon/freemocap_blender_addon/old_loadOpenMocapSession.py b/freemocap_blender_addon/freemocap_blender_addon/old_loadOpenMocapSession.py
deleted file mode 100644
index 5555eb3a..00000000
--- a/freemocap_blender_addon/freemocap_blender_addon/old_loadOpenMocapSession.py
+++ /dev/null
@@ -1,184 +0,0 @@
-import bpy
-import numpy as np
-from mathutils import Matrix, Vector, Euler
-import pathlib
-
-class OMC_OT_loadOpenMoCapSession(bpy.types.Operator): #setting the type as "OMC" for "OpenMoCap"
- """ Load data from an OpenMoCap(OMC) recording session into Blender """
- bl_idname = "omc.load_session_data"
- bl_label = "Load Session Data"
- bl_options = {'REGISTER', 'UNDO'}
-
- charucoMar_size: bpy.props.FloatProperty(
- name = 'Charuco Marker Size',
- description="Radius of the Charuco Marker Spheres",
- default = .2,
- min = 0, soft_max = 1,
- )
-
- dlcMar_size: bpy.props.FloatProperty(
- name = 'DLC Marker Size',
- description="Radius of the DLC Marker Spheres",
- default = .3,
- min = 0, soft_max = 1,
- )
-
- bodyMar_size: bpy.props.FloatProperty(
- name = 'Skeleton Body Marker Size',
- description="Radius of the Skeleton Body Marker Spheres",
- default = .2,
- min = 0, soft_max = 1,
- )
-
- faceMar_size: bpy.props.FloatProperty(
- name = 'Skeleton Face Marker Size',
- description="Radius of the Skeleton Face Marker Spheres",
- default = .15,
- min = 0, soft_max = 1,
- )
-
- handMar_size: bpy.props.FloatProperty(
- name = 'Skeleton Hand Marker Size',
- description="Radius of the Skeleton Hand Marker Spheres",
- default = .2,
- min = 0, soft_max = 1,
- )
-
- meshType: bpy.props.StringProperty(
- name = 'Marker Mesh Type',
- description = 'Type of mesh to draw at marker locations (just `sphere` and `monkey` for now)',
- default = 'uv_sphere',
- )
-
- def execute(self, context):
- """Load in data from an OpenMoCap recording session and place all 3D points as spheres in the 3D Viewport"""
- C = bpy.context
- D = bpy.data
-
- # #%% Nuke it all
- # bpy.ops.object.select_all(action='SELECT') #select all
- # bpy.ops.object.delete(use_global=False) #delete everything
-
- # try:
- # bpy.ops.outliner.select_all(action='SELECT')
- # bpy.ops.outliner.delete(hierarchy=True)
- # except:
- # pass
-
- #%% _______________________________________________________________________
- # Load in data
-
- loadedData = np.load(r"C:\Users\jonma\Dropbox\GitKrakenRepos\OpenMoCap\Data\test6_01_21a\outData\saveData.npz")
- skel_fr_mar_xyz = loadedData['skel_fr_mar_xyz'] #OpenPose skeleton data
- dlcPts_fr_mar_xyz = loadedData['dlcPts_fr_mar_xyz']
- charucoCorners_pt_XYZ = loadedData['charucoCornersXYZ']
-
- startFr = 0
- numFrames = skel_fr_mar_xyz.shape[0]-1
-
- #names of markers
- skel_markerID = ["Nose", "Neck", "RShoulder", "RElbow", "RWrist", "LShoulder",
- "LElbow", "LWrist", "MidHip", "RHip", "RKnee", "RAnkle", "LHip", "LKnee",
- "LAnkle", "REye", "LEye", "REar", "LEar", "LBigToe", "LSmallToe", "LHeel",
- "RBigToe", "RSmallToe", "RHeel"]
-
- #%% create spheres at marker locations
-
- #%% _______________________________________________________________________
- #Charuco grid!
- charucoCollectionName = 'CharucoBoard'
- # charColl = eby.create_collection(charucoCollectionName)
- # assert charColl.name == charucoCollectionName, 'Charuco Collection name doesnt match. Did it already exist when you tried to make it? If so, Blender would make a new one called `thing.001` or something'
-
- # C.scene.collection.children.link(charColl) #link the newly created collection to the Blender Scene (so it will show up in the outliner)
-
- print('Loading Charuco Markers')
- for marNum in range(len(charucoCorners_pt_XYZ[:,0])):
- thisMarLoc = charucoCorners_pt_XYZ[marNum,:]
- ms = self.charucoMar_size
-
- if self.meshType == 'uv_sphere':
- bpy.ops.mesh.primitive_uv_sphere_add(align='WORLD', location=thisMarLoc, scale=(ms, ms, ms))
- elif self.meshType == 'monkey':
- bpy.ops.mesh.primitive_monkey_add(align='WORLD', location=thisMarLoc, scale=(ms, ms, ms))
-
- thisMarker = C.active_object
-
- # eby.move_object_to_collection(thisMarker, charColl)
-
- #%% _______________________________________________________________________
- # Deeplabcut (DLC) data!
- dlcCollectionName = 'DLC'
- # dlcColl = eby.create_collection(dlcCollectionName)
- # assert dlcColl.name == dlcCollectionName, 'Charuco Collection name doesnt match. Did it already exist when you tried to make it? If so, Blender would make a new one called `thing.001` or something'
-
- # C.scene.collection.children.link(charColl) #link the newly created collection to the Blender Scene (so it will show up in the outliner)
-
- print('Loading DLC Markers')
- for marNum in range(len(dlcPts_fr_mar_xyz[0,:,0])):
- thisMarLoc = dlcPts_fr_mar_xyz[0,marNum,:]
- ms = self.dlcMar_size
-
- if self.meshType == 'uv_sphere':
- bpy.ops.mesh.primitive_uv_sphere_add(align='WORLD', location=thisMarLoc, scale=(ms, ms, ms))
- elif self.meshType == 'monkey':
- bpy.ops.mesh.primitive_monkey_add(align='WORLD', location=thisMarLoc, scale=(ms, ms, ms))
-
- thisMarker = C.active_object
- # eby.move_object_to_collection(thisMarker, dlcColl)
-
- #loop through each frame (after the first [0th] frame) to set the keyframes for this marker
- for fr in range(1, numFrames):
- thisMarker.location = dlcPts_fr_mar_xyz[fr,marNum,:]
- thisMarker.keyframe_insert(data_path="location", frame=fr)
-
-
-
- #%% _______________________________________________________________________
- # Skreleton data!
- skelCollectionName = 'skel'
- # skelColl = eby.create_collection(skelCollectionName)
- # assert skelColl.name == skelCollectionName, 'Charuco Collection name doesnt match. Did it already exist when you tried to make it? If so, Blender would make a new one called `thing.001` or something'
-
- # C.scene.collection.children.link(charColl) #link the newly created collection to the Blender Scene (so it will show up in the outliner)
- print('Loading Skeleton Markers!')
- for marNum in range(len(skel_fr_mar_xyz[startFr,:,0])):
- thisMarLoc = skel_fr_mar_xyz[startFr,marNum,:]
-
- #these will define the size of teh body, hand, and face markers
- bms = self.bodyMar_size
- hms = self.handMar_size
- fms = self.faceMar_size
-
- if self.meshType == 'uv_sphere':
- bpy.ops.object.armature_add(align='WORLD', location=thisMarLoc)
- elif self.meshType == 'monkey':
- bpy.ops.mesh.primitive_monkey_add(align='WORLD', location=thisMarLoc)
-
- thisMarker = C.active_object
-
- # eby.move_object_to_collection(thisMarker, skelColl)
-
- #get names of body markers from name array "skel_markerID" (and build hand and face names from there)
- if marNum < 25 :
- thisMarker.name = skel_markerID[marNum]
- thisMarker.scale = (bms, bms, bms)
- elif marNum < 46:
- if marNum == 26: print('Loading Hands')
- thisMarker.name = "HandR"
- thisMarker.scale=(hms, hms, hms)
- elif marNum < 67:
- thisMarker.name = "HandL"
- thisMarker.scale=(hms, hms, hms)
- else:
- if marNum == 67: print('Loading Face')
- thisMarker.name = 'Face'
- thisMarker.scale=(fms, fms, fms)
-
- #loop through each frame (after the first [0th] frame) to set the keyframes for this marker
- for fr in range(1, numFrames):
- thisMarker.location = skel_fr_mar_xyz[fr,marNum,:]
- thisMarker.keyframe_insert(data_path="location", frame=fr)
-
- return{'FINISHED'}
-
diff --git a/freemocap_blender_addon/freemocap_blender_addon/ui_view3d_panel.py b/freemocap_blender_addon/freemocap_blender_addon/ui_view3d_panel.py
deleted file mode 100644
index 9ea6c19b..00000000
--- a/freemocap_blender_addon/freemocap_blender_addon/ui_view3d_panel.py
+++ /dev/null
@@ -1,82 +0,0 @@
-import bpy
-from pathlib import Path
-
-#%% Build the User Interface panel
-class VIEW3D_PT_freemocap(bpy.types.Panel):
- bl_space_type = 'VIEW_3D'
- bl_region_type = 'UI'
- bl_category = "FreeMoCap"
- bl_label = "FMC_LoadSession"
-
- def draw(self,context):
- layout = self.layout
-
- #######################################################
- # UI_COLUMN_0 - The part of the panel where you specify the Session Folder
- ui_set_session_path = layout.column(align=True)
- ui_set_session_path.prop(context.scene, 'fmc_session_path' )
-
- if context.scene.fmc_session_path : #once you set the config path
- session_path = Path(context.scene.fmc_session_path)
- if session_path.is_dir(): #JSM NOTE - This is kinda sloppy, but I don't know how to alter the actual session path variable. I want there to be a way to enforce that the 'session_path' value points to the whole session folder, NOT a file within that folder
- ui_set_session_path.label(text=f'Session Path: {str(session_path)}')
- else:
- ui_set_session_path.label(text=f'Session Path: {str(session_path.parent)}')
- else:
- ui_set_session_path.label(text='-No Session Config Loaded-')
- ui_set_session_path.label(text='_______')
-
- #######################################################
-
- ui_column_1 = self.layout.column(align=True)
-
- ui_column_1.operator('fmc.load_marker_empties',
- text='Load Marker Empties!',
- icon = 'EMPTY_AXIS')
-
-
- #######################################################
-
- ui_as_bones_button = self.layout.column(align=True)
-
- ui_as_bones_button.operator('fmc.load_raw_mocap_data_as_bones',
- text='Load raw mocap data as bones!',
- icon = 'GROUP_BONE')
-
- #######################################################
-
- ui_build_armature= self.layout.column(align=True)
-
- ui_build_armature.operator('fmc.build_armature_from_raw_mocap_data',
- text='build armature from raw mocap data',
- icon = 'ARMATURE_DATA')
-
-
-
-
- #######################################################
- ui_column_2= self.layout.column(align=True)
-
- ui_column_2.operator('fmc.load_nsynced_videos',
- text='Load nSynced Videos!!',
- icon = 'CAMERA_DATA')
-
- # properties_0 = ui_column_2.operator('fmc.load_session_data',
- # text='Load FreeMoCap Session (Marshmallow Style!)',
- # icon = 'VOLUME_DATA')
- # properties_0.bodyMar_size = 10
- # properties_0.faceMar_size = 10
- # properties_0.handMar_size = 10
-
- # properties_1 = ui_column_2.operator('fmc.load_session_data',
- # text='Load FreeMoCap Session (Monkey Style)',
- # icon = 'MONKEY')
- # properties_1.meshType = 'monkey'
-
-
- #######################################################
- # UI_COLUMN_3 #The part of the panel where you click PLAY and whatnot
- ui_column_3 = self.layout.column(align=True)
- ui_column_3.prop(context.scene, 'frame_current', text='Current Frame#' )
- ui_column_3.operator('screen.animation_play', icon='PLAY')
-
diff --git a/freemocap_runme_script.py b/freemocap_runme_script.py
deleted file mode 100644
index 158422c6..00000000
--- a/freemocap_runme_script.py
+++ /dev/null
@@ -1,34 +0,0 @@
-import freemocap
-freemocap.RunMe()
-
-
-#####################
-### freemocap.RunMe() - Default parameters
-#####################
-
-# def RunMe(sessionID=None,
-# stage=1,
-# useOpenPose=False,
-# runOpenPose = True,
-# useMediaPipe=True,
-# runMediaPipe=True,
-# useDLC=False,
-# dlcConfigPath=None,
-# debug=False,
-# setDataPath = False,
-# userDataPath = None,
-# recordVid = True,
-# showAnimation = True,
-# reconstructionConfidenceThreshold = .5,
-# charucoSquareSize = 36,#mm - ~the size of the squares when printed on 8.5x11" paper based on parameters in ReadMe.md
-# calVideoFrameLength = 1,
-# startFrame = 0,
-# useBlender = False,
-# resetBlenderExe = False,
-# get_synced_unix_timestamps = True,
-# good_clean_frame_number = 0,
-# use_saved_calibration = False,
-# bundle_adjust_3d_points=False,
-# place_skeleton_on_origin = False,
-# save_annotated_videos = False,
-# ):
\ No newline at end of file
diff --git a/how_to_update_pip_package.txt b/how_to_update_pip_package.txt
deleted file mode 100644
index feba992a..00000000
--- a/how_to_update_pip_package.txt
+++ /dev/null
@@ -1,11 +0,0 @@
-
-git commit --allow-empty -m "REL: v0.0.31"
-git tag -a v0.0.31 # Don't forget the leading v
-git push origin main
-git push origin v0.0.31
-python3 -m pip install --upgrade wheel
-git clean -dfx
-python setup.py sdist
-python setup.py bdist_wheel
-twine upload dist/*
-
diff --git a/jon_scratch/__init__.py b/jon_scratch/__init__.py
deleted file mode 100644
index daacd152..00000000
--- a/jon_scratch/__init__.py
+++ /dev/null
@@ -1,3 +0,0 @@
-
-
-
diff --git a/jon_scratch/calculate_head_rotation_matrix.ipynb b/jon_scratch/calculate_head_rotation_matrix.ipynb
deleted file mode 100644
index a066aa25..00000000
--- a/jon_scratch/calculate_head_rotation_matrix.ipynb
+++ /dev/null
@@ -1,700 +0,0 @@
-{
- "cells": [
- {
- "cell_type": "markdown",
- "metadata": {
- "pycharm": {
- "name": "#%% md\n"
- }
- },
- "source": [
- "# Calculate head rotation matricies\n",
- "\n",
- "calculate orthonormal basis vectors of the head on each frame, stack them on top of each other to make 3x3 rotation matricies, because apparently that's how that works?!\n",
- "\n",
- "1 - calculate `head_center_xyz` as mean of left and right ear markers\n",
- "2 - define x+ as vector between `head_center_xyz` and `nose_xyz`- normalize to get `x_hat`\n",
- "3 - define y+ as vector between `head_center_xyz` and `left_ear_xyz` - normalize to get `y_hat_temp` (will be replaced later, to ensure orthogonal \\)\n",
- "4 - define z+ as cross product of `x_hat` and `y_hat`\n",
- "5 - replace `y_hat_temp` with `z_hat` crossed wtih `x_hat` (Pretty sure that makes it right handed...)\n",
- "\n",
- "Stack x_hat, y_hat, and z_hat on top of each other, and that's your head rotation matrix on that frame\n"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {
- "pycharm": {
- "name": "#%% md\n"
- }
- },
- "source": [
- "install requirements to Python kernel (I think a 'kernel' is roughly equivalent to a conda environment, i.e. telling the system which version of `python.exe` you want to use to evaluate this Python code )"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 1,
- "metadata": {
- "pycharm": {
- "name": "#%%\n"
- }
- },
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "Requirement already satisfied: numpy in c:\\users\\jonma\\miniconda3\\envs\\humon-env\\lib\\site-packages (1.22.3)\n",
- "Requirement already satisfied: matplotlib in c:\\users\\jonma\\miniconda3\\envs\\humon-env\\lib\\site-packages (3.5.1)\n",
- "Requirement already satisfied: cycler>=0.10 in c:\\users\\jonma\\miniconda3\\envs\\humon-env\\lib\\site-packages (from matplotlib) (0.11.0)\n",
- "Requirement already satisfied: pyparsing>=2.2.1 in c:\\users\\jonma\\miniconda3\\envs\\humon-env\\lib\\site-packages (from matplotlib) (3.0.8)\n",
- "Requirement already satisfied: numpy>=1.17 in c:\\users\\jonma\\miniconda3\\envs\\humon-env\\lib\\site-packages (from matplotlib) (1.22.3)\n",
- "Requirement already satisfied: fonttools>=4.22.0 in c:\\users\\jonma\\miniconda3\\envs\\humon-env\\lib\\site-packages (from matplotlib) (4.33.2)\n",
- "Requirement already satisfied: pillow>=6.2.0 in c:\\users\\jonma\\miniconda3\\envs\\humon-env\\lib\\site-packages (from matplotlib) (9.1.0)\n",
- "Requirement already satisfied: packaging>=20.0 in c:\\users\\jonma\\miniconda3\\envs\\humon-env\\lib\\site-packages (from matplotlib) (21.3)\n",
- "Requirement already satisfied: kiwisolver>=1.0.1 in c:\\users\\jonma\\miniconda3\\envs\\humon-env\\lib\\site-packages (from matplotlib) (1.4.2)\n",
- "Requirement already satisfied: python-dateutil>=2.7 in c:\\users\\jonma\\miniconda3\\envs\\humon-env\\lib\\site-packages (from matplotlib) (2.8.2)\n",
- "Requirement already satisfied: six>=1.5 in c:\\users\\jonma\\miniconda3\\envs\\humon-env\\lib\\site-packages (from python-dateutil>=2.7->matplotlib) (1.16.0)\n",
- "Requirement already satisfied: pyqt5 in c:\\users\\jonma\\miniconda3\\envs\\humon-env\\lib\\site-packages (5.15.6)\n",
- "Requirement already satisfied: PyQt5-Qt5>=5.15.2 in c:\\users\\jonma\\miniconda3\\envs\\humon-env\\lib\\site-packages (from pyqt5) (5.15.2)\n",
- "Requirement already satisfied: PyQt5-sip<13,>=12.8 in c:\\users\\jonma\\miniconda3\\envs\\humon-env\\lib\\site-packages (from pyqt5) (12.10.1)\n",
- "Requirement already satisfied: keyboard in c:\\users\\jonma\\miniconda3\\envs\\humon-env\\lib\\site-packages (0.13.5)\n"
- ]
- }
- ],
- "source": [
- "#I should specify the versions to ensure future stability\n",
- "!pip install numpy\n",
- "!pip install matplotlib\n",
- "!pip install pyqt5\n",
- "!pip install keyboard"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 2,
- "metadata": {
- "pycharm": {
- "name": "#%%\n"
- }
- },
- "outputs": [],
- "source": [
- "\n",
- "import numpy as np\n",
- "from pathlib import Path\n",
- "\n",
- "import matplotlib.pyplot as plt\n",
- "import keyboard"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 3,
- "metadata": {
- "pycharm": {
- "name": "#%%\n"
- }
- },
- "outputs": [],
- "source": [
- "debug = True\n",
- "# %matplotlib widget\n",
- "import matplotlib.pyplot as plt\n",
- "# %matplotlib widget\n",
- "\n",
- "%matplotlib qt \n",
- "#pops out a window for matplot lib plots. It'd be cool to figure out how to play animations inline"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 4,
- "metadata": {
- "pycharm": {
- "name": "#%%\n"
- }
- },
- "outputs": [],
- "source": [
- "\n",
- "### get yr paths right\n",
- "session_id = 'sesh_2022-02-15_11_54_28_pupil_maybe'\n",
- "\n",
- "freemocap_data_folder = Path('C:/Users/jonma/Dropbox/FreeMoCapProject/FreeMocap_Data')\n",
- "\n",
- "session_folder_path = freemocap_data_folder / session_id\n",
- "\n",
- "data_arrays_path = session_folder_path / 'DataArrays'\n",
- "\n",
- "mediapipe_skeleton_data_path = data_arrays_path / 'mediaPipeSkel_3d_smoothed.npy'"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {
- "pycharm": {
- "name": "#%% md\n"
- }
- },
- "source": [
- "\n",
- " ### load in data\n",
- "\n",
- "- full body 3d kinematic data - `mediapipe_skeleton_frame_mar_xyz`\n",
- " - type: numpy array\n",
- " - dimensions: [frame_number, tracked_point_number, dimension (xyz)]\n",
- "\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 5,
- "metadata": {
- "pycharm": {
- "name": "#%%\n"
- }
- },
- "outputs": [],
- "source": [
- "mediapipe_skeleton_fr_mar_xyz = np.load(mediapipe_skeleton_data_path)"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 6,
- "metadata": {
- "pycharm": {
- "name": "#%%\n"
- }
- },
- "outputs": [],
- "source": [
- "nose_id= 0\n",
- "right_ear_id = 8\n",
- "left_ear_id = 7\n",
- "\n",
- "nose_xyz = mediapipe_skeleton_fr_mar_xyz[:, nose_id, :]\n",
- "right_ear_xyz = mediapipe_skeleton_fr_mar_xyz[:, right_ear_id, :]\n",
- "left_ear_xyz = mediapipe_skeleton_fr_mar_xyz[:, left_ear_id, :]\n",
- "\n",
- "head_center_xyz = (right_ear_xyz + left_ear_xyz) / 2 "
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 7,
- "metadata": {
- "pycharm": {
- "name": "#%%\n"
- }
- },
- "outputs": [],
- "source": [
- "fig = plt.figure(num=123)\n",
- "ax = fig.add_subplot(111)\n",
- "ax.plot(nose_xyz[:,0], label='nose_x')\n",
- "ax.plot(nose_xyz[:,1], label='nose_y')\n",
- "ax.plot(nose_xyz[:,2], label='nose_z')\n",
- "ax.plot(right_ear_xyz[:,0], label='right_ear_x')\n",
- "ax.plot(right_ear_xyz[:,1], label='right_ear_y')\n",
- "ax.plot(right_ear_xyz[:,2], label='right_ear_z')\n",
- "ax.plot(left_ear_xyz[:,0], label='left_ear_x')\n",
- "ax.plot(left_ear_xyz[:,1], label='left_ear_y')\n",
- "ax.plot(left_ear_xyz[:,2], label='left_ear_z')\n",
- "ax.plot(head_center_xyz[:,0], label='head_center_x')\n",
- "ax.plot(head_center_xyz[:,1], label='head_center_y')\n",
- "ax.plot(head_center_xyz[:,2], label='head_center_z')\n",
- "ax.legend()\n",
- "plt.show()\n",
- "plt.pause(.1)"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {
- "pycharm": {
- "name": "#%% md\n"
- }
- },
- "source": [
- "zero everything out, aka pin it to the origin, aka \"subtract the position of the thing you want to be the origin from everything else\", aka \"do the thing that makes the X,Y,Z coordinates of the thing that should be (0,0,0) equal to (0,0,0)\""
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 8,
- "metadata": {
- "pycharm": {
- "name": "#%%\n"
- }
- },
- "outputs": [
- {
- "data": {
- "text/plain": [
- "array([[ nan, nan, nan],\n",
- " [ nan, nan, nan],\n",
- " [ nan, nan, nan],\n",
- " ...,\n",
- " [ 12.47374782, 69.0853272 , -22.37502357],\n",
- " [ 14.10629544, 60.84139366, -6.04679083],\n",
- " [ 25.76475466, 63.75538109, -21.2651289 ]])"
- ]
- },
- "execution_count": 8,
- "metadata": {},
- "output_type": "execute_result"
- }
- ],
- "source": [
- "z_nose_xyz = nose_xyz - head_center_xyz\n",
- "z_nose_x = z_nose_xyz[:,0]\n",
- "z_nose_y = z_nose_xyz[:,1]\n",
- "z_nose_z = z_nose_xyz[:,2]\n",
- "\n",
- "z_left_ear_xyz = left_ear_xyz - head_center_xyz\n",
- "z_left_ear_x = z_left_ear_xyz[:,0]\n",
- "z_left_ear_y = z_left_ear_xyz[:,1]\n",
- "z_left_ear_z = z_left_ear_xyz[:,2]\n",
- "\n",
- "z_nose_xyz"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {
- "pycharm": {
- "name": "#%% md\n"
- }
- },
- "source": [
- "Normalize so they are unit vectors"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 9,
- "metadata": {
- "pycharm": {
- "name": "#%%\n"
- }
- },
- "outputs": [],
- "source": [
- "z_norm_nose_xyz = z_nose_xyz / np.linalg.norm(z_nose_xyz, axis=1)[:,None]\n",
- "z_norm_nose_x = z_norm_nose_xyz[:,0]\n",
- "z_norm_nose_y = z_norm_nose_xyz[:,1]\n",
- "z_norm_nose_z = z_norm_nose_xyz[:,2]\n",
- "\n",
- "z_norm_left_ear_xyz = z_left_ear_xyz / np.linalg.norm(z_left_ear_xyz, axis=1)[:,None]\n",
- "z_norm_left_ear_x = z_norm_left_ear_xyz[:,0]\n",
- "z_norm_left_ear_y = z_norm_left_ear_xyz[:,1]\n",
- "z_norm_left_ear_z = z_norm_left_ear_xyz[:,2]"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {
- "pycharm": {
- "name": "#%% md\n"
- }
- },
- "source": [
- "define x_hat as the zero'd out nose vector (i.e. the +X axis of the head starts at the head center and goes out the person's nose)"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 10,
- "metadata": {
- "pycharm": {
- "name": "#%%\n"
- }
- },
- "outputs": [
- {
- "data": {
- "text/plain": [
- "array([[ nan, nan, nan],\n",
- " [ nan, nan, nan],\n",
- " [ nan, nan, nan],\n",
- " ...,\n",
- " [ 0.16929195, 0.93761632, -0.30367067],\n",
- " [ 0.22481111, 0.96962534, -0.09636731],\n",
- " [ 0.35795511, 0.8857668 , -0.29544087]])"
- ]
- },
- "execution_count": 10,
- "metadata": {},
- "output_type": "execute_result"
- }
- ],
- "source": [
- "x_hat_xyz = z_norm_nose_xyz\n",
- "x_hat_x = x_hat_xyz[:,0]\n",
- "x_hat_y = x_hat_xyz[:,1]\n",
- "x_hat_z = x_hat_xyz[:,2]\n",
- "\n",
- "x_hat_xyz"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {
- "pycharm": {
- "name": "#%% md\n"
- }
- },
- "source": [
- "define z as x cross y"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 11,
- "metadata": {
- "pycharm": {
- "name": "#%%\n"
- }
- },
- "outputs": [
- {
- "data": {
- "text/plain": [
- "array([[ nan, nan, nan],\n",
- " [ nan, nan, nan],\n",
- " [ nan, nan, nan],\n",
- " ...,\n",
- " [ 0.07844496, -0.31995954, -0.9441781 ],\n",
- " [ 0.23993877, -0.15094018, -0.95898199],\n",
- " [ 0.15626882, -0.36877272, -0.91628966]])"
- ]
- },
- "execution_count": 11,
- "metadata": {},
- "output_type": "execute_result"
- }
- ],
- "source": [
- "z_hat_xyz = np.cross(x_hat_xyz, z_norm_left_ear_xyz) #create `z_hat` a vector perpendicular to `x_hat` and the vector from the nose to the left ear(i.e. pseudo y_hat)\n",
- "z_hat_xyz = z_hat_xyz / np.linalg.norm(z_hat_xyz, axis=1)[:,None] #not sure if this needs normalizing, but it couldn't hurt\n",
- "z_hat_x = z_hat_xyz[:,0]\n",
- "z_hat_y = z_hat_xyz[:,1]\n",
- "z_hat_z = z_hat_xyz[:,2]\n",
- "\n",
- "z_hat_xyz"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {
- "pycharm": {
- "name": "#%% md\n"
- }
- },
- "source": [
- "define y_hat as z_hat cross with x_hat (this ensures that they are all orthogonal, where as the original vector to the left ear might not have been )"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 12,
- "metadata": {
- "pycharm": {
- "name": "#%%\n"
- }
- },
- "outputs": [
- {
- "data": {
- "text/plain": [
- "array([[ nan, nan, nan],\n",
- " [ nan, nan, nan],\n",
- " [ nan, nan, nan],\n",
- " ...,\n",
- " [ 0.98243912, -0.13602032, 0.12771785],\n",
- " [ 0.94439894, -0.19246755, 0.26658374],\n",
- " [ 0.9205695 , -0.28182237, 0.27042181]])"
- ]
- },
- "execution_count": 12,
- "metadata": {},
- "output_type": "execute_result"
- }
- ],
- "source": [
- "y_hat_xyz = np.cross(z_hat_xyz, z_norm_nose_xyz)\n",
- "y_hat_xyz = y_hat_xyz / np.linalg.norm(y_hat_xyz, axis=1)[:,None] #not sure if this needs normalizing, but it couldn't hurt\n",
- "y_hat_x = y_hat_xyz[:,0]\n",
- "y_hat_y = y_hat_xyz[:,1]\n",
- "y_hat_z = y_hat_xyz[:,2]\n",
- "\n",
- "y_hat_xyz"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {
- "pycharm": {
- "name": "#%% md\n"
- }
- },
- "source": [
- "create head rotation matricies by stacking x_hat_xyz, y_hat_xyz, and z_hat_xyz"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 13,
- "metadata": {
- "pycharm": {
- "name": "#%%\n"
- }
- },
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "4916\n",
- "[[[nan nan nan]\n",
- " [nan nan nan]\n",
- " [nan nan nan]]]\n"
- ]
- }
- ],
- "source": [
- "head_rotation_matricies = [np.dstack((this_x_hat_xyz, this_y_hat_xyz, this_z_hat_xyz))\n",
- " for this_x_hat_xyz, this_y_hat_xyz, this_z_hat_xyz in zip(x_hat_xyz, y_hat_xyz, z_hat_xyz)]\n",
- "\n",
- "print(len(head_rotation_matricies))\n",
- "print(head_rotation_matricies[0])"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {
- "pycharm": {
- "name": "#%% md\n"
- }
- },
- "source": [
- "make a point in head space and rotate it with the head rotation matricies, as a test of these strange mathemagics"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 14,
- "metadata": {
- "pycharm": {
- "name": "#%%\n"
- }
- },
- "outputs": [
- {
- "data": {
- "text/plain": [
- "array([[ nan, nan, nan],\n",
- " [ nan, nan, nan],\n",
- " [ nan, nan, nan],\n",
- " ...,\n",
- " [ 1.23017602, 0.48163646, -1.12013092],\n",
- " [ 1.40914882, 0.62621761, -0.78876556],\n",
- " [ 1.43479342, 0.23517171, -0.94130872]])"
- ]
- },
- "execution_count": 14,
- "metadata": {},
- "output_type": "execute_result"
- }
- ],
- "source": [
- "test_point_xyz_og = np.array((1,1,1))\n",
- "test_point_xyz_rot = np.empty(z_hat_xyz.shape)\n",
- "\n",
- "\n",
- "for frame_number in range(len(head_rotation_matricies)):\n",
- " test_point_xyz_rot[frame_number,:] = head_rotation_matricies[frame_number] @ test_point_xyz_og\n",
- "\n",
- "\n",
- "test_point_xyz_rot"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {
- "pycharm": {
- "name": "#%% md\n"
- }
- },
- "source": [
- "Visualize results! Press ESC to quit"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 15,
- "metadata": {
- "pycharm": {
- "name": "#%%\n"
- }
- },
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "You Pressed Escape!\n"
- ]
- }
- ],
- "source": [
- "if debug:\n",
- " plt.close('all')\n",
- " fig = plt.figure(num=124)\n",
- " fig.suptitle('Press ESC to Quit')\n",
- " ax = fig.add_subplot(111, projection='3d')\n",
- "\n",
- " ax_range = 2\n",
- "\n",
- "\n",
- " for frame_number in range(1200, z_nose_y.shape[0]):\n",
- " ax.clear()\n",
- "\n",
- "\n",
- " #plot head orthonormal basis vectors\n",
- " ax.plot(x_hat_x[frame_number-30:frame_number],\n",
- " x_hat_y[frame_number-30:frame_number],\n",
- " x_hat_z[frame_number-30:frame_number], 'r-')\n",
- "\n",
- " ax.plot(y_hat_x[frame_number-30:frame_number],\n",
- " y_hat_y[frame_number-30:frame_number],\n",
- " y_hat_z[frame_number-30:frame_number], 'g-')\n",
- "\n",
- " ax.plot(z_hat_x[frame_number-30:frame_number],\n",
- " z_hat_y[frame_number-30:frame_number],\n",
- " z_hat_z[frame_number-30:frame_number], 'b-')\n",
- " \n",
- " ax.plot([0, x_hat_x[frame_number]],\n",
- " [0, x_hat_y[frame_number]], \n",
- " [0, x_hat_z[frame_number]], 'r-o',label='x_hat')\n",
- "\n",
- " ax.plot([0, y_hat_x[frame_number]],\n",
- " [0, y_hat_y[frame_number]],\n",
- " [0, y_hat_z[frame_number]], 'g-o',label='y_hat')\n",
- " \n",
- " ax.plot([0, z_hat_x[frame_number]],\n",
- " [0, z_hat_y[frame_number]],\n",
- " [0, z_hat_z[frame_number]], 'b-o',label='z_hat')\n",
- " # original nose and ear directions (ear should be slightly diff from y_hat)]\\\n",
- " ax.plot([0, z_nose_x[frame_number]],\n",
- " [0, z_nose_y[frame_number]], \n",
- " [0, z_nose_z[frame_number]], 'r:o',label='z_nose')\n",
- "\n",
- " ax.plot([0, z_left_ear_x[frame_number]],\n",
- " [0, z_left_ear_y[frame_number]],\n",
- " [0, z_left_ear_z[frame_number]], 'g:o',label='z_left_ear')\n",
- "\n",
- " # plot test point rotated with head rotation matricies\n",
- "\n",
- " ax.plot(test_point_xyz_rot[frame_number-30:frame_number, 0],\n",
- " test_point_xyz_rot[frame_number-30:frame_number, 1],\n",
- " test_point_xyz_rot[frame_number-30:frame_number, 2], 'k-')\n",
- " \n",
- " ax.plot([0, test_point_xyz_rot[frame_number,0]],\n",
- " [0, test_point_xyz_rot[frame_number,1]],\n",
- " [0, test_point_xyz_rot[frame_number,2]], 'k-o',label='test point')\n",
- "\n",
- "\n",
- "\n",
- "\n",
- " ax.set_xlim([-ax_range, ax_range])\n",
- " ax.set_ylim([-ax_range, ax_range])\n",
- " ax.set_zlim([-ax_range, ax_range])\n",
- " ax.legend()\n",
- " plt.pause(.01)\n",
- " if keyboard.is_pressed('esc'): \n",
- " print('You Pressed Escape!')\n",
- " break # finishing the loop\n",
- "\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 16,
- "metadata": {
- "pycharm": {
- "name": "#%%\n"
- }
- },
- "outputs": [
- {
- "data": {
- "text/plain": [
- "(4916, 3, 3)"
- ]
- },
- "execution_count": 16,
- "metadata": {},
- "output_type": "execute_result"
- }
- ],
- "source": [
- "head_rotation_matricies_fr_row_col = np.squeeze(np.asarray(head_rotation_matricies)) #convert list to array and give a friendly squeeze to pop the extra 'singleton' dimension\n",
- "head_rotation_matricies_fr_row_col.shape"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 17,
- "metadata": {
- "pycharm": {
- "name": "#%%\n"
- }
- },
- "outputs": [],
- "source": [
- "save_head_rot_path = data_arrays_path / 'mediaPipeSkel_3d_head_rotation_matricies_fr_row_col.npy'\n",
- "np.save(save_head_rot_path, head_rotation_matricies_fr_row_col)"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {
- "pycharm": {
- "name": "#%%\n"
- }
- },
- "outputs": [],
- "source": []
- }
- ],
- "metadata": {
- "interpreter": {
- "hash": "4ef2e72e5b895021b427c707c9f05b4880b5a5a00e886b84de197a42e54c7f32"
- },
- "kernelspec": {
- "display_name": "Python 3.9.12 ('humon-env')",
- "language": "python",
- "name": "python3"
- },
- "language_info": {
- "codemirror_mode": {
- "name": "ipython",
- "version": 3
- },
- "file_extension": ".py",
- "mimetype": "text/x-python",
- "name": "python",
- "nbconvert_exporter": "python",
- "pygments_lexer": "ipython3",
- "version": "3.9.12"
- },
- "orig_nbformat": 4
- },
- "nbformat": 4,
- "nbformat_minor": 2
-}
diff --git a/jon_scratch/create_retina_centered_video_from_pupil_labs_data.ipynb b/jon_scratch/create_retina_centered_video_from_pupil_labs_data.ipynb
deleted file mode 100644
index 6753d12e..00000000
--- a/jon_scratch/create_retina_centered_video_from_pupil_labs_data.ipynb
+++ /dev/null
@@ -1,618 +0,0 @@
-{
- "cells": [
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "# a notebook to make a quick and dirty retina centered video from standard Pupil Player export video\n",
- "\n",
- "It'll make one retina centered video from a standard Pupil Payer export video\n",
- "\n",
- "and also a video of the gaze trace\n",
- "\n",
- "I'll put them together in Adobe Premier or, via this script. We'll see lol"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "import cv2\n",
- "from pathlib import Path\n",
- "import matplotlib.pyplot as plt\n",
- "import pandas as pd\n",
- "import numpy as np\n",
- "from PIL import Image\n",
- "from scipy import signal\n",
- "from scipy.signal import savgol_filter\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "# !pip install pyqt5\n",
- "%matplotlib qt"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "Getcher paths straight"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "#freemocap session\n",
- "session_id = 'sesh_2022-05-07_17_15_05_pupil_wobble_juggle_0'\n",
- "freemocap_data_folder = Path('C:/Users/jonma/Dropbox/FreeMoCapProject/FreeMocap_Data')\n",
- "session_folder_path = freemocap_data_folder / session_id\n",
- "pupil_data_path = session_folder_path / 'pupil_000'\n",
- "pupil_data_exports_path = pupil_data_path / 'exports' / '000'\n",
- "pupil_export_video_path = pupil_data_exports_path / 'world.mp4'\n",
- "pupil_world_video_path = pupil_data_path / 'world.mp4'\n",
- "\n",
- "# #argp pilot_0\n",
- "# pupil_data_path = Path(r'H:\\Other computers\\My Computer_MocapComputer\\Wirth_ARGP\\ARGP_Main\\data\\2022_04_29\\pupil_data')\n",
- "# pupil_data_exports_path = pupil_data_path / 'exports' / 'Wirth_Pilot_ARGP_2022-04-09_export'\n",
- "# pupil_export_video_path = pupil_data_exports_path / 'argp_pilot_May2022.mp4'\n",
- "\n",
- "\n",
- "pupil_world_video_path = pupil_data_path / 'world.mp4'\n",
- "\n",
- "\n",
- "gaze_positions_path = pupil_data_exports_path / 'gaze_positions.csv'\n",
- "\n"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "load stuff "
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "#open cv video capture object\n",
- "pupil_export_video_cap_object = cv2.VideoCapture(str(pupil_export_video_path))\n",
- "\n",
- "#pupil labs - gaze data\n",
- "pupil_dataframe = pd.read_csv(gaze_positions_path)"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "get some info from the video cap"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "video_width = int(pupil_export_video_cap_object.get(cv2.CAP_PROP_FRAME_WIDTH))\n",
- "video_height = int(pupil_export_video_cap_object.get(cv2.CAP_PROP_FRAME_HEIGHT))\n",
- "video_framerate = int(pupil_export_video_cap_object.get(cv2.CAP_PROP_FPS))\n",
- "print(f'video_width : {video_width }')\n",
- "print(f'video_height: {video_height}')\n",
- "print(f'video_framerate: {video_framerate}')\n"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "gaze locations"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "norm_pos_x = pupil_dataframe.norm_pos_x\n",
- "norm_pos_y = pupil_dataframe.norm_pos_y\n",
- "\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "# fig = plt.Figure(123)\n",
- "# fig.plot(norm_pos_x, label = 'norm_pos_x')\n",
- "# fig.plot(norm_pos_y, label ='norm_pos_x')"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "\n",
- "gaze_on_screen_x = norm_pos_x * video_width\n",
- "gaze_on_screen_y = norm_pos_y * video_height\n",
- "\n",
- "world_camera_frame_index_all = pupil_dataframe.world_index"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "zero-lag 4th order butterworth filter with a 7Hz cutoff"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "\n",
- "\n",
- "order = 5\n",
- "cutoff=10**-1\n",
- "b, a = signal.butter(order, cutoff)\n",
- "gaze_on_screen_x_filtered = signal.filtfilt(b, a, gaze_on_screen_x)\n",
- "gaze_on_screen_y_filtered = signal.filtfilt(b, a, gaze_on_screen_y)\n",
- "\n",
- "print(f\"nans in gaze_on_screen_x: {np.isnan(gaze_on_screen_x).sum()}\")\n",
- "print(f\"nans in gaze_on_screen_y: {np.isnan(gaze_on_screen_y).sum()}\")\n",
- "print(f\"nans in gaze_on_screen_x_filtered: {np.isnan(gaze_on_screen_x_filtered).sum()}\")\n",
- "print(f\"nans in gaze_on_screen_y_filtered: {np.isnan(gaze_on_screen_y_filtered).sum()}\")\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "gaze_on_screen_x_filtered"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "\n",
- "plt.cla()\n",
- "fig2 = plt.Figure()\n",
- "ax = plt.gca()\n",
- "ax.plot(gaze_on_screen_x, label = 'gaze_on_screen_x_raw')\n",
- "ax.plot(gaze_on_screen_y, label = 'gaze_on_screen_y_raw')\n",
- "ax.plot(gaze_on_screen_x_filtered, label = 'gaze_on_screen_x_filtered')\n",
- "ax.plot(gaze_on_screen_y_filtered, label = 'gaze_on_screen_y_filtered')\n",
- "ax.set_ylim((0-100, video_width+100))\n",
- "ax.legend()\n"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "squash data down so each frame is the average of all data recorded on that frame"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "number_of_frames = np.max(world_camera_frame_index_all)\n",
- "number_of_frames\n",
- "\n",
- "gaze_on_screen_x_downsampled = []\n",
- "gaze_on_screen_y_downsampled = []\n",
- "\n",
- "for this_world_frame_index in range(number_of_frames):\n",
- " this_frame_data = world_camera_frame_index_all == this_world_frame_index\n",
- " this_frame_x_data = gaze_on_screen_x_filtered[this_frame_data]\n",
- " this_frame_y_data = gaze_on_screen_y_filtered[this_frame_data]\n",
- " gaze_on_screen_x_downsampled.append(np.nanmedian(this_frame_x_data))\n",
- " gaze_on_screen_y_downsampled.append(np.nanmedian(this_frame_y_data))"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "\n",
- "print(f\"nans in gaze_on_screen_x: {np.isnan(gaze_on_screen_x).sum()}\")\n",
- "print(f\"nans in gaze_on_screen_y: {np.isnan(gaze_on_screen_y).sum()}\")\n",
- "print(f\"nans in gaze_on_screen_x_filtered: {np.isnan(gaze_on_screen_x_filtered).sum()}\")\n",
- "print(f\"nans in gaze_on_screen_y_filtered: {np.isnan(gaze_on_screen_y_filtered).sum()}\")\n",
- "print(f\"nans in gaze_on_screen_x_downsampled: {np.isnan(gaze_on_screen_x_downsampled).sum()}\")\n",
- "print(f\"nans in gaze_on_screen_y_downsampled: {np.isnan(gaze_on_screen_y_downsampled).sum()}\")\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "\n",
- "# order = 4\n",
- "# cutoff=10**-1\n",
- "# b, a = signal.butter(order, cutoff)\n",
- "# gaze_on_screen_x_filtered = signal.filtfilt(b, a, gaze_on_screen_x_downsampled)\n",
- "# gaze_on_screen_y_filtered = signal.filtfilt(b, a, gaze_on_screen_y_downsampled)\n",
- "\n",
- "print(f\"nans in gaze_on_screen_x: {np.isnan(gaze_on_screen_x).sum()}\")\n",
- "print(f\"nans in gaze_on_screen_y: {np.isnan(gaze_on_screen_y).sum()}\")\n",
- "print(f\"nans in gaze_on_screen_x_filtered: {np.isnan(gaze_on_screen_x_filtered).sum()}\")\n",
- "print(f\"nans in gaze_on_screen_y_filtered: {np.isnan(gaze_on_screen_y_filtered).sum()}\")\n",
- "\n",
- "# plt.close('all')\n",
- "# fig2 = plt.Figure()\n",
- "# ax = plt.gca()\n",
- "# # ax.plot(gaze_on_screen_x_downsampled, label = 'gaze_on_screen_x_downsampled')\n",
- "# # ax.plot(gaze_on_screen_y_downsampled, label = 'gaze_on_screen_y_downsampled')\n",
- "# ax.plot(gaze_on_screen_x_filtered, label = 'gaze_on_screen_x_filtered')\n",
- "# ax.plot(gaze_on_screen_y_filtered, label = 'gaze_on_screen_y_filtered')\n",
- "# ax.set_ylim((0-100, video_width+100))\n",
- "# ax.legend()\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "\n",
- "#smoooooooooth, just a bit\n",
- "smoothWinLength = 5\n",
- "smoothOrder = 3\n",
- "\n",
- "gaze_on_screen_x_downsampled_smoothed = savgol_filter(gaze_on_screen_x_downsampled, smoothWinLength, smoothOrder)\n",
- "gaze_on_screen_y_downsampled_smoothed = savgol_filter(gaze_on_screen_y_downsampled, smoothWinLength, smoothOrder)"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "print(f\"nans in gaze_on_screen_x_downsampled: {np.isnan(gaze_on_screen_x_downsampled).sum()}\")\n",
- "print(f\"nans in gaze_on_screen_y_downsampled: {np.isnan(gaze_on_screen_y_downsampled).sum()}\")\n",
- "\n",
- "gaze_x_df = pd.DataFrame(gaze_on_screen_x_downsampled)\n",
- "gaze_x_df.interpolate(method = 'linear', inplace = True)\n",
- "gaze_on_screen_x_downsampled_gapfilled = gaze_x_df.to_numpy()\n",
- "\n",
- "gaze_y_df = pd.DataFrame(gaze_on_screen_y_downsampled)\n",
- "gaze_y_df.interpolate(method = 'linear', inplace = True)\n",
- "gaze_on_screen_y_downsampled_gapfilled = gaze_y_df.to_numpy()\n",
- "\n",
- "print(f\"nans in gaze_on_screen_x_downsampled_gapfilled: {np.isnan(gaze_on_screen_x_downsampled_gapfilled).sum()}\")\n",
- "print(f\"nans in gaze_on_screen_y_downsampled_gapfilled: {np.isnan(gaze_on_screen_y_downsampled_gapfilled).sum()}\")"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "plt.close(\"all\")\n",
- "fig2 = plt.Figure()\n",
- "ax = plt.gca()\n",
- "ax.plot(gaze_on_screen_x_downsampled, '.-', label = 'gaze_on_screen_x_downsampled')\n",
- "ax.plot(gaze_on_screen_y_downsampled, '.-',label = 'gaze_on_screen_y_downsampled')\n",
- "ax.plot(gaze_on_screen_x_downsampled_smoothed, '.-', label = 'gaze_on_screen_x_downsampled_smoothed')\n",
- "ax.plot(gaze_on_screen_y_downsampled_smoothed, '.-',label = 'gaze_on_screen_y_downsampled_smoothed')\n",
- "ax.plot(gaze_on_screen_x_downsampled_gapfilled, '.-', label = 'gaze_on_screen_x_downsampled_gapfilled')\n",
- "ax.plot(gaze_on_screen_y_downsampled_gapfilled, '.-',label = 'gaze_on_screen_y_downsampled_gapfilled')\n",
- "\n",
- "ax.set_ylim((0-100, video_width+100))\n",
- "ax.legend(loc='upper left')\n",
- "\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "\n",
- "\n",
- "\n",
- "big_blank_image = np.ones((int(video_height)*2, int(video_width)*2, 3), dtype=np.uint8)\n",
- "\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "# pupil_world_video_cap_object = cv2.VideoCapture(str(pupil_world_video_path))\n",
- "\n",
- "# frame_num = 0\n",
- "# success = True\n",
- "# while success: \n",
- "# success, image_raw = pupil_world_video_cap_object.read()\n",
- "# if not success:\n",
- "# break\n",
- "# frame_num += 1\n",
- "# print(f\"frame_num: {frame_num}\")"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "create circular mask\n",
- "\n",
- "from =- https://stackoverflow.com/questions/61516526/how-to-use-opencv-to-crop-circular-image"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "#define circles\n",
- "radius = video_height #pixels\n",
- "x_center = video_width\n",
- "y_center = video_height\n",
- "\n",
- "# draw filled circles in white on black background as masks\n",
- "circular_mask = np.zeros_like(big_blank_image)\n",
- "circular_mask = cv2.circle(circular_mask, (x_center,y_center), radius, (255,255,255), -1)\n",
- "\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "video_framerate"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "retinal_video_save_path = pupil_data_exports_path / 'retinal_aligned_video.mp4'\n",
- "\n",
- "make_retinal_video = False\n",
- "if make_retinal_video:\n",
- " pupil_world_video_cap_object = cv2.VideoCapture(str(pupil_world_video_path))\n",
- "\n",
- " this_retinal_aligned_image = big_blank_image.copy()\n",
- " this_retinal_aligned_image[:, video_width-video_height:(video_width-video_height)+2*video_height,:]\n",
- "\n",
- " retinal_video_writer = cv2.VideoWriter(str(retinal_video_save_path),\n",
- " cv2.VideoWriter_fourcc(*\"MP4V\"),\n",
- " video_framerate, \n",
- " (this_retinal_aligned_image.shape[0], this_retinal_aligned_image.shape[0]))\n",
- "\n",
- " success = True\n",
- " for frame_number in range(gaze_on_screen_x_downsampled_gapfilled.shape[0]):\n",
- " success, image= pupil_world_video_cap_object.read()\n",
- " if not success:\n",
- " print('failed to read frame')\n",
- " break\n",
- "\n",
- " # image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)\n",
- " this_retinal_aligned_image = big_blank_image.copy()\n",
- "\n",
- " #pull out gaze data to align image to retinal coordinates\n",
- " gx = int(gaze_on_screen_x_downsampled_gapfilled[frame_number])\n",
- " gy = int(gaze_on_screen_y_downsampled_gapfilled[frame_number])\n",
- "\n",
- " bottom_edge_row = int(video_height)*2-(int(video_height)-gy)\n",
- " top_edge_row = int(video_height) -(int(video_height)-gy)\n",
- " left_col = (int(video_width)-gx)\n",
- " right_col = int(video_width)+(int(video_width)-gx)\n",
- "\n",
- " cols = np.arange(top_edge_row,bottom_edge_row)\n",
- "\n",
- " #if things are going off screen, use whatever gaze data worked most recently\n",
- " if top_edge_row < 0:\n",
- " gy = previous_gy\n",
- " top_edge_row = int(video_height) -(int(video_height)-gy)\n",
- " bottom_edge_row = int(video_height)*2-(int(video_height)-gy)\n",
- "\n",
- " if bottom_edge_row > int(video_height)*2:\n",
- " gy = previous_gy\n",
- " top_edge_row = int(video_height) -(int(video_height)-gy)\n",
- " bottom_edge_row = int(video_height)*2-(int(video_height)-gy)\n",
- " \n",
- " if left_col < 0:\n",
- " gx = previous_gx\n",
- " right_col = int(video_width)+(int(video_width)-gx)\n",
- " left_col = (int(video_width)-gx)\n",
- " \n",
- " if right_col > int(video_width)*2:\n",
- " gx = previous_gx\n",
- " right_col = int(video_width)+(int(video_width)-gx)\n",
- " left_col = (int(video_width)-gx)\n",
- "\n",
- " previous_gx = gx \n",
- " previous_gy = gy\n",
- " \n",
- " this_retinal_aligned_image[top_edge_row:bottom_edge_row, left_col:right_col,:] = image\n",
- "\n",
- " this_retinal_aligned_image[circular_mask==0] = 0\n",
- "\n",
- "\n",
- " this_retinal_aligned_image = this_retinal_aligned_image[:, video_width-video_height:(video_width-video_height)+2*video_height,:]\n",
- "\n",
- " this_retinal_aligned_image = cv2.line(this_retinal_aligned_image, \n",
- " (int(video_height), 0), \n",
- " (int(video_height), int(video_height)*2), \n",
- " (0,0,0,255), \n",
- " 5)\n",
- " this_retinal_aligned_image = cv2.line(this_retinal_aligned_image, \n",
- " (0, int(video_height)), \n",
- " (int(video_width)*2, \n",
- " int(video_height)), \n",
- " (0,0,0,255), \n",
- " 5)\n",
- " this_retinal_aligned_image = cv2.line(this_retinal_aligned_image, \n",
- " (int(video_height), 0), \n",
- " (int(video_height), int(video_height)*2), \n",
- " (255,255,255,255), \n",
- " 1,)\n",
- " this_retinal_aligned_image = cv2.line(this_retinal_aligned_image, \n",
- " (0, int(video_height)), \n",
- " (int(video_width)*2, \n",
- " int(video_height)), \n",
- " (255,255,255,255), \n",
- " 1)\n",
- " this_retinal_aligned_image = cv2.circle(this_retinal_aligned_image, \n",
- " (int(video_height), int(video_height)),\n",
- " 20,\n",
- " (0,0,0,255), \n",
- " 5)\n",
- " this_retinal_aligned_image = cv2.circle(this_retinal_aligned_image, \n",
- " (int(video_height), int(video_height)),\n",
- " 20,\n",
- " (255,255,255,255), \n",
- " 1)\n",
- "\n",
- " # plt.cla()\n",
- " # plt.imshow(this_retinal_aligned_image[:,:,:3]) \n",
- " # plt.show()\n",
- " # plt.pause(0.1)\n",
- "\n",
- " retinal_video_writer.write(this_retinal_aligned_image) \n",
- "\n",
- " if frame_number%100 == 0:\n",
- " print(f'frame_number: {frame_number}')\n",
- "\n",
- " retinal_video_writer.release()\n",
- " print('done!')"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "make Pupil Exports + Retinal + Gaze Trace Vid"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 36,
- "metadata": {},
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "frame_number: 1\n"
- ]
- }
- ],
- "source": [
- "plt.close('all')\n",
- "retinal_video_save_path = pupil_data_exports_path / 'retinal_aligned_video.mp4'\n",
- "\n",
- "retinal_vid_cap = cv2.VideoCapture(str(retinal_video_save_path))\n",
- "pupil_export_vid_cap = cv2.VideoCapture(str(pupil_export_video_path))\n",
- "\n",
- "combo_video_save_path = pupil_data_exports_path / 'combo_retinal_world_video.mp4'\n",
- "\n",
- "\n",
- "combo_video_writer = cv2.VideoWriter(str(combo_video_save_path),\n",
- " cv2.VideoWriter_fourcc(*\"MP4V\"),\n",
- " video_framerate, \n",
- " (video_height,2000))\n",
- "\n",
- "pup_success = True\n",
- "ret_success = True\n",
- "frame_number = 0\n",
- "while pup_success and ret_success:\n",
- " frame_number += 1\n",
- " print(f'frame_number: {frame_number}')\n",
- " ret_success, ret_image = retinal_vid_cap.read()\n",
- " if not ret_success:\n",
- " print('ret - failed to read frame')\n",
- " break\n",
- "\n",
- " pup_success, pup_image = pupil_export_vid_cap.read()\n",
- " if not pup_success:\n",
- " print('pup - failed to read frame')\n",
- " break\n",
- " \n",
- " ret_image = cv2.cvtColor(ret_image, cv2.COLOR_BGR2RGB)\n",
- " pup_image = cv2.cvtColor(pup_image, cv2.COLOR_BGR2RGB)\n",
- "\n",
- " shrink_ret_image = cv2.resize(ret_image, (0,0), fx=0.5, fy=0.5)\n",
- " combo_image = np.hstack((shrink_ret_image, pup_image))\n",
- "\n",
- " combo_video_writer.write(combo_image) \n"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": []
- }
- ],
- "metadata": {
- "interpreter": {
- "hash": "122c9931a57dd91c579842728ee2ee1c7ffefd770186c077f442b22e7e57f48e"
- },
- "kernelspec": {
- "display_name": "Python 3.7.13 ('freemocap-env')",
- "language": "python",
- "name": "python3"
- },
- "language_info": {
- "codemirror_mode": {
- "name": "ipython",
- "version": 3
- },
- "file_extension": ".py",
- "mimetype": "text/x-python",
- "name": "python",
- "nbconvert_exporter": "python",
- "pygments_lexer": "ipython3",
- "version": "3.7.13"
- },
- "orig_nbformat": 4
- },
- "nbformat": 4,
- "nbformat_minor": 2
-}
diff --git a/jon_scratch/examine_timestamps.ipynb b/jon_scratch/examine_timestamps.ipynb
deleted file mode 100644
index 82090aaf..00000000
--- a/jon_scratch/examine_timestamps.ipynb
+++ /dev/null
@@ -1,318 +0,0 @@
-{
- "cells": [
- {
- "cell_type": "code",
- "execution_count": 1,
- "metadata": {},
- "outputs": [],
- "source": [
- "import pandas as pd\n",
- "import numpy as np\n",
- "from pathlib import Path\n",
- "from matplotlib import pyplot as plt\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 3,
- "metadata": {},
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- " Unnamed: 0 Camera0 Camera1 Camera2\n",
- "0 0 1.643064e+09 1.643064e+09 1.643064e+09\n",
- "1 1 1.643064e+09 1.643064e+09 1.643064e+09\n",
- "2 2 1.643064e+09 1.643064e+09 1.643064e+09\n",
- "3 3 1.643064e+09 1.643064e+09 1.643064e+09\n",
- "4 4 1.643064e+09 1.643064e+09 1.643064e+09\n",
- ".. ... ... ... ...\n",
- "140 140 1.643064e+09 1.643064e+09 1.643064e+09\n",
- "141 141 1.643064e+09 1.643064e+09 1.643064e+09\n",
- "142 142 1.643064e+09 1.643064e+09 1.643064e+09\n",
- "143 143 1.643064e+09 1.643064e+09 1.643064e+09\n",
- "144 144 1.643064e+09 1.643064e+09 1.643064e+09\n",
- "\n",
- "[145 rows x 4 columns]\n"
- ]
- }
- ],
- "source": [
- "\n",
- "path_to_timestamps = Path('~/timestamps.csv')\n",
- "timestamps_df = pd.read_csv(path_to_timestamps)\n",
- "\n",
- "print(timestamps_df)\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 6,
- "metadata": {},
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- " Unnamed: 0 Camera0 Camera1 Camera2\n",
- "0 0.0 0.000000 0.000000 0.000000\n",
- "1 1.0 0.001001 0.002000 0.187001\n",
- "2 2.0 0.025000 0.031500 0.218002\n",
- "3 3.0 0.057001 0.063001 0.250002\n",
- "4 4.0 0.090501 0.096501 0.282006\n",
- ".. ... ... ... ...\n",
- "140 140.0 4.633425 4.622925 4.826427\n",
- "141 141.0 4.666926 4.671926 4.858427\n",
- "142 142.0 4.697927 4.703427 4.890428\n",
- "143 143.0 4.729926 4.735926 4.922928\n",
- "144 144.0 4.761926 4.767427 4.953428\n",
- "\n",
- "[145 rows x 4 columns]\n"
- ]
- }
- ],
- "source": [
- "min_ts = timestamps_df.min()\n",
- "timestamps_df =timestamps_df - min_ts\n",
- "print(timestamps_df)"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 7,
- "metadata": {},
- "outputs": [],
- "source": [
- "\n",
- "cam0_ts = timestamps_df['Camera0'].to_numpy()\n",
- "cam1_ts = timestamps_df['Camera1'].to_numpy()\n",
- "cam2_ts = timestamps_df['Camera2'].to_numpy()\n",
- "cam0_id_ts = np.vstack([np.zeros(len(cam0_ts)), cam0_ts])\n",
- "cam1_id_ts = np.vstack([np.zeros(len(cam1_ts))+1, cam0_ts])\n",
- "cam2_id_ts = np.vstack([np.zeros(len(cam2_ts))+2, cam0_ts])"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 13,
- "metadata": {},
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- " camID timestamp\n",
- "0 0.0 0.000000\n",
- "1 0.0 0.001001\n",
- "2 0.0 0.025000\n",
- "3 0.0 0.057001\n",
- "4 0.0 0.090501\n",
- ".. ... ...\n",
- "430 2.0 4.633425\n",
- "431 2.0 4.666926\n",
- "432 2.0 4.697927\n",
- "433 2.0 4.729926\n",
- "434 2.0 4.761926\n",
- "\n",
- "[435 rows x 2 columns]\n"
- ]
- }
- ],
- "source": [
- "\n",
- "\n",
- "\n",
- "\n",
- "allTimestamps_id_ts = np.hstack([cam0_id_ts, cam1_id_ts, cam2_id_ts])\n",
- "allTimestamps_df = pd.DataFrame(allTimestamps_id_ts.T, columns=['camID', 'timestamp'])\n",
- "print(allTimestamps_df)"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 14,
- "metadata": {},
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- " camID timestamp\n",
- "0 0.0 0.000000\n",
- "290 2.0 0.000000\n",
- "145 1.0 0.000000\n",
- "1 0.0 0.001001\n",
- "291 2.0 0.001001\n",
- ".. ... ...\n",
- "143 0.0 4.729926\n",
- "288 1.0 4.729926\n",
- "289 1.0 4.761926\n",
- "144 0.0 4.761926\n",
- "434 2.0 4.761926\n",
- "\n",
- "[435 rows x 2 columns]\n"
- ]
- }
- ],
- "source": [
- "allTimestamps_df = allTimestamps_df.sort_values(by=['timestamp'])\n",
- "print(allTimestamps_df)"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 16,
- "metadata": {},
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "Using matplotlib backend: TkAgg\n"
- ]
- }
- ],
- "source": [
- "%matplotlib \n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 17,
- "metadata": {},
- "outputs": [
- {
- "data": {
- "text/plain": [
- "[<matplotlib.lines.Line2D at 0x22b4d05d848>]"
- ]
- },
- "execution_count": 17,
- "metadata": {},
- "output_type": "execute_result"
- }
- ],
- "source": [
- "colors = ['red', 'green', 'blue']\n",
- "figure, ax = plt.subplots()\n",
- "plt.plot(allTimestamps_df['timestamp'], allTimestamps_df['camID'], '-o') \n",
- "\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 30,
- "metadata": {},
- "outputs": [
- {
- "data": {
- "text/html": [
- "<div>\n",
- "<style scoped>\n",
- " .dataframe tbody tr th:only-of-type {\n",
- " vertical-align: middle;\n",
- " }\n",
- "\n",
- " .dataframe tbody tr th {\n",
- " vertical-align: top;\n",
- " }\n",
- "\n",
- " .dataframe thead th {\n",
- " text-align: right;\n",
- " }\n",
- "</style>\n",
- "<table border=\"1\" class=\"dataframe\">\n",
- " <thead>\n",
- " <tr style=\"text-align: right;\">\n",
- " <th></th>\n",
- " <th>camID</th>\n",
- " <th>timestamp</th>\n",
- " </tr>\n",
- " </thead>\n",
- " <tbody>\n",
- " <tr>\n",
- " <th>0</th>\n",
- " <td>0.0</td>\n",
- " <td>0.0</td>\n",
- " </tr>\n",
- " </tbody>\n",
- "</table>\n",
- "</div>"
- ],
- "text/plain": [
- " camID timestamp\n",
- "0 0.0 0.0"
- ]
- },
- "execution_count": 30,
- "metadata": {},
- "output_type": "execute_result"
- }
- ],
- "source": [
- "allTimestamps_df.loc[:0]"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "a = np.random.rand(4,2)\n",
- "b = np.random.rand(4,2)\n",
- "a[:,1] = 1\n",
- "b[:,1] = 2\n",
- "# print(a)\n",
- "# print(b)\n",
- "\n",
- "ab_raw = np.vstack([a,b])\n",
- "\n",
- "# print('ab_raw')\n",
- "# print(ab_raw)\n",
- "\n",
- "ab_raw_df = pd.DataFrame(data=ab_raw, columns=['num', 'id'])\n",
- "\n",
- "print(ab_raw_df)\n",
- "\n",
- "ab_sorted = ab_raw_df.sort_values(by=['num'])\n",
- "print(ab_sorted)\n",
- "# ab = np.sort(ab_raw)\n",
- "# print(ab)"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": []
- }
- ],
- "metadata": {
- "interpreter": {
- "hash": "a27e02b00040eb3222236c12664def6c278394870265aa932cf722c3b1a8ef6b"
- },
- "kernelspec": {
- "display_name": "Python 3.7.11 64-bit ('fmc-env': conda)",
- "language": "python",
- "name": "python3"
- },
- "language_info": {
- "codemirror_mode": {
- "name": "ipython",
- "version": 3
- },
- "file_extension": ".py",
- "mimetype": "text/x-python",
- "name": "python",
- "nbconvert_exporter": "python",
- "pygments_lexer": "ipython3",
- "version": "3.7.11"
- },
- "orig_nbformat": 4
- },
- "nbformat": 4,
- "nbformat_minor": 2
-}
diff --git a/jon_scratch/freemocap_plotly.py b/jon_scratch/freemocap_plotly.py
deleted file mode 100644
index 7cf531e0..00000000
--- a/jon_scratch/freemocap_plotly.py
+++ /dev/null
@@ -1,112 +0,0 @@
-# Import data
-import time
-import numpy as np
-import plotly.graph_objects as go
-from skimage import io
-from pathlib import Path
-## load in freemocap data
-session_id = 'sesh_2022-02-15_11_54_28_pupil_maybe'
-freemocap_data_folder = Path('C:/Users/jonma/Dropbox/FreeMoCapProject/FreeMocap_Data')
-session_folder_path = freemocap_data_folder / session_id
-data_arrays_path = session_folder_path / 'DataArrays'
-mediapipe_skeleton_data_path = data_arrays_path / 'mediaPipeSkel_3d_smoothed.npy'
-mediapipe_skeleton_fr_mar_xyz = np.load(mediapipe_skeleton_data_path)
-
-##
-vol = io.imread("https://s3.amazonaws.com/assets.datacamp.com/blog_assets/attention-mri.tif")
-volume = vol.T
-r, c = volume[0].shape
-
-# Define frames
-number_of_frames = mediapipe_skeleton_fr_mar_xyz.shape[0]
-
-fig = go.Figure(frames=[
- go.Frame(
-
- data=go.Scatter3d(
- x=mediapipe_skeleton_fr_mar_xyz[this_frame_number, :, 0],
- y=mediapipe_skeleton_fr_mar_xyz[this_frame_number, :, 1],
- z=mediapipe_skeleton_fr_mar_xyz[this_frame_number, :, 2],
- mode='markers',
- marker=dict(
- size=12,
- color='red', # set color to an array/list of desired values
- colorscale='Viridis', # choose a colorscale
- opacity=0.8
- )
- ),
-
- name=str(this_frame_number) # you need to name the frame for the animation to behave properly
- )
- for this_frame_number in range(number_of_frames)])
-
-# Add data to be displayed before animation starts
-fig.add_trace(go.Surface(
- z=6.7 * np.ones((r, c)),
- surfacecolor=np.flipud(volume[67]),
- colorscale='Gray',
- cmin=0, cmax=200,
- colorbar=dict(thickness=20, ticklen=4)
-))
-
-
-def frame_args(duration):
- return {
- "frame": {"duration": duration},
- "mode": "immediate",
- "fromcurrent": True,
- "transition": {"duration": duration, "easing": "linear"},
- }
-
-
-sliders = [
- {
- "pad": {"b": 10, "t": 60},
- "len": 0.9,
- "x": 0.1,
- "y": 0,
- "steps": [
- {
- "args": [[f.name], frame_args(0)],
- "label": str(k),
- "method": "animate",
- }
- for k, f in enumerate(fig.frames)
- ],
- }
-]
-
-# Layout
-fig.update_layout(
- title='Slices in volumetric data',
- width=600,
- height=600,
- scene=dict(
- zaxis=dict(range=[-2e3, 2e3], autorange=False),
- aspectratio=dict(x=1, y=1, z=1),
- ),
- updatemenus=[
- {
- "buttons": [
- {
- "args": [None, frame_args(0)],
- "label": "&#9654;", # play symbol
- "method": "animate",
- },
- {
- "args": [[None], frame_args(0)],
- "label": "&#9724;", # pause symbol
- "method": "animate",
- },
- ],
- "direction": "left",
- "pad": {"r": 10, "t": 70},
- "type": "buttons",
- "x": 0.1,
- "y": 0,
- }
- ],
- sliders=sliders
-)
-
-fig.show()
diff --git a/jon_scratch/karls_pupil_freemocap_code.ipynb b/jon_scratch/karls_pupil_freemocap_code.ipynb
deleted file mode 100644
index a613c97b..00000000
--- a/jon_scratch/karls_pupil_freemocap_code.ipynb
+++ /dev/null
@@ -1,1256 +0,0 @@
-{
- "cells": [
- {
- "cell_type": "markdown",
- "metadata": {
- "pycharm": {
- "name": "#%% md\n"
- }
- },
- "source": [
- "\n",
- "# this is Jon's attempt to put Karl's `alignPupilFMC.py` into an jupyter notebook "
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {
- "pycharm": {
- "name": "#%% md\n"
- }
- },
- "source": [
- "### import stuff"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {
- "pycharm": {
- "name": "#%%\n"
- }
- },
- "outputs": [],
- "source": [
- "!pip install scipy\n",
- "!pip install pandas\n",
- "!pip install numpy\n",
- "!pip install pyqt5"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {
- "pycharm": {
- "name": "#%%\n"
- }
- },
- "outputs": [],
- "source": [
- "\n",
- "import numpy as np\n",
- "import pandas as pd\n",
- "import json\n",
- "from pathlib import Path\n",
- "\n",
- "from scipy import optimize\n",
- "from scipy.spatial.transform import Rotation\n",
- "\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {
- "pycharm": {
- "name": "#%%\n"
- }
- },
- "outputs": [],
- "source": [
- "debug = True\n",
- "if debug:\n",
- " %matplotlib qt\n",
- " # %matplotlib \n",
- " import matplotlib.pyplot as plt\n"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {
- "pycharm": {
- "name": "#%% md\n"
- }
- },
- "source": [
- "### get yr paths right"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {
- "pycharm": {
- "name": "#%%\n"
- }
- },
- "outputs": [],
- "source": [
- "session_id = 'sesh_2022-02-15_11_54_28_pupil_maybe'\n",
- "freemocap_data_folder = Path('C:/Users/jonma/Dropbox/FreeMoCapProject/FreeMocap_Data')\n",
- "\n",
- "session_folder_path = freemocap_data_folder / session_id\n",
- "\n",
- "mediapipe_skeleton_data_path = session_folder_path / 'DataArrays'/ 'mediaPipeSkel_3d_smoothed.npy'\n",
- "mediapipe_head_rotations_path = session_folder_path / 'DataArrays'/ 'mediaPipeSkel_3d_head_rotation_matricies_fr_row_col.npy'\n",
- "\n",
- "pupil_data_path = session_folder_path / 'pupil_000'\n",
- "pupil_data_exports_path = pupil_data_path / 'exports' / '000'\n",
- "pupil_positions_path = pupil_data_exports_path / 'pupil_positions.csv'\n",
- "pupil_recording_info_path = pupil_data_path / 'info.player.json'\n",
- "\n",
- "freemocap_unix_timestamp_path = session_folder_path /'unix_synced_timestamps.csv'\n"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {
- "pycharm": {
- "name": "#%% md\n"
- }
- },
- "source": [
- " ### load in data\n",
- "\n",
- "- full body 3d kinematic data - `mediapipe_skeleton_frame_mar_xyz`\n",
- " - type: numpy array\n",
- " - dimensions: [frame_number, tracked_point_number, dimension (xyz)]\n",
- "- pupil data from `pupil_positions.csv` in the **pupil exports** folder\n",
- " - definitions in `pupil_gaze_positions_info.txt`\n",
- "- pupil start time from `info.player.json` for sync\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {
- "pycharm": {
- "name": "#%%\n"
- }
- },
- "outputs": [],
- "source": [
- "mediapipe_skeleton_fr_mar_xyz = np.load(mediapipe_skeleton_data_path)\n",
- "mediapipe_head_rotation_matricies_fr_row_col = np.load(mediapipe_head_rotations_path)\n",
- "pupil_dataframe = pd.read_csv(pupil_positions_path)\n",
- "pupil_recording_info_json = json.load(open(pupil_recording_info_path))\n",
- "freemocap_unix_timestamps_dataframe = pd.read_csv(freemocap_unix_timestamp_path)"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {
- "pycharm": {
- "name": "#%% md\n"
- }
- },
- "source": [
- "### pull out relevant pupil data"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {
- "pycharm": {
- "name": "#%% md\n"
- }
- },
- "source": [
- "data for both eyes"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {
- "pycharm": {
- "name": "#%%\n"
- }
- },
- "outputs": [],
- "source": [
- "\n",
- "timestamps = np.array(pupil_dataframe['pupil_timestamp'])\n",
- "eye_theta = np.array(pupil_dataframe['theta'])\n",
- "eye_phi = np.array(pupil_dataframe['phi'])\n",
- "sphere_center_x = np.array(pupil_dataframe['sphere_center_x'])\n",
- "sphere_center_y = np.array(pupil_dataframe['sphere_center_y'])\n",
- "sphere_center_z = np.array(pupil_dataframe['sphere_center_z'])\n",
- "pupil_center_normal_x = np.array(pupil_dataframe['circle_3d_normal_x'])\n",
- "pupil_center_normal_y = np.array(pupil_dataframe['circle_3d_normal_y'])\n",
- "pupil_center_normal_z = np.array(pupil_dataframe['circle_3d_normal_z'])\n",
- "\n",
- "eye_d = pupil_dataframe['eye_id']\n",
- "method = pupil_dataframe['method']\n",
- "# tracking_method_name = 'pye3d 0.3.0 real-time'\n",
- "\n",
- "\n"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {
- "pycharm": {
- "name": "#%% md\n"
- }
- },
- "source": [
- "get data for the right eye\n",
- "\n",
- "pull out data according to `eye_d` (right_eye == 0) and tracking method (because pupil interleaves 2d and 3d data)"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {
- "pycharm": {
- "name": "#%%\n"
- }
- },
- "outputs": [],
- "source": [
- "right_eye_d = 0 \n",
- "\n",
- "#timestamps\n",
- "r_eye_timestamps_og = timestamps[np.logical_and(eye_d==right_eye_d, method!='2d c++')]\n",
- "\n",
- "r_eye_theta = eye_theta[np.logical_and(eye_d==right_eye_d, method!='2d c++')]\n",
- "r_eye_phi = eye_phi[np.logical_and(eye_d==right_eye_d, method!='2d c++')]\n",
- "\n",
- "r_eye_sphere_center_x = sphere_center_x[np.logical_and(eye_d==right_eye_d, method!='2d c++')]\n",
- "r_eye_sphere_center_y = sphere_center_y[np.logical_and(eye_d==right_eye_d, method!='2d c++')]\n",
- "r_eye_sphere_center_z = sphere_center_z[np.logical_and(eye_d==right_eye_d, method!='2d c++')]\n",
- "\n",
- "r_eye_pupil_center_normal_x = pupil_center_normal_x[np.logical_and(eye_d==right_eye_d, method!='2d c++')]\n",
- "r_eye_pupil_center_normal_y = pupil_center_normal_y[np.logical_and(eye_d==right_eye_d, method!='2d c++')]\n",
- "r_eye_pupil_center_normal_z = pupil_center_normal_z[np.logical_and(eye_d==right_eye_d, method!='2d c++')]\n"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {
- "pycharm": {
- "name": "#%% md\n"
- }
- },
- "source": [
- "Get data for the left eye\n",
- "\n",
- "pull out data according to `eye_d` (left eye == 1) and tracking method (because pupil interleaves 2d and 3d data)"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {
- "pycharm": {
- "name": "#%%\n"
- }
- },
- "outputs": [],
- "source": [
- "left_eye_d = 1 \n",
- "\n",
- "#timestamps\n",
- "l_eye_timestamps_og = timestamps[np.logical_and(eye_d==left_eye_d, method!='2d c++')]\n",
- "\n",
- "l_eye_theta = eye_theta[np.logical_and(eye_d==left_eye_d, method!='2d c++')]\n",
- "l_eye_phi = eye_phi[np.logical_and(eye_d==left_eye_d, method!='2d c++')]\n",
- "\n",
- "l_eye_sphere_center_x = sphere_center_x[np.logical_and(eye_d==left_eye_d, method!='2d c++')]\n",
- "l_eye_sphere_center_y = sphere_center_y[np.logical_and(eye_d==left_eye_d, method!='2d c++')]\n",
- "l_eye_sphere_center_z = sphere_center_z[np.logical_and(eye_d==left_eye_d, method!='2d c++')]\n",
- "\n",
- "l_eye_pupil_center_normal_x = pupil_center_normal_x[np.logical_and(eye_d==left_eye_d, method!='2d c++')]\n",
- "l_eye_pupil_center_normal_y = pupil_center_normal_y[np.logical_and(eye_d==left_eye_d, method!='2d c++')]\n",
- "l_eye_pupil_center_normal_z = pupil_center_normal_z[np.logical_and(eye_d==left_eye_d, method!='2d c++')]\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {
- "pycharm": {
- "name": "#%%\n"
- }
- },
- "outputs": [],
- "source": [
- "if debug:\n",
- " fig = plt.figure(num=2134,figsize=(10,10))\n",
- " \n",
- " ax1 = fig.add_subplot(321)\n",
- " ax1.plot(r_eye_timestamps_og, r_eye_theta, '.-', label='r eye theta')\n",
- " ax1.plot(r_eye_timestamps_og, r_eye_phi, '.-', label='r eye phi')\n",
- "\n",
- " ax1.legend(loc='upper right')\n",
- " \n",
- " ax3 = fig.add_subplot(323)\n",
- " ax3.plot(r_eye_timestamps_og, r_eye_pupil_center_normal_x, '.-', label='r_eye_pupil_center_normal_x')\n",
- " ax3.plot(r_eye_timestamps_og, r_eye_pupil_center_normal_y, '.-', label='r_eye_pupil_center_normal_y')\n",
- " ax3.plot(r_eye_timestamps_og, r_eye_pupil_center_normal_z, '.-', label='r_eye_pupil_center_normal_z')\n",
- " ax3.legend(loc='upper right')\n",
- "\n",
- " ax5 = fig.add_subplot(325)\n",
- " ax5.plot(r_eye_timestamps_og, r_eye_sphere_center_x, '.-', label='r_eye_sphere_center_x')\n",
- " ax5.plot(r_eye_timestamps_og, r_eye_sphere_center_y, '.-', label='r_eye_sphere_center_y')\n",
- " ax5.plot(r_eye_timestamps_og, r_eye_sphere_center_z, '.-', label='r_eye_sphere_center_z')\n",
- " ax5.legend(loc='upper right')\n",
- "\n",
- " \n",
- " ax2 = fig.add_subplot(322)\n",
- " ax2.plot(l_eye_timestamps_og, l_eye_theta, '.-', label='l eye theta')\n",
- " ax2.plot(l_eye_timestamps_og, l_eye_phi, '.-', label='l eye phi')\n",
- " ax2.legend(loc='upper right')\n",
- " \n",
- " ax4 = fig.add_subplot(324)\n",
- " ax4.plot(l_eye_timestamps_og, l_eye_pupil_center_normal_x, '.-', label='l_eye_pupil_center_normal_x')\n",
- " ax4.plot(l_eye_timestamps_og, l_eye_pupil_center_normal_y, '.-', label='l_eye_pupil_center_normal_y')\n",
- " ax4.plot(l_eye_timestamps_og, l_eye_pupil_center_normal_z, '.-', label='l_eye_pupil_center_normal_z')\n",
- " ax4.legend(loc='upper right')\n",
- "\n",
- " ax6 = fig.add_subplot(326)\n",
- " ax6.plot(l_eye_timestamps_og, l_eye_sphere_center_x, '.-', label='l_eye_sphere_center_x')\n",
- " ax6.plot(l_eye_timestamps_og, l_eye_sphere_center_y, '.-', label='l_eye_sphere_center_y')\n",
- " ax6.plot(l_eye_timestamps_og, l_eye_sphere_center_z, '.-', label='l_eye_sphere_center_z')\n",
- "\n",
- " plt.pause(.1)\n",
- " plt.show()\n"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {
- "pycharm": {
- "name": "#%% md\n"
- }
- },
- "source": [
- "### create XYZ gaze array\n",
- "\n",
- "\n",
- "subtract eyeball center from pupil center to re-base the gaze vector to the origin "
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {
- "pycharm": {
- "name": "#%% md\n"
- }
- },
- "source": [
- "skipping 'remove nans' step for now, but i might need to add it later? "
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {
- "pycharm": {
- "name": "#%% md\n"
- }
- },
- "source": [
- "### synchronize pupil and freemocap timestamps "
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {
- "pycharm": {
- "name": "#%% md\n"
- }
- },
- "source": [
- "#### convert pupil timestamps into unix time"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {
- "pycharm": {
- "name": "#%%\n"
- }
- },
- "outputs": [],
- "source": [
- "r_eye_timestamps = r_eye_timestamps_og - pupil_recording_info_json['start_time_synced_s'] +pupil_recording_info_json['start_time_system_s'] \n",
- "l_eye_timestamps = l_eye_timestamps_og - pupil_recording_info_json['start_time_synced_s'] +pupil_recording_info_json['start_time_system_s'] \n",
- "\n"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {
- "pycharm": {
- "name": "#%% md\n"
- }
- },
- "source": [
- "calculate freemocap unix timestamps (as mean of each camera's timestamp on each frame)"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {
- "pycharm": {
- "name": "#%%\n"
- }
- },
- "outputs": [],
- "source": [
- "\n",
- "each_cam_timestamps_list = []\n",
- "\n",
- "camera_names = [column_name for column_name in list(freemocap_unix_timestamps_dataframe.columns) if 'Cam' in column_name]\n",
- "\n",
- "for this_camera_name in camera_names:\n",
- " each_cam_timestamps_list.append(np.array(freemocap_unix_timestamps_dataframe[this_camera_name]))\n",
- " \n",
- "cameras_timestamp_array = np.stack(each_cam_timestamps_list,axis=1)\n",
- "cameras_timestamp_array[cameras_timestamp_array==-1]=np.nan #replace -1 with nan\n",
- "\n",
- "freemocap_timestamps = np.nanmean(cameras_timestamp_array,axis=1)\n",
- "\n",
- "freemocap_frame_durations = np.diff(freemocap_timestamps)\n",
- "freemocap_frames_per_second = np.nanmean(freemocap_frame_durations**-1)\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {
- "pycharm": {
- "name": "#%%\n"
- }
- },
- "outputs": [],
- "source": [
- "if debug:\n",
- "\n",
- " timestamp_diff_on_each_frame_rel_cam0 = np.diff(cameras_timestamp_array, axis=1)\n",
- " frame_duration = np.diff(freemocap_timestamps)\n",
- "\n",
- " fig = plt.figure(234899234)\n",
- " ax1 = fig.add_subplot(411)\n",
- " ax1.plot(cameras_timestamp_array, '.-',label='each cam')\n",
- " ax1.plot(freemocap_timestamps, 'r-',label='freemocap_timestamps')\n",
- " ax1.set_title('cameras_timestamps')\n",
- " ax1.set_xlabel('frame number')\n",
- " ax1.set_ylabel('timestamp')\n",
- " ax1.legend(loc='upper left')\n",
- " \n",
- " ax2 = fig.add_subplot(412)\n",
- " for this_cam_num in range(timestamp_diff_on_each_frame_rel_cam0.shape[1]):\n",
- " ax2.hist(timestamp_diff_on_each_frame_rel_cam0[:,this_cam_num], label=f'camera {this_cam_num}', alpha=0.5)\n",
- " ax2.set_xlim(-.1,.1)\n",
- " ax2.set_xlabel('timestamp diff on each frame (s)')\n",
- " ax2.legend()\n",
- "\n",
- " ax3 = fig.add_subplot(413)\n",
- " ax3.plot(freemocap_frame_durations, '.-',label='frame duration')\n",
- " ax3.plot([0, len(freemocap_frame_durations)],\n",
- " [np.nanmean(freemocap_frame_durations), np.nanmean(freemocap_frame_durations)],\n",
- " 'r-',\n",
- " label=f'mean frame duration (ms):{str(np.nanmean(freemocap_frame_durations)*1000)[:5]}',\n",
- " )\n",
- " ax3.legend(loc='upper left')\n",
- " ax3.set_xlabel('frame number')\n",
- " ax3.set_ylabel('frame duration (s)')\n",
- "\n",
- " ax4 = fig.add_subplot(414)\n",
- " ax4.hist(freemocap_frame_durations**-1, label='frame duration')\n",
- " ax4.legend(loc='upper left')\n",
- " ax4.set_xlabel('frame rate (frames per second')\n",
- " ax4.set_xlim(0,50)\n",
- " \n",
- " plt.pause(.1)\n",
- " plt.show()"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {
- "pycharm": {
- "name": "#%%\n"
- }
- },
- "outputs": [],
- "source": [
- "print(f'freemocap_timestamps[-1]: {freemocap_timestamps[-1]}')\n",
- "print(f'r_eye_timestamps[-1]: {r_eye_timestamps[-1]}')\n",
- "\n",
- "np.min((freemocap_timestamps[-1],r_eye_timestamps[-1]))"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {
- "pycharm": {
- "name": "#%% md\n"
- }
- },
- "source": [
- "#### align freemocap and pupil timestamps and clip the starts and ends of the various data traces so that everything covers the same timespacn"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {
- "pycharm": {
- "name": "#%%\n"
- }
- },
- "outputs": [],
- "source": [
- "\n",
- "#find start and end frames shared by all datastreams\n",
- "start_time_unix = np.max((freemocap_timestamps[0],r_eye_timestamps[0], l_eye_timestamps[0]))\n",
- "end_time_unix = np.min((freemocap_timestamps[-1],r_eye_timestamps[-1], l_eye_timestamps[-1]))\n",
- "\n",
- "#freemocap\n",
- "if any(freemocap_timestamps>=start_time_unix):\n",
- " freemocap_start = np.where(freemocap_timestamps>=start_time_unix)[0][0]\n",
- "else:\n",
- " freemocap_start = 0\n",
- "\n",
- "if any(freemocap_timestamps<=end_time_unix):\n",
- " freemocap_end = np.where(freemocap_timestamps<=end_time_unix)[0][-1]\n",
- "else:\n",
- " freemocap_end = len(freemocap_timestamps)\n",
- "\n",
- "#right eye\n",
- "if any(r_eye_timestamps>=start_time_unix):\n",
- " r_eye_start = np.where(r_eye_timestamps>=start_time_unix)[0][0]\n",
- "else:\n",
- " r_eye_start = 0\n",
- " \n",
- "if any(r_eye_timestamps<=end_time_unix):\n",
- " r_eye_end = np.where(r_eye_timestamps<=end_time_unix)[0][-1]\n",
- "else:\n",
- " r_eye_end = len(r_eye_timestamps)\n",
- "\n",
- "#left eye\n",
- "if any(l_eye_timestamps>=start_time_unix):\n",
- " l_eye_start = np.where(l_eye_timestamps>=start_time_unix)[0][0]\n",
- "else:\n",
- " l_eye_start = 0\n",
- " \n",
- "if any(l_eye_timestamps<=end_time_unix):\n",
- " l_eye_end = np.where(l_eye_timestamps<=end_time_unix)[0][-1]\n",
- "else:\n",
- " l_eye_end = len(l_eye_timestamps)\n",
- "\n",
- "#rebase time onto freemocap's framerate (b/c it's slower than pupil) <- sloppy, assumes mocap slower than eye tracker, which is untrue for say GoPros\n",
- "new_timestamps = np.arange(start_time_unix,end_time_unix,1/freemocap_frames_per_second) \n",
- "\n",
- "\n",
- "freemocap_timestamps = freemocap_timestamps[freemocap_start:freemocap_end]\n",
- "r_eye_timestamps = r_eye_timestamps[r_eye_start:r_eye_end]\n",
- "l_eye_timestamps = l_eye_timestamps[l_eye_start:l_eye_end]\n",
- "\n"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {
- "pycharm": {
- "name": "#%% md\n"
- }
- },
- "source": [
- "clip out portions of each eye's data stream that correspond to the shared time period\n",
- "\n",
- "(I appear to be skiping the freemocap data, which might cause fail on other recordings?)"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {
- "pycharm": {
- "name": "#%%\n"
- }
- },
- "outputs": [],
- "source": [
- "r_eye_sphere_center_x = r_eye_sphere_center_x[r_eye_start:r_eye_end]\n",
- "r_eye_sphere_center_y = r_eye_sphere_center_y[r_eye_start:r_eye_end]\n",
- "r_eye_sphere_center_z = r_eye_sphere_center_z[r_eye_start:r_eye_end]\n",
- "\n",
- "r_eye_pupil_center_normal_x = r_eye_pupil_center_normal_x[r_eye_start:r_eye_end]\n",
- "r_eye_pupil_center_normal_y = r_eye_pupil_center_normal_y[r_eye_start:r_eye_end]\n",
- "r_eye_pupil_center_normal_z = r_eye_pupil_center_normal_z[r_eye_start:r_eye_end]"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {
- "pycharm": {
- "name": "#%%\n"
- }
- },
- "outputs": [],
- "source": [
- "l_eye_sphere_center_x = l_eye_sphere_center_x[l_eye_start:l_eye_end]\n",
- "l_eye_sphere_center_y = l_eye_sphere_center_y[l_eye_start:l_eye_end]\n",
- "l_eye_sphere_center_z = l_eye_sphere_center_z[l_eye_start:l_eye_end]\n",
- "\n",
- "l_eye_pupil_center_normal_x = l_eye_pupil_center_normal_x[l_eye_start:l_eye_end]\n",
- "l_eye_pupil_center_normal_y = l_eye_pupil_center_normal_y[l_eye_start:l_eye_end]\n",
- "l_eye_pupil_center_normal_z = l_eye_pupil_center_normal_z[l_eye_start:l_eye_end]"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {
- "pycharm": {
- "name": "#%% md\n"
- }
- },
- "source": [
- "create r_eye_gaze_xyz : the direction the eye is pointing *in head centered coordinates*"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {
- "pycharm": {
- "name": "#%%\n"
- }
- },
- "outputs": [],
- "source": [
- "r_eye_gaze_x = r_eye_pupil_center_normal_x\n",
- "r_eye_gaze_y = r_eye_pupil_center_normal_y\n",
- "r_eye_gaze_z = r_eye_pupil_center_normal_z\n",
- "\n",
- "r_eye_gaze_xyz_og = np.vstack((r_eye_gaze_x, r_eye_gaze_y, r_eye_gaze_z)).T\n",
- "\n",
- "print(f'r_eye_gaze_xyz_og.shape: {r_eye_gaze_xyz_og.shape}')"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {
- "pycharm": {
- "name": "#%%\n"
- }
- },
- "outputs": [],
- "source": [
- "l_eye_gaze_x = l_eye_pupil_center_normal_x\n",
- "l_eye_gaze_y = l_eye_pupil_center_normal_y\n",
- "l_eye_gaze_z = l_eye_pupil_center_normal_z\n",
- "\n",
- "l_eye_gaze_xyz_og = np.vstack((l_eye_gaze_x, l_eye_gaze_y, l_eye_gaze_z)).T\n",
- "\n",
- "print(f'l_eye_gaze_xyz_og.shape: {l_eye_gaze_xyz_og.shape}')"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {
- "pycharm": {
- "name": "#%% md\n"
- }
- },
- "source": [
- "#### resample gaze and skeleton data so that each has the same number of frames\n",
- "\n",
- "resample pupil data onto freemocap timestamps"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {
- "pycharm": {
- "name": "#%%\n"
- }
- },
- "outputs": [],
- "source": [
- "\n",
- "r_eye_gaze_xyz = np.zeros((len(freemocap_timestamps),3))\n",
- "l_eye_gaze_xyz = np.zeros((len(freemocap_timestamps),3))\n",
- "\n",
- "for this_dimension in range(3): #loop over the X Y and Z simensions and resample to new timestamps\n",
- " r_eye_gaze_xyz[:,this_dimension] = np.interp(freemocap_timestamps,\n",
- " r_eye_timestamps,\n",
- " r_eye_gaze_xyz_og[:,this_dimension])\n",
- " l_eye_gaze_xyz[:,this_dimension] = np.interp(freemocap_timestamps,\n",
- " l_eye_timestamps,\n",
- " l_eye_gaze_xyz_og[:,this_dimension])\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {
- "pycharm": {
- "name": "#%%\n"
- }
- },
- "outputs": [],
- "source": [
- "r_eye_gaze_xyz = r_eye_gaze_xyz/np.linalg.norm(r_eye_gaze_xyz,axis=1,ord=2)[:,None]\n",
- "l_eye_gaze_xyz = l_eye_gaze_xyz/np.linalg.norm(l_eye_gaze_xyz,axis=1,ord=2)[:,None]\n"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {
- "pycharm": {
- "name": "#%% md\n"
- }
- },
- "source": [
- "# snip off the first frame of the freemocap data becuase there is a -> BUG <- such that there are one fewer timestamp than there are recorded frames. \n",
- "\n",
- "V V V V V V"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {
- "pycharm": {
- "name": "#%%\n"
- }
- },
- "outputs": [],
- "source": [
- "if r_eye_gaze_xyz.shape[0] != mediapipe_skeleton_fr_mar_xyz.shape[0]:\n",
- " mediapipe_skeleton_fr_mar_xyz = np.delete(mediapipe_skeleton_fr_mar_xyz, 0, axis=0)\n",
- " mediapipe_head_rotation_matricies_fr_row_col = np.delete(mediapipe_head_rotation_matricies_fr_row_col, 0, axis=0)\n",
- "# DOESN'T BOTHER ME AT ALL HAHA"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {
- "pycharm": {
- "name": "#%% md\n"
- }
- },
- "source": [
- "These should all have the exact same number of frame"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {
- "pycharm": {
- "name": "#%%\n"
- }
- },
- "outputs": [],
- "source": [
- "print(f'r_eye_gaze_xyz.shape: {r_eye_gaze_xyz.shape}')\n",
- "print(f'l_eye_gaze_xyz.shape: {l_eye_gaze_xyz.shape}')\n",
- "print(f'mediapipe_skeleton_fr_mar_xyz.shape: {mediapipe_skeleton_fr_mar_xyz.shape}')\n",
- "print(f'mediapipe_head_rotation_matricies_fr_row_col.shape: {mediapipe_head_rotation_matricies_fr_row_col.shape}')"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {
- "pycharm": {
- "name": "#%%\n"
- }
- },
- "outputs": [],
- "source": [
- "if debug:\n",
- " fig = plt.figure(num=65341,figsize=(10,20))\n",
- " ax1 = fig.add_subplot(211)\n",
- " ax1.plot(freemocap_timestamps, r_eye_gaze_xyz[:,0], '.-', label='r_eye_gaze_x')\n",
- " ax1.plot(freemocap_timestamps, r_eye_gaze_xyz[:,1], '.-', label='r_eye_gaze_y')\n",
- " ax1.plot(freemocap_timestamps, r_eye_gaze_xyz[:,2], '.-', label='r_eye_gaze_z')\n",
- " ax1.legend(loc='upper left')\n",
- " \n",
- " ax2 = fig.add_subplot(212)\n",
- " ax2.plot(freemocap_timestamps, l_eye_gaze_xyz[:,0], '.-', label='_eye_gaze_x')\n",
- " ax2.plot(freemocap_timestamps, l_eye_gaze_xyz[:,1], '.-', label='_eye_gaze_y')\n",
- " ax2.plot(freemocap_timestamps, l_eye_gaze_xyz[:,2], '.-', label='_eye_gaze_z')\n",
- " ax2.legend(loc='upper left')\n",
- " plt.show()\n",
- "\n"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {
- "pycharm": {
- "name": "#%% md\n"
- }
- },
- "source": [
- "normalize gaze vector to unit length"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {
- "pycharm": {
- "name": "#%% md\n"
- }
- },
- "source": [
- "save out `npy` of gaze_xyz data"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {
- "pycharm": {
- "name": "#%% md\n"
- }
- },
- "source": [
- "Smooth a bit with savitsky golay filter"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {
- "pycharm": {
- "name": "#%%\n"
- }
- },
- "outputs": [],
- "source": [
- "from scipy.signal import savgol_filter\n",
- "\n",
- "smoothWinLength = 5\n",
- "smoothOrder = 3\n",
- "for dim in range(r_eye_gaze_xyz.shape[1]):\n",
- " r_eye_gaze_xyz[:,dim] = savgol_filter(r_eye_gaze_xyz[:,dim], smoothWinLength, smoothOrder)\n",
- " l_eye_gaze_xyz[:,dim] = savgol_filter(l_eye_gaze_xyz[:,dim], smoothWinLength, smoothOrder)\n",
- "\n",
- "\n",
- "# #reorient gaze (I think because it comes in in image coordiates? not really sure )\n",
- "# r_eye_gaze_xyz[:,1] = -r_eye_gaze_xyz[:,1]\n",
- "# r_eye_gaze_xyz[:,(0,2)] = r_eye_gaze_xyz[:,(2,0)]\n",
- "\n",
- "# l_eye_gaze_xyz[:,1] = -l_eye_gaze_xyz[:,1]\n",
- "# l_eye_gaze_xyz[:,(0,2)] = l_eye_gaze_xyz[:,(2,0)]"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {
- "pycharm": {
- "name": "#%%\n"
- }
- },
- "outputs": [],
- "source": [
- "r_gaze_xyz_npy_save_path = pupil_data_exports_path / 'right_eye_gaze_xyz_synchronized_w_freemocap_uncalibrated.npy'\n",
- "np.save(r_gaze_xyz_npy_save_path, r_eye_gaze_xyz)\n",
- "\n",
- "l_gaze_xyz_npy_save_path = pupil_data_exports_path / 'left_eye_gaze_xyz_synchronized_w_freemocap_uncalibrated.npy'\n",
- "np.save(l_gaze_xyz_npy_save_path, l_eye_gaze_xyz)\n"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {
- "pycharm": {
- "name": "#%% md\n"
- }
- },
- "source": [
- "# VOR Calibration"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {
- "pycharm": {
- "name": "#%% md\n"
- }
- },
- "source": [
- "# prep data for VOR calibration\n",
- "\n",
- "we'll be finding a rotational offset such that gaze_xyz rotated-by-the offset-then-rotated-by-head-orientation will align with the fixation point\n",
- "\n",
- " so we want to put the fixation point (in this case the right index finger in a eyeball-centered reference frame (i.e. where `r_eye_xyz` is at `(0,0,0)`)"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {
- "collapsed": false,
- "pycharm": {
- "name": "#%%\n"
- }
- },
- "outputs": [],
- "source": [
- "vor_frame_start =1000\n",
- "vor_frame_end = 1400\n",
- "\n",
- "right_index_fingertip_idx = 41 # pretty sure this is right?\n",
- "r_eye_idx = 5\n",
- "\n",
- "fixation_point_xyz = np.squeeze(mediapipe_skeleton_fr_mar_xyz[:, right_index_fingertip_idx, :])\n",
- "r_eyeball_center_xyz = np.squeeze(mediapipe_skeleton_fr_mar_xyz[:, r_eye_idx, :])\n",
- "#make sure everyone is the right size and shape\n",
- "print(f'head_rotation_martices_fr_row_col.shape: {mediapipe_head_rotation_matricies_fr_row_col.shape}')\n",
- "print(f'r_eye_gaze_xyz.shape: {r_eye_gaze_xyz.shape}')\n",
- "print(f'fixation_point_xyz.shape: {fixation_point_xyz.shape}')\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {
- "collapsed": false,
- "pycharm": {
- "name": "#%%\n"
- }
- },
- "outputs": [],
- "source": [
- "\n",
- "fixation_point_during_vor_xyz = mediapipe_skeleton_fr_mar_xyz[vor_frame_start:vor_frame_end, right_index_fingertip_idx, :]\n",
- "r_eyeball_center_during_vor_xyz = mediapipe_skeleton_fr_mar_xyz[vor_frame_start:vor_frame_end, r_eye_idx, :]\n",
- "\n",
- "fixation_point_in_r_eyeball_coordinates_fr_xyz = r_eyeball_center_during_vor_xyz - fixation_point_during_vor_xyz #Subtract the-thing-that-will-be-at-origin from the-other-things to put other-things in ## thing-that-will-be-at-origin-centered-reference-frame\n",
- "fixation_point_distance_xyz = np.squeeze(np.linalg.norm(fixation_point_in_r_eyeball_coordinates_fr_xyz,axis=1,ord=2)[:,None])\n",
- "\n",
- "\n",
- "\n",
- "r_gaze_during_vor_fr_xyz = r_eye_gaze_xyz[vor_frame_start:vor_frame_end]\n",
- "r_gaze_during_vor_fr_xyz[:,0] = r_gaze_during_vor_fr_xyz[:,0] * fixation_point_distance_xyz #scale gaze vector to reach fixation point\n",
- "r_gaze_during_vor_fr_xyz[:,1] = r_gaze_during_vor_fr_xyz[:,1] * fixation_point_distance_xyz #scale gaze vector to reach fixation point\n",
- "r_gaze_during_vor_fr_xyz[:,2] = r_gaze_during_vor_fr_xyz[:,2] * fixation_point_distance_xyz #scale gaze vector to reach fixation point\n",
- "r_gaze_during_vor_fr_xyz"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {
- "collapsed": false,
- "pycharm": {
- "name": "#%%\n"
- }
- },
- "outputs": [],
- "source": [
- "\n",
- "head_rotation_matrices_during_vor_fr_row_col = mediapipe_head_rotation_matricies_fr_row_col[vor_frame_start:vor_frame_end, :, :]\n",
- "\n",
- "#make sure everyone is the right size and shape\n",
- "print(f'head_rotation_matrices_during_vor_fr_row_col.shape: {head_rotation_matrices_during_vor_fr_row_col.shape}')\n",
- "print(f'r_gaze_during_vor_xyz.shape: {r_gaze_during_vor_fr_xyz.shape}')\n",
- "print(f'fixation_point_in_r_eyeball_coordinates_xyz.shape: {fixation_point_in_r_eyeball_coordinates_fr_xyz.shape}')\n"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {
- "collapsed": false,
- "pycharm": {
- "name": "#%% md\n"
- }
- },
- "source": [
- "put mediapipe skel into eyeball centered coordinates (for debugging)"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {
- "collapsed": false,
- "pycharm": {
- "name": "#%%\n"
- }
- },
- "outputs": [],
- "source": [
- "skel_during_vor_fr_mar_dim = mediapipe_skeleton_fr_mar_xyz[vor_frame_start:vor_frame_end,:,:]\n",
- "\n",
- "for this_marker_number in range(skel_during_vor_fr_mar_dim.shape[1]):\n",
- " skel_during_vor_fr_mar_dim[:,this_marker_number,:] = r_eyeball_center_during_vor_xyz - skel_during_vor_fr_mar_dim[:,this_marker_number,:]\n",
- "\n",
- "\n",
- "print(f'skel_during_vor_fr_mar_dim.shape: {skel_during_vor_fr_mar_dim.shape}')"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {
- "collapsed": false,
- "pycharm": {
- "name": "#%% md\n"
- }
- },
- "source": [
- "# define error functions and run optimization\n",
- "\n",
- "according to lines 58:68 of - [https://github.com/trentwirth/ARGP_Matlab_LaserSkeleton/blob/main/Toolbox/vorPupilAlignErrFun_eyeCam.m](https://github.com/trentwirth/ARGP_Matlab_LaserSkeleton/blob/main/Toolbox/vorPupilAlignErrFun_eyeCam.m)\n",
- "```\n",
- "\n",
- "%%\n",
- "%%%%%%% This part's important - Rotate gaze vector by [this guess at the proper alignment matrix], prior to resituating the origin on on the eyeball\n",
- "%%%%\n",
- "\n",
- "\n",
- "for rr = 1:length(gazeXYZ)\n",
- " \n",
- " thisET_frame_unrot = camRotMatGuess * [gazeXYZ(rr,1); gazeXYZ(rr,2); gazeXYZ(rr,3)];\n",
- " thisETframe = headRotMat_row_col_fr(:,:,rr) * thisET_frame_unrot;\n",
- " \n",
- " headOrVec(rr,:) = headRotMat_row_col_fr(:,:,rr) * [2e3; 0;0];\n",
- " \n",
- " gazeXYZ(rr,:) = thisETframe;\n",
- " \n",
- "end\n",
- "\n",
- "```\n",
- "\n",
- "we want to rotate by rotation_guess THEN by head rotation \n",
- "\n",
- "(which makes sense, since we're using the optimizer to find the rotational offset between the eye camera reference frame and the eye-in-head reference frame)\n",
- "\n"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {
- "collapsed": false,
- "pycharm": {
- "name": "#%% md\n"
- }
- },
- "source": [
- "### optimization error animation function \n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {
- "collapsed": false,
- "pycharm": {
- "name": "#%%\n"
- }
- },
- "outputs": [],
- "source": [
- "plt.close('all')\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {
- "collapsed": false,
- "pycharm": {
- "name": "#%%\n"
- }
- },
- "outputs": [],
- "source": [
- "\n",
- "if debug:\n",
- " def plot_optimization_error(error,gaze_xyz, gaze_rotated_by_guess_then_head_rotation_xyz, mean_fixation_point_xyz, skel_during_vor_fr_mar_dim):\n",
- " figure_number=13451\n",
- "\n",
- " if not plt.fignum_exists(figure_number):\n",
- " fig = plt.figure(figure_number)\n",
- " ax = fig.add_subplot(111, projection='3d')\n",
- " else:\n",
- " fig = plt.gcf()\n",
- " ax = plt.gca()\n",
- "\n",
- "\n",
- " fig.suptitle(f'error: {error}')\n",
- " ax_range = 1e3\n",
- " ax.clear() \n",
- "\n",
- " ax.plot(0,0,0, 'mo',label='origin')\n",
- "\n",
- " ax.plot(gaze_xyz[:,0],\n",
- " gaze_xyz[:,1], \n",
- " gaze_xyz[:,2], 'k-o',label='original gaze xyz')\n",
- "\n",
- " gaze_rot_xyz =np.array(gaze_rotated_by_guess_then_head_rotation_xyz)\n",
- " ax.plot(gaze_rot_xyz[:,0],\n",
- " gaze_rot_xyz[:,1], \n",
- " gaze_rot_xyz[:,2], 'r-o',label='gaze_rotated_by_guess_then_head_rotation_xyz')\n",
- "\n",
- " ax.plot(mean_fixation_point_xyz[0],\n",
- " mean_fixation_point_xyz[1], \n",
- " mean_fixation_point_xyz[2], 'b-o',label='mean_fixation_point_xyz')\n",
- "\n",
- " ax.set_xlim([-ax_range, ax_range])\n",
- " ax.set_ylim([-ax_range, ax_range])\n",
- " ax.set_zlim([-ax_range, ax_range])\n",
- " ax.legend()\n",
- " plt.pause(.01)\n",
- "\n",
- "\n",
- "\n",
- "def get_error_between_two_rotation_matricies(euler_angle_guess,\n",
- " gaze_xyz,\n",
- " fixation_point_in_eye_coordinates_xyz,\n",
- " head_rotation_maticies_fr_row_col,\n",
- " skel_during_vor_fr_mar_dim):\n",
- " #convert euler angles to rotation matrix\n",
- " rotation_matrix_guess = Rotation.from_euler('XYZ',euler_angle_guess).as_matrix()\n",
- "\n",
- " #rotate gaze by rotation guess\n",
- " gaze_rotated_by_guess = [rotation_matrix_guess @ gaze_xyz[this_frame_number,:] for this_frame_number in range(gaze_xyz.shape[0])]\n",
- "\n",
- " #...then rotate THAT by head_rotation matrix\n",
- " gaze_rotated_by_guess_then_head_rotation_xyz =[head_rotation_maticies_fr_row_col[this_frame_number,:,:] @ gaze_rotated_by_guess[this_frame_number]\n",
- " for this_frame_number in range(gaze_xyz.shape[0])]\n",
- "\n",
- " mean_fixation_point_xyz = np.mean(fixation_point_in_eye_coordinates_xyz, axis=0)\n",
- " #define error as difference between the fixation point and that rotated gaze estimate (these are both normalized, I think)\n",
- " error_per_frame = gaze_rotated_by_guess_then_head_rotation_xyz - mean_fixation_point_xyz\n",
- " error = np.nanmean(np.nansum(error_per_frame**2)/error_per_frame.shape[0])\n",
- " \n",
- " plot_optimization_error(error,gaze_xyz, gaze_rotated_by_guess_then_head_rotation_xyz, mean_fixation_point_xyz, skel_during_vor_fr_mar_dim)\n",
- "\n",
- " return error\n",
- "\n",
- "\n",
- "def get_optimal_rotation_matrix_to_align_gaze_with_target(gaze_xyz,\n",
- " fixation_point_in_eye_coordinates_xyz,\n",
- " head_rotation_matricies_fr_row_col,\n",
- " skel_during_vor_fr_mar_dim):\n",
- " euler_angles = optimize.least_squares(get_error_between_two_rotation_matricies,\n",
- " [0,0,0],\n",
- " args=(gaze_xyz,fixation_point_in_eye_coordinates_xyz, head_rotation_matricies_fr_row_col, skel_during_vor_fr_mar_dim),\n",
- " gtol=1e-10,\n",
- " verbose=2).x\n",
- " return Rotation.from_euler('XYZ',euler_angles).as_matrix()\n",
- "\n",
- "\n",
- "######################################\n",
- "\n",
- "\n",
- "rotation_matrix_to_align_pupil_data_to_eye_in_head_coordinates = get_optimal_rotation_matrix_to_align_gaze_with_target(r_gaze_during_vor_fr_xyz,\n",
- " fixation_point_in_r_eyeball_coordinates_fr_xyz,\n",
- " head_rotation_matrices_during_vor_fr_row_col,\n",
- " skel_during_vor_fr_mar_dim)\n",
- "\n",
- "r_eye_gaze_xyz_calibrated = [rotation_matrix_to_align_pupil_data_to_eye_in_head_coordinates @ r_eye_gaze_xyz[this_frame_number,:] for this_frame_number in range(r_eye_gaze_xyz.shape[0])]\n",
- "\n",
- "\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {
- "pycharm": {
- "name": "#%%\n"
- }
- },
- "outputs": [],
- "source": [
- "gaze_xyz_npy_save_path = pupil_data_exports_path / 'right_eye_gaze_xyz.npy'\n",
- "np.save(gaze_xyz_npy_save_path, r_eye_gaze_xyz_calibrated)"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {
- "pycharm": {
- "name": "#%%\n"
- }
- },
- "outputs": [],
- "source": [
- "import plotly.offline as py\n",
- "import plotly.express as px \n",
- "import plotly.graph_objects as go\n",
- "\n",
- "fig = go.Figure()\n",
- "\n",
- "fig.add_trace(go.Scatter(x=np.arange(r_eye_gaze_xyz.shape[0]), y=r_eye_gaze_xyz[:,0], mode='lines+markers'))\n",
- "fig.add_trace(go.Scatter(x=np.arange(r_eye_gaze_xyz.shape[0]), y=r_eye_gaze_xyz[:,1], mode='lines+markers'))\n",
- "fig.add_trace(go.Scatter(x=np.arange(r_eye_gaze_xyz.shape[0]), y=r_eye_gaze_xyz[:,2], mode='lines+markers'))\n",
- "fig.show()"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {
- "pycharm": {
- "name": "#%%\n"
- }
- },
- "outputs": [],
- "source": [
- "\n",
- "data_path = Path('C:/Users/jonma/Dropbox/FreeMoCapProject/FreeMocap_Data/')\n",
- "session_path = data_path / 'sesh_2022-02-15_11_54_28_pupil_maybe'\n",
- "\n",
- "qt_gl_laser_skeleton = QT_GL_LaserSkeleton(session_path)\n",
- "qt_gl_laser_skeleton.start_animation()\n"
- ]
- }
- ],
- "metadata": {
- "interpreter": {
- "hash": "4ef2e72e5b895021b427c707c9f05b4880b5a5a00e886b84de197a42e54c7f32"
- },
- "kernelspec": {
- "display_name": "Python 3.9.12 ('humon-env')",
- "language": "python",
- "name": "python3"
- },
- "language_info": {
- "codemirror_mode": {
- "name": "ipython",
- "version": 3
- },
- "file_extension": ".py",
- "mimetype": "text/x-python",
- "name": "python",
- "nbconvert_exporter": "python",
- "pygments_lexer": "ipython3",
- "version": "3.9.12"
- },
- "orig_nbformat": 4
- },
- "nbformat": 4,
- "nbformat_minor": 2
-}
diff --git a/jon_scratch/matplotlib_laser_skeleton.py b/jon_scratch/matplotlib_laser_skeleton.py
deleted file mode 100644
index 27d59552..00000000
--- a/jon_scratch/matplotlib_laser_skeleton.py
+++ /dev/null
@@ -1,1039 +0,0 @@
-"""
-============
-β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆ β–ˆβ–ˆ
-β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ
-β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ
-β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ
-β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆ
-============
-Font - ANSI Regular - https://patorjk.com/software/taag/#p=display&f=ANSI%20Regular&t=Play%20Skeleton%20Animation
-============
-Originally based on tutorial from - https://matplotlib.org/2.1.2/gallery/animation/simple_3danim.html
-
-Create a matplotlib animation from a FreeMoCap recording session.
-"""
-
-
-################################################################################################################
-################################################################################################################
-###
-### β–ˆβ–ˆ β–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ
-### β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ
-### β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ
-### β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ
-### β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ
-###
-################################################################################################################
-################################################################################################################
-
-
-import numpy as np
-
-import matplotlib as mpl
-import matplotlib.pyplot as plt
-import mpl_toolkits.mplot3d.axes3d as p3
-import matplotlib.animation as animation
-from matplotlib.widgets import Slider
-import cv2
-from scipy.signal import savgol_filter
-import moviepy.editor as mp
-
-import os
-import copy
-from pathlib import Path
-
-#RICH CONSOLE STUFF
-from rich import pretty
-pretty.install() #makes all print statement output pretty
-from rich import inspect
-from rich.console import Console
-console = Console()
-from rich.traceback import install as rich_traceback_install
-from rich.markdown import Markdown
-
-#colors from Taylor Davis branding -
-humon_dark = np.array([37, 67, 66])/255
-humon_green = np.array([53, 93, 95])/255
-humon_blue = np.array([14, 90, 253])/255
-humon_red = np.array([217, 61, 67])/255
-
-
-def PlaySkeletonAnimation(
- session=None,
- vidType=1,
- startFrame=0,
- azimuth=-90,
- elevation=-70,
- useOpenPose=True,
- useMediaPipe=False,
- useDLC=False,
- recordVid = True,
- showAnimation =True,
- ):
-
-
-
-
- ###
- ###
- ### β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ
- ### β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ
- ### β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆ
- ### β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ
- ### β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ
- ###
- def update_figure(frameNum):
- """
- Called by matplotlib animator for each frame.
- """
-
- if useOpenPose:
- op_skel_dottos = matplotlib_artist_objs['op_skel_dottos']
- op_skel_trajectories = figure_data['openPose_skel_trajectories|mar|fr_dim']
-
- if useMediaPipe:
- mp_skel_dottos = matplotlib_artist_objs['mp_skel_dottos']
- mp_skel_trajectories = figure_data['mediaPipe_skel_trajectories|mar|fr_dim']
-
- charuco_dottos = matplotlib_artist_objs['charuco_dottos']
- charuco_trajectories = figure_data['charuco_trajectories|mar|fr_dim']
-
- if useDLC:
- dlc_dottos = matplotlib_artist_objs['dlc_dottos']
- dlc_trajectories = figure_data['dlc_trajectories|mar|fr_dim']
-
- #function to update the lines for each 3d body segment
- def update_3d_skel_segments(key, data_fr_mar_xyz):
- """
- updates the Artist of each body segment with the current frame data.
- """
- split = key.split('_')
-
- if split[0] == 'op':
- dict_of_segments_idxs = dict_of_openPoseSegmentIdx_dicts[key]
- if split[0] == 'mp':
- dict_of_segments_idxs = dict_of_mediaPipeSegmentIdx_dicts[key]
- elif split[0] == 'dlc':
- dict_of_segments_idxs = dict_of_dlcSegmentIdx_dicts[key]
-
- try:
- dict_of_artists = matplotlib_artist_objs[key]
- except:
- print('KeyError:', key)
-
-
- for thisItem in dict_of_segments_idxs.items():
- segName = thisItem[0]
- segArtist = dict_of_artists[segName]
- segArtist.set_data((data_fr_mar_xyz[frameNum, dict_of_segments_idxs[segName], 0], data_fr_mar_xyz[frameNum, dict_of_segments_idxs[segName], 1]))
- segArtist.set_3d_properties(data_fr_mar_xyz[frameNum, dict_of_segments_idxs[segName], 2])
-
- if useOpenPose:
- update_3d_skel_segments('op_body', openPose_skel_fr_mar_xyz)
- update_3d_skel_segments('op_rHand', openPose_skel_fr_mar_xyz)
- update_3d_skel_segments('op_lHand', openPose_skel_fr_mar_xyz)
- update_3d_skel_segments('op_face', openPose_skel_fr_mar_xyz)
-
- if useMediaPipe:
- update_3d_skel_segments('mp_body', mediaPipe_skel_fr_mar_xyz)
- update_3d_skel_segments('mp_rHand', mediaPipe_skel_fr_mar_xyz)
- update_3d_skel_segments('mp_lHand', mediaPipe_skel_fr_mar_xyz)
-
- if useDLC:
- update_3d_skel_segments('dlc_pinkBall', dlc_fr_mar_xyz)
- update_3d_skel_segments('dlc_redBall', dlc_fr_mar_xyz)
- update_3d_skel_segments('dlc_greenBall', dlc_fr_mar_xyz)
- update_3d_skel_segments('dlc_wobbleBoard', dlc_fr_mar_xyz)
- update_3d_skel_segments('dlc_wobbleWheel', dlc_fr_mar_xyz)
-
- for bb in range(3):
- thisTailArtist = matplotlib_artist_objs['ball_tails'][bb]
-
- thisTailArtist.set_data((dlc_trajectories[bb][frameNum-ballTailLen:frameNum+1, 0],
- dlc_trajectories[bb][frameNum-ballTailLen:frameNum+1, 1]))
-
- thisTailArtist.set_3d_properties(dlc_trajectories[bb][frameNum-ballTailLen:frameNum+1, 2])
- #dlc data
- marNum = -1
- for thisDotto, thisTraj in zip(dlc_dottos,dlc_trajectories):
- marNum+=1
- # NOTE: there is no .set_data() for 3 dim data...
- thisDotto.set_data(thisTraj[ frameNum, 0:2])
- thisDotto.set_3d_properties(thisTraj[ frameNum, 2])
-
- #Plots the dots!
- #openpose data
- if useOpenPose:
- marNum = -1
- for thisSkelDotto, thisTraj in zip(op_skel_dottos,op_skel_trajectories):
- marNum+=1
- # NOTE: there is no .set_data() for 3 dim data...
- thisSkelDotto.set_data(thisTraj[ frameNum, 0:2])
- thisSkelDotto.set_3d_properties(thisTraj[ frameNum, 2])
-
- #mediapipe data
- if useMediaPipe:
- marNum = -1
- for thisSkelDotto, thisTraj in zip(mp_skel_dottos,mp_skel_trajectories):
- marNum+=1
- # NOTE: there is no .set_data() for 3 dim data...
- thisSkelDotto.set_data(thisTraj[ frameNum, 0:2])
- thisSkelDotto.set_3d_properties(thisTraj[ frameNum, 2])
-
-
-
- #charuco data
- for thisDotto, thisTraj in zip(charuco_dottos,charuco_trajectories):
-
- if frameNum<charuco_trajectories[0].shape[0]:
- thisDotto.set_data(thisTraj[ frameNum, 0:2])
- thisDotto.set_3d_properties(thisTraj[ frameNum, 2])
- else:
- thisDotto.set_color('none')
-
-
-
-
- # function to update the lines for each body segment
- def update_2d_skel_segments(vidNum,key):
- """
- updates the Artist of each body segment with the current frame data.
- """
- split = key.split('_')
- if split[0] == 'op':
- dict_of_segments_idxs = dict_of_openPoseSegmentIdx_dicts[key]
- dict_of_artists = thisVidOpenPoseArtist_dict[key]
- elif split[0] == 'mp':
- dict_of_segments_idxs = dict_of_mediaPipeSegmentIdx_dicts[key]
- dict_of_artists = thisVidMediaPipeArtist_dict[key]
-
-
- for thisItem in dict_of_segments_idxs.items():
- segName = thisItem[0]
- segArtist = dict_of_artists[segName]
-
- if split[0] == 'op':
- xData = openPose_nCams_nFrames_nImgPts_XYC[vidNum, frameNum, dict_of_segments_idxs[segName],0]
- yData = openPose_nCams_nFrames_nImgPts_XYC[vidNum, frameNum, dict_of_segments_idxs[segName],1]
- elif split[0] == 'mp':
- xData = mediaPipe_nCams_nFrames_nImgPts_XYC[vidNum, frameNum, dict_of_segments_idxs[segName],0]
- yData = mediaPipe_nCams_nFrames_nImgPts_XYC[vidNum, frameNum, dict_of_segments_idxs[segName],1]
-
- xDataMasked = np.ma.masked_array(xData, mask=(xData==0))
- yDataMasked = np.ma.masked_array(yData, mask=(xData==0))
- segArtist.set_data(xDataMasked,yDataMasked)
-
-
- #update video frames
- for vidNum, thisVidArtist in enumerate(vidAristList):
- vidCapObjList[vidNum].set(cv2.CAP_PROP_POS_FRAMES, frameNum)
- success, image = vidCapObjList[vidNum].read()
-
- if success:
- thisVidArtist.set_array(cv2.cvtColor(image, cv2.COLOR_BGR2RGB))
- else:
- vidCapObjList[vidNum].set(cv2.CAP_PROP_POS_FRAMES, 0)
- success, image = vidCapObjList[vidNum].read()
-
- if useOpenPose:
- thisVidOpenPoseArtist_dict = list_of_vidOpenPoseArtistdicts[vidNum]
- update_2d_skel_segments(vidNum,'op_body')
- update_2d_skel_segments(vidNum,'op_rHand')
- update_2d_skel_segments(vidNum,'op_lHand')
- update_2d_skel_segments(vidNum,'op_face')
-
- if useMediaPipe:
- thisVidMediaPipeArtist_dict = list_of_vidMediaPipeArtistdicts[vidNum]
- update_2d_skel_segments(vidNum,'mp_body')
- update_2d_skel_segments(vidNum,'mp_rHand')
- update_2d_skel_segments(vidNum,'mp_lHand')
-
- if useDLC: #JSM NOTE - this one won't work, we'll need to fix it the next time we get DLC data
- thisVidDLCArtist[0].set_data( dlcData_nCams_nFrames_nImgPts_XYC[vidNum,frameNum,:,0],
- dlcData_nCams_nFrames_nImgPts_XYC[vidNum,frameNum,:,1],)
-
-
- #shift timeseries xlims along with the frameNum
- xTimeSeriesAx.set_xlim([(frameNum/fps)-timeRange, (frameNum/fps)+timeRange])
- yTimeSeriesAx.set_xlim([(frameNum/fps)-timeRange, (frameNum/fps)+timeRange])
- for thisArtistKey in xCurrTimeArtists:
-
- xCurrTimeArtists[thisArtistKey][0].set_xdata(frameNum/fps)
- yCurrTimeArtists[thisArtistKey][0].set_xdata(frameNum/fps)
- if not thisArtistKey == 'blackLine':
- xCurrTimeArtists[thisArtistKey][0].set_ydata(xCurrTimeYdata[thisArtistKey][frameNum] )
- yCurrTimeArtists[thisArtistKey][0].set_ydata(yCurrTimeYdata[thisArtistKey][frameNum] )
-
- yCurrTimeArtists['frameNumber'].set_x(frameNum/fps+3/fps)
- yCurrTimeArtists['frameNumber'].set_text('Frame# '+ str(frameNum))
- # if recordVid:
- # thisFramePath = str(animationFramePath) + '/'+ str(session.sessionID) + "_frame_" + str(frameNum).zfill(6) + ".png"
- # plt.savefig(thisFramePath)
- # # fig.suptitle("nSessionID: {}, Frame: {} of {}".format(session.sessionID, frameNum, numFrames), fontsize=10)
- # # animSlider.set_val(val=frameNum)
-
- ####
- #### β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ
- #### β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ
- #### β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆ
- #### β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ
- #### β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ
- ####
-
-
- fig = plt.figure(dpi=200)
- plt.ion()
-
-
- ###
- ### β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ
- ### β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ
- ### β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ
- ### β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ
- ### β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ
- ###
- ###
-
- # ax3d = p3.Axes3D(fig)
- ax3d = fig.add_subplot(projection='3d')
- ax3d.set_position([-.065, .28, .7, .7]) # [left, bottom, width, height])
- ax3d.set_xticklabels([])
- ax3d.set_yticklabels([])
- ax3d.set_zticklabels([])
-
- # ax3d.set_xlabel('X')
- # ax3d.set_ylabel('Y')
- # ax3d.set_zlabel('Z')
- # ax3d.set_axis_off()
-
-
- ax3d.tick_params(length=0) # WHY DOESNT THIS WORK? I HATE THOSE TICK MARKS >:(
-
- smoothData=True
- smoothWinLength = 5
- smoothOrder = 3
-
- if useOpenPose:
- try:
- openPose_skel_fr_mar_xyz = np.load(session.dataArrayPath / 'openPoseSkel_3d.npy')
- openPose_nCams_nFrames_nImgPts_XYC = np.load(session.dataArrayPath / 'openPoseData_2d.npy')
- except:
- print('No openPose data found.')
-
- if smoothData:
- for dim in range(openPose_skel_fr_mar_xyz.shape[2]):
- for mm in range(openPose_skel_fr_mar_xyz.shape[1]):
- openPose_skel_fr_mar_xyz[:,mm,dim] = savgol_filter(openPose_skel_fr_mar_xyz[:,mm,dim], smoothWinLength, smoothOrder)
-
- if useMediaPipe:
- try:
- mediaPipe_skel_fr_mar_xyz = np.load(session.dataArrayPath / 'mediaPipeSkel_3d.npy')
- mediaPipe_nCams_nFrames_nImgPts_XYC = np.load(session.dataArrayPath / 'mediaPipeData_2d.npy')
- except:
- print('No mediaPipe data found.')
-
- if smoothData:
- for dim in range(mediaPipe_skel_fr_mar_xyz.shape[2]):
- for mm in range(mediaPipe_skel_fr_mar_xyz.shape[1]):
- mediaPipe_skel_fr_mar_xyz[:,mm,dim] = savgol_filter(mediaPipe_skel_fr_mar_xyz[:,mm,dim], smoothWinLength, smoothOrder)
-
- try:
- charuco_fr_mar_xyz = np.load(session.dataArrayPath / 'charuco_3d_points.npy')
- except:
- console.warning('No charuco data found')
-
-
-
-
- figure_data = dict()
- if useOpenPose:
- figure_data['openPose_skel_trajectories|mar|fr_dim'] = [openPose_skel_fr_mar_xyz[:,markerNum,:] for markerNum in range(openPose_skel_fr_mar_xyz.shape[1])]
- figure_data['openPose_skel_fr_mar_xyz'] = openPose_skel_fr_mar_xyz
-
- dict_of_openPoseSegmentIdx_dicts, dict_of_op_skel_lineColor = formatOpenPoseStickIndices() #these will help us draw body and hands stick figures
-
-
- if useMediaPipe:
- mediaPipe_trajectories = [mediaPipe_skel_fr_mar_xyz[:,markerNum,:] for markerNum in range(mediaPipe_skel_fr_mar_xyz.shape[1])]
- figure_data['mediaPipe_skel_trajectories|mar|fr_dim'] = [mediaPipe_skel_fr_mar_xyz[:,markerNum,:] for markerNum in range(mediaPipe_skel_fr_mar_xyz.shape[1])]
- figure_data['mediaPipe_skel_fr_mar_xyz'] = mediaPipe_skel_fr_mar_xyz
-
- dict_of_mediaPipeSegmentIdx_dicts, dict_of_mp_skel_lineColor = formatMediaPipeStickIndices() #these will help us draw body and hands stick figures
-
-
- charuco_trajectories = [charuco_fr_mar_xyz[:,markerNum,:] for markerNum in range(charuco_fr_mar_xyz.shape[1])]
- figure_data['charuco_trajectories|mar|fr_dim'] = charuco_trajectories
- figure_data['charuco_fr_mar_xyz'] = charuco_fr_mar_xyz
-
-
- if useDLC:
- dlc_fr_mar_xyz = np.load(session.dataArrayPath / "deepLabCut_3d.npy")
- dlcData_nCams_nFrames_nImgPts_XYC = np.load(session.dataArrayPath / "deepLabCutData_2d.npy")
-
- for mm in range(dlc_fr_mar_xyz.shape[1]):
- for dim in range(dlc_fr_mar_xyz.shape[2]):
- dlc_fr_mar_xyz[:,mm,dim] = savgol_filter(dlc_fr_mar_xyz[:,mm,dim], 11, 3)
-
- ballTailLen = 6
- if ballTailLen > startFrame:
- startFrame = ballTailLen+1 #gotta do this, or the tail will index negative frames (without requiring annoying checks later)
-
- dlc_trajectories = [dlc_fr_mar_xyz[:,markerNum,:] for markerNum in range(dlc_fr_mar_xyz.shape[1])]
- figure_data['dlc_trajectories|mar|fr_dim'] = dlc_trajectories
- figure_data['dlc_fr_mar_xyz'] = dlc_fr_mar_xyz
-
-
-
-
- def build_3d_segment_artist_dict(data_fr_mar_xyz,
- dict_of_list_of_segment_idxs,
- segColor = 'k',
- lineWidth = 1,
- lineStyle = '-',
- markerType = None,
- marSize = 12,
- markerEdgeColor = 'k',):
- """
- Builds a dictionary of line artists for each 3D body segment.
- """
- segNames = list(dict_of_list_of_segment_idxs)
-
-
-
- dict_of_artist_objects = dict()
- for segNum, segName in enumerate(segNames):
-
- #determine color of segment, based on class of 'segColor' input
- if isinstance(segColor, str):
- thisRGBA = segColor
- elif isinstance(segColor, np.ndarray):
- thisRGBA = segColor
- elif isinstance(segColor, dict):
- thisRGBA = segColor[segName]
- elif isinstance(segColor, list):
- try:
- thisRGBA = segColor[segNum]
- except:
- print('Not enough colors provided, using Black instead')
- thisRGBA = 'k'
- else:
- thisRGBA = 'k'
-
- if isinstance(segName, str):
- idxsOG = dict_of_list_of_segment_idxs[segName]
- else:
- idxsOG
-
- if isinstance(idxsOG, int) or isinstance(idxsOG, float):
- idxs = [idxsOG]
- elif isinstance(idxsOG, dict):
- idxs = idxsOG[0]
- else:
- idxs = idxsOG.copy()
-
-
- dict_of_artist_objects[segName] = ax3d.plot(
- data_fr_mar_xyz[startFrame, idxs ,0],
- data_fr_mar_xyz[startFrame, idxs ,1],
- data_fr_mar_xyz[startFrame, idxs ,2],
- linestyle=lineStyle,
- linewidth=lineWidth,
- markerSize = marSize,
- marker = markerType,
- color = thisRGBA,
- markeredgecolor = markerEdgeColor,
- )[0]
- return dict_of_artist_objects
-
-
-
- matplotlib_artist_objs = dict()
-
- if useOpenPose:
- matplotlib_artist_objs['op_body'] = build_3d_segment_artist_dict(openPose_skel_fr_mar_xyz, dict_of_openPoseSegmentIdx_dicts['op_body'], segColor = dict_of_op_skel_lineColor)
- matplotlib_artist_objs['op_rHand'] = build_3d_segment_artist_dict(openPose_skel_fr_mar_xyz, dict_of_openPoseSegmentIdx_dicts['op_rHand'], segColor=np.append(humon_red, 1), markerType='.', markerEdgeColor = humon_red, lineWidth=1, marSize = 2)
- matplotlib_artist_objs['op_lHand'] = build_3d_segment_artist_dict(openPose_skel_fr_mar_xyz, dict_of_openPoseSegmentIdx_dicts['op_lHand'], segColor=np.append(humon_blue, 1), markerType='.', markerEdgeColor = humon_blue, lineWidth=1, marSize = 2)
- matplotlib_artist_objs['op_face'] = build_3d_segment_artist_dict(openPose_skel_fr_mar_xyz, dict_of_openPoseSegmentIdx_dicts['op_face'], segColor='k', lineWidth=.5)
-
- if useMediaPipe:
- matplotlib_artist_objs['mp_body'] = build_3d_segment_artist_dict(mediaPipe_skel_fr_mar_xyz, dict_of_mediaPipeSegmentIdx_dicts['mp_body'], segColor = dict_of_mp_skel_lineColor)
- matplotlib_artist_objs['mp_rHand'] = build_3d_segment_artist_dict(mediaPipe_skel_fr_mar_xyz, dict_of_mediaPipeSegmentIdx_dicts['mp_rHand'], segColor=np.append(humon_red, 1), markerType='.', markerEdgeColor = humon_red, lineWidth=1, marSize = 2)
- matplotlib_artist_objs['mp_lHand'] = build_3d_segment_artist_dict(mediaPipe_skel_fr_mar_xyz, dict_of_mediaPipeSegmentIdx_dicts['mp_lHand'], segColor=np.append(humon_blue, 1), markerType='.', markerEdgeColor = humon_blue, lineWidth=1, marSize = 2)
-
- if useDLC:
- dict_of_dlcSegmentIdx_dicts = dict()
- dict_of_dlcSegmentIdx_dicts['pinkBall'] = {'pinkBall': [0]}
- dict_of_dlcSegmentIdx_dicts['greenBall'] = {'greenBall': [1]}
- dict_of_dlcSegmentIdx_dicts['redBall'] = {'redBall': [2]}
- dict_of_dlcSegmentIdx_dicts['wobbleBoard'] = {'wobbleboard':[3,4,5,6,3,7,5,4,7,6]}
- dict_of_dlcSegmentIdx_dicts['wobbleWheel'] = {'wobbleWheel':[8,9]}
-
-
- ballColor = ['darkviolet', 'forestgreen', 'xkcd:goldenrod']
- matplotlib_artist_objs['pinkBall'] = build_3d_segment_artist_dict(dlc_fr_mar_xyz, dict_of_dlcSegmentIdx_dicts['pinkBall'], segColor=ballColor[0], markerType = 'o', marSize = 6, markerEdgeColor = 'indigo')
- matplotlib_artist_objs['redBall'] = build_3d_segment_artist_dict(dlc_fr_mar_xyz, dict_of_dlcSegmentIdx_dicts['redBall'], segColor=ballColor[2], markerType = 'o', marSize = 6, markerEdgeColor ='orangered')
- matplotlib_artist_objs['greenBall'] = build_3d_segment_artist_dict(dlc_fr_mar_xyz, dict_of_dlcSegmentIdx_dicts['greenBall'], segColor=ballColor[1], markerType = 'o', marSize = 6, markerEdgeColor ='darkgreen')
-
- matplotlib_artist_objs['wobbleBoard'] = build_3d_segment_artist_dict(dlc_fr_mar_xyz, dict_of_dlcSegmentIdx_dicts['wobbleBoard'], segColor='k', lineWidth=1)
- matplotlib_artist_objs['wobbleWheel'] = build_3d_segment_artist_dict(dlc_fr_mar_xyz, dict_of_dlcSegmentIdx_dicts['wobbleWheel'], segColor='k', lineWidth=1)
-
- if useOpenPose:
- op_skel_dottos = []
- for mm in range(67): #getcher dottos off my face!
- thisTraj = openPose_skel_fr_mar_xyz[:, mm, :]
- if mm==15:
- col = 'r'
- markerSize = 2
- elif mm == 16:
- col = 'b'
- markerSize = 2
- else:
- col = 'k'
- markerSize = 1
-
- thisDotto =ax3d.plot(thisTraj[0, 0:1], thisTraj[1, 0:1], thisTraj[2, 0:1][0],'.', markersize=markerSize, color = col)
- op_skel_dottos.append(thisDotto[0])
-
- matplotlib_artist_objs['op_skel_dottos'] = op_skel_dottos
-
- if useMediaPipe:
- matplotlib_artist_objs['mp_skel_dottos'] = [ax3d.plot(thisTraj[0, 0:1], thisTraj[1, 0:1], thisTraj[2, 0:1],'m.', markersize=1)[0] for thisTraj in mediaPipe_trajectories]
-
- matplotlib_artist_objs['charuco_dottos'] = [ax3d.plot(thisTraj[0, 0:1], thisTraj[1, 0:1], thisTraj[2, 0:1],'m.', markersize=1)[0] for thisTraj in charuco_trajectories]
-
-
- if useDLC:
- matplotlib_artist_objs['dlc_dottos'] = [ax3d.plot(thisTraj[0, 0:1], thisTraj[1, 0:1], thisTraj[2, 0:1],'b.', markersize=1)[0] for thisTraj in dlc_trajectories]
-
- matplotlib_artist_objs['ball_tails'] = [ax3d.plot(
- dlc_trajectories[bb][startFrame-ballTailLen:startFrame, 0],
- dlc_trajectories[bb][startFrame-ballTailLen:startFrame, 1],
- dlc_trajectories[bb][startFrame-ballTailLen:startFrame, 2],
- '-', color=ballColor[bb])[0] for bb in range(3)]
-
-
- if useOpenPose:
- numFrames = openPose_skel_fr_mar_xyz.shape[0]
- mx = np.nanmean(openPose_skel_fr_mar_xyz[int(numFrames/2),:,0])
- my = np.nanmean(openPose_skel_fr_mar_xyz[int(numFrames/2),:,1])
- mz = np.nanmean(openPose_skel_fr_mar_xyz[int(numFrames/2),:,2])
-
- if useMediaPipe:
- numFrames = mediaPipe_skel_fr_mar_xyz.shape[0]
- mx = np.nanmean(mediaPipe_skel_fr_mar_xyz[int(numFrames/2),:,0])
- my = np.nanmean(mediaPipe_skel_fr_mar_xyz[int(numFrames/2),:,1])
- mz = np.nanmean(mediaPipe_skel_fr_mar_xyz[int(numFrames/2),:,2])
-
-
- if np.isnan(mx) or np.isnan(my) or np.isnan(mz):
- mx = 0
- my = 0
- mz = 0
- # groundX = np.arange(mx-100,mx+100)
- # groundZ = np.arange(my-100,my+100)
- # groundXX, groundZZ = np.meshgrid(groundX, groundZ)
- # groundYY = np.zeros_like(groundXX)
- # groundMesh = ax3d.plot_surface(groundXX, groundZZ, groundYY, color='k', alpha=.5)
-
- axRange = 1000#session.board.square_length * 10
-
- # Setting the axes properties
- ax3d.set_xlim3d([mx-axRange, mx+axRange])
- ax3d.set_ylim3d([my-axRange, my+axRange])
- ax3d.set_zlim3d([mz-axRange, mz+axRange])
-
- tit1 = fig.text(.5, .96, "The FreeMoCap Project", fontsize=15, horizontalalignment='center')
- tit2 = fig.text(.5, .92, "Session: {}".format(session.sessionID), fontsize=8, horizontalalignment='center')
-
-
-
- ax3d.view_init(azim=azimuth, elev=elevation)
-
-
-
- ###
- ###
- ### β–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ
- ### β–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ
- ### β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ
- ### β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ
- ### β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ
- ###
- ###
-
-
- syncedVidPathListAll = list(sorted(session.syncedVidPath.glob('*.mp4')))
- numVids = len(syncedVidPathListAll)
-
- syncedVidPathList = syncedVidPathListAll.copy()
-
- vidAxesList = []
- vidAristList = []
- vidCapObjList = []
-
- list_of_vidOpenPoseArtistdicts = []
- list_of_vidMediaPipeArtistdicts = []
-
- if useDLC: vidDLCArtistList = []
-
- def build_2d_segment_artist_dict(vidNum, data_nCams_nFrames_nImgPts_XYC, dict_of_list_of_segment_idxs, segColor = 'k', lineWidth = 1, lineStyle = '-'):
- """
- Builds a dictionary of line artists for each body 2d segment.
- """
- segNames = list(dict_of_list_of_segment_idxs)
-
- dict_of_artist_objects = dict()
- for segNum, segName in enumerate(segNames):
-
- #determine color of segment, based on class of 'segColor' input
- if isinstance(segColor, str):
- thisRGBA = segColor
- elif isinstance(segColor, np.ndarray):
- thisRGBA = segColor
- elif isinstance(segColor, dict):
- thisRGBA = segColor[segName].copy()
- thisRGBA[-1] = .75
- elif isinstance(segColor, list):
- try:
- thisRGBA = segColor[segNum]
- except:
- print('Not enough colors provided, using Black instead')
- thisRGBA = 'k'
- else:
- thisRGBA = 'k'
-
- xData = data_nCams_nFrames_nImgPts_XYC[vidNum, startFrame, dict_of_list_of_segment_idxs[segName],0]
- yData = data_nCams_nFrames_nImgPts_XYC[vidNum, startFrame, dict_of_list_of_segment_idxs[segName],1]
-
- # #make NaN's invisible (i thought they already would be but???!!!!)
- # thisRGBAall = np.tile(thisRGBA,(len(xData),1))
- # thisRGBAall[np.isnan(xData),3] = 0
-
- xDataMasked = np.ma.masked_where(xData, np.isnan(xData))
- yDataMasked = np.ma.masked_where(yData, np.isnan(yData))
-
- dict_of_artist_objects[segName] = thisVidAxis.plot(
- xDataMasked,
- yDataMasked,
- linestyle=lineStyle,
- linewidth=lineWidth,
- color = thisRGBA,
- )[0]
- return dict_of_artist_objects
-
- # vidImageGrid = ImageGrid(fig, [.45, 0.05, .54, .9], nrows_ncols = (2,2), axes_pad = 0.1) # https://matplotlib.org/stable/gallery/axes_grid1/simple_axesgrid.html
- if numVids < 4:
- numRows = numVids
- numCols = 1
- else:
- numRows = int(np.ceil(numVids/2))
- numCols = 2
-
-
- vidAxGridSpec = fig.add_gridspec(numRows, numCols, left=.55, bottom=.025, right=.9, top=.9, wspace=.1, hspace=.1)
-
-
- for thisVidNum, thisVidPath in enumerate(syncedVidPathList):
- #make subplot for figure (and set position)
-
- if numVids < 4:
- thisVidAxis = fig.add_subplot(vidAxGridSpec[thisVidNum])
- elif numVids %2 > 0: #if odd number videos plot the first vid across 2 spots
- if thisVidNum==0:
- thisVidAxis = fig.add_subplot(vidAxGridSpec[0,:])
- else:
- thisVidAxis = fig.add_subplot(vidAxGridSpec[thisVidNum+1])
- else:
- thisVidAxis = fig.add_subplot(vidAxGridSpec[thisVidNum])
-
-
- thisVidAxis.set_axis_off()
-
- vidAxesList.append(thisVidAxis)
-
- #create video capture object
- thisVidCap = cv2.VideoCapture(str(thisVidPath))
-
-
- #create artist object for each video
- success, image = thisVidCap.read()
-
- assert success==True, "{} - failed to load an image".format(thisVidPath.stem) #make sure we have a frame
-
- vidAristList.append(thisVidAxis.imshow(cv2.cvtColor(image, cv2.COLOR_BGR2RGB)))
- vidCapObjList.append(thisVidCap)
-
-
-
- if useOpenPose:
- vidOpenPoseArtist_dict = dict()
- vidOpenPoseArtist_dict['op_body'] = build_2d_segment_artist_dict(thisVidNum, openPose_nCams_nFrames_nImgPts_XYC, dict_of_openPoseSegmentIdx_dicts['op_body'], segColor = dict_of_op_skel_lineColor)
- vidOpenPoseArtist_dict['op_rHand'] = build_2d_segment_artist_dict(thisVidNum, openPose_nCams_nFrames_nImgPts_XYC, dict_of_openPoseSegmentIdx_dicts['op_rHand'], segColor=np.append(humon_red, .75), lineWidth=.5)
- vidOpenPoseArtist_dict['op_lHand'] = build_2d_segment_artist_dict(thisVidNum, openPose_nCams_nFrames_nImgPts_XYC, dict_of_openPoseSegmentIdx_dicts['op_lHand'], segColor=np.append(humon_blue, .75), lineWidth=.5)
- vidOpenPoseArtist_dict['op_face'] = build_2d_segment_artist_dict(thisVidNum, openPose_nCams_nFrames_nImgPts_XYC, dict_of_openPoseSegmentIdx_dicts['op_face'], segColor = np.array([1.,1.,1.,1]), lineWidth=.25)
- list_of_vidOpenPoseArtistdicts.append(vidOpenPoseArtist_dict)
-
- if useMediaPipe:
- vidMediaPipeArtist_dict = dict()
- vidMediaPipeArtist_dict['mp_body'] = build_2d_segment_artist_dict(thisVidNum, mediaPipe_nCams_nFrames_nImgPts_XYC, dict_of_mediaPipeSegmentIdx_dicts['mp_body'], segColor = 'g')
- vidMediaPipeArtist_dict['mp_rHand'] = build_2d_segment_artist_dict(thisVidNum, mediaPipe_nCams_nFrames_nImgPts_XYC, dict_of_mediaPipeSegmentIdx_dicts['mp_rHand'], segColor=np.append(humon_red, .75), lineWidth=.5)
- vidMediaPipeArtist_dict['mp_lHand'] = build_2d_segment_artist_dict(thisVidNum, mediaPipe_nCams_nFrames_nImgPts_XYC, dict_of_mediaPipeSegmentIdx_dicts['mp_lHand'], segColor=np.append(humon_blue, .75), lineWidth=.5)
- list_of_vidMediaPipeArtistdicts.append(vidMediaPipeArtist_dict)
-
-
- if useDLC:
-
- vidDLCArtistList.append(thisVidAxis.plot(
- dlcData_nCams_nFrames_nImgPts_XYC[thisVidNum,startFrame,:,0],
- dlcData_nCams_nFrames_nImgPts_XYC[thisVidNum,startFrame,:,1],
- linestyle='none',
- marker = '.',
- markersize = 1,
- color='w',
- markerfacecolor='none' ))
-
- ###
- ###
- ### β–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ
- ### β–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ
- ### β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ
- ### β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ
- ### β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ
- ###
- ###
-
-
- fps=30 #NOTE - This should be saved in the session Class some how
- time = np.arange(0, numFrames)/fps
- if useMediaPipe:
- rHandIdx = 20
- lHandIdx = 19
- rHandX = mediaPipe_skel_fr_mar_xyz[:,rHandIdx,0]/1000 #convert mm to meters
- rHandY = -mediaPipe_skel_fr_mar_xyz[:,rHandIdx,1]/1000
- lHandX = mediaPipe_skel_fr_mar_xyz[:,lHandIdx,0]/1000
- lHandY = -mediaPipe_skel_fr_mar_xyz[:,lHandIdx,1]/1000
-
- if useOpenPose:
- rHandIdx = 4
- lHandIdx = 7
- rHandX = openPose_skel_fr_mar_xyz[:,rHandIdx,0]/1000 #convert mm to meters
- rHandY = -openPose_skel_fr_mar_xyz[:,rHandIdx,1]/1000
- lHandX = openPose_skel_fr_mar_xyz[:,lHandIdx,0]/1000
- lHandY = -openPose_skel_fr_mar_xyz[:,lHandIdx,1]/1000
-
-
- linePlotWidth = .45
- linePlotHeight = .14
-
- yTimeSeriesAx = fig.add_subplot(position=[.07, .225, linePlotWidth, linePlotHeight])
- yTimeSeriesAx.set_title('Hand Position vs Time', fontsize = 7, pad=2)
-
- yTimeSeriesAx.plot(time, rHandY, color=humon_red, linewidth=.75, label='Right Hand')
- yTimeSeriesAx.plot(time, lHandY, color=humon_blue, linewidth=.75, label='Left Hand')
-
- timeRange = 3
- ylimRange = .6
-
- yCurrTimeArtists = dict()
- yCurrTimeYdata = dict()
- yCurrTimeArtists['blackLine'] = yTimeSeriesAx.plot([startFrame/fps, startFrame/fps], [-ylimRange, ylimRange*2], color='k', linewidth=1)
-
- yCurrTimeArtists['rHandDot'] = yTimeSeriesAx.plot([startFrame/fps], [rHandY[startFrame]], markeredgecolor=humon_red, markerfacecolor = 'k',marker='o', markersize=3)
- yCurrTimeYdata['rHandDot'] = rHandY
- yCurrTimeArtists['lHandDot'] = yTimeSeriesAx.plot([startFrame/fps], [lHandY[startFrame]], markeredgecolor=humon_blue, markerfacecolor = 'k', marker='o', markersize=3)
- yCurrTimeYdata['lHandDot'] = lHandY
-
-
- yCurrTimeArtists['frameNumber'] = yTimeSeriesAx.text(startFrame/fps+3/fps, ylimRange*.7, "Frame# " + str(startFrame), fontsize=6)
-
- yTimeSeriesAx.tick_params(labelsize=6, direction='in', width=.5)
- yTimeSeriesAx.tick_params( pad=2)
-
-
- yTimeSeriesAx.set_ylabel('Vertical (m)', fontsize=7, labelpad=3)
- yTimeSeriesAx.set_ylim([-ylimRange, ylimRange])
- yTimeSeriesAx.set_xlim([(startFrame/fps)-timeRange, (startFrame/fps)+timeRange])
-
-
-
- for axis in ['top','bottom','left','right']:
- yTimeSeriesAx.spines[axis].set_linewidth(0.5)
-
-
-
- yTimeSeriesAx.legend(loc='upper left', fontsize=6)
-
-
-
- xTimeSeriesAx = fig.add_subplot(position=[.07, 0.05, linePlotWidth, linePlotHeight])
-
- xTimeSeriesAx.plot(time, rHandX, color=humon_red, linewidth=.75, label='Right Hand')
- xTimeSeriesAx.plot(time, lHandX, color=humon_blue, linewidth=.75, label='Left Hand')
-
-
-
- xCurrTimeArtists = dict()
- xCurrTimeYdata = dict()
- xCurrTimeArtists['blackLine'] = xTimeSeriesAx.plot([startFrame/fps, startFrame/fps], [-ylimRange, ylimRange], color='k', linewidth=1)
- xCurrTimeArtists['rHandDot'] = xTimeSeriesAx.plot([startFrame/fps], [rHandX[startFrame]], markeredgecolor=humon_red, markerfacecolor = 'k',marker='o', markersize=3)
- xCurrTimeYdata['rHandDot'] = rHandX
- xCurrTimeArtists['lHandDot'] = xTimeSeriesAx.plot([startFrame/fps], [lHandX[startFrame]], markeredgecolor=humon_blue, markerfacecolor = 'k', marker='o', markersize=3)
- xCurrTimeYdata['lHandDot'] = lHandX
-
-
-
- xTimeSeriesAx.tick_params(labelsize=6, direction='in', width=.5)
- xTimeSeriesAx.tick_params( pad=2)
-
- xTimeSeriesAx.set_ylabel('Left/Right (m)', fontsize=7, labelpad=0)
- xTimeSeriesAx.set_xlabel('Time(sec)', fontsize=8, labelpad=0)
-
- xTimeSeriesAx.set_ylim([-ylimRange, ylimRange])
-
- xTimeSeriesAx.set_xlim([(startFrame/fps)-timeRange, (startFrame/fps)+timeRange])
-
-
- for axis in ['top','bottom','left','right']:
- xTimeSeriesAx.spines[axis].set_linewidth(0.5)
-
-
-
- # #slider
- # axControls = fig.add_subplot(2,1,2)
- # axControls.set_position([0.25, 0.01, 0.6, 0.05])
- # animSlider = Slider(
- # ax=axControls,
- # label="FrameNum",
- # valmin=10,
- # valmax=numFrames,
- # valinit=10,
- # orientation="horizontal"
- # )
-
- # thisVidAxis.text(-565,1440, 'Music - artist: Neon Exdeath, song: Meowmaline, album: Jewel Tones',color=humon_green, fontsize=6)
- thisVidAxis.text(0,thisVidCap.get(cv2.CAP_PROP_FRAME_HEIGHT)*1.06, 'github.com/jonmatthis/freemocap || freemocap.org',color=humon_green, fontsize=6)
-
- logoAx = fig.add_subplot(position=[.85, .85, .15, .15])
- logoIm = cv2.imread(r'logo\fmc-logo-black-border-white-bkgd.png') #JSM NOTE - THis doesn't work, but SOMETIMES IT DOES?!
- if logoIm is not None: logoAx.imshow(cv2.cvtColor(logoIm, cv2.COLOR_BGR2RGB))
- logoAx.axis('off')
-
- # if recordVid:
- # animationFramePath = session.sessionPath / "animationFrames"
- # animationFramePath.mkdir(parents=True, exist_ok=True)
-
- # Creating the Animation object
- line_animation = animation.FuncAnimation(fig, update_figure, range(startFrame,numFrames), fargs=(),
- interval=1, blit=False)
-
-
-
- if recordVid:
- # vidSavePath = '{}_animVid.mp4'.format(str(session.sessionPath / session.sessionID))
- gifSavePath = '{}_animVid.gif'.format(str(session.sessionPath / session.sessionID)) #NOTE - saving as a gif first then converting to MP4, because saving directly to MP4 requires users to install ffmpeg (independently of the pip install)
- with console.status('Saving animation for {}'.format(session.sessionID)):
- # Writer = animation.writers['ffmpeg']
- Writer = animation.writers['pillow']
- writer = Writer(fps=fps, metadata=dict(artist='FreeMoCap'))#, bitrate=1800)
- line_animation.save(gifSavePath, writer = writer)
- # Writer = animation.FFMpegWriter(fps=30, metadata=dict(artist='FreeMoCap', comment=session.sessionID), bitrate=1800)
- # vidSavePath = '{}_outVid.mp4'.format(str(session.sessionPath / session.sessionID))
- # Writer.saving(fig = fig, outfile=vidSavePath, dpi=150)
-
- gif_filepath = mp.VideoFileClip(gifSavePath)
- gif_filepath.write_videofile(gifSavePath.replace('.gif','.mp4'))
- os.remove(gifSavePath)
-
-
- try:
- if showAnimation:
- with console.status('Playing Skeleton animation! Close the `matplotlib` window to continue...'):
- plt.pause(0.1)
- plt.draw()
- except:
- pass
-
-
-
-
-
-
- ###
- ###
- ### β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ
- ### β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ
- ### β–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ
- ### β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ
- ### β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ
- ###
- ###
-def formatOpenPoseStickIndices():
- """
- generate dictionary of arrays, each containing the 'connect-the-dots' order to draw a given body segment
-
- returns:
- openPoseBodySegmentIds= a dictionary of arrays containing indices of individual body segments (Note, a lot of markerless mocap comp sci types like to say 'pose' instead of 'body'. They also use 'pose' to refer to camera 6 DoF position sometimes. Comp sci is frustrating like that lol)
- openPoseHandIds = a dictionary of arrays containing indices of individual hand segments, along with offset to know where to start in the 'skel_fr_mar_xyz.shape[1]' part of the array
- dict_of_op_skel_lineColor = a dictionary of arrays, each containing the color (RGBA) to use for a given body segment
- """
- dict_of_openPoseSegmentIdx_dicts = dict()
-
- #make body dictionary
- openPoseBodySegmentIds = dict()
- openPoseBodySegmentIds['op_head'] = [17, 15, 0, 1,0, 16, 18, ]
- openPoseBodySegmentIds['op_spine'] = [1,8,5,1, 2, 12, 8, 9, 5, 1, 2, 8]
- openPoseBodySegmentIds['op_rArm'] = [1, 2, 3, 4, ]
- openPoseBodySegmentIds['op_lArm'] = [1, 5, 6, 7, ]
- openPoseBodySegmentIds['op_rLeg'] = [8, 9, 10, 11, 22, 23, 11, 24, ]
- openPoseBodySegmentIds['op_lLeg'] = [8,12, 13, 14, 19, 20, 14, 21,]
- dict_of_openPoseSegmentIdx_dicts['op_body'] = openPoseBodySegmentIds
-
-
- #make colors dictionary
- openPoseBodyColor = np.array([50, 89, 0])/255
- openPoseRightColor = np.array([230, 50, 0])/255
- openPoseLeftColor = np.array([0, 50, 230])/255
-
- dict_of_op_skel_lineColor = dict()
- dict_of_op_skel_lineColor['op_head'] = np.append(openPoseBodyColor, 0.5)
- dict_of_op_skel_lineColor['op_spine'] = np.append(openPoseBodyColor, 1)
- dict_of_op_skel_lineColor['op_rArm'] = np.append(openPoseRightColor, 1)
- dict_of_op_skel_lineColor['op_lArm'] = np.append(openPoseLeftColor, 1)
- dict_of_op_skel_lineColor['op_rLeg'] = np.append(openPoseRightColor, 1)
- dict_of_op_skel_lineColor['op_lLeg'] = np.append(openPoseLeftColor, 1)
-
-
- # Make some handy maps ;D
- openPoseHandIds = dict()
- rHandIDstart = 25
- lHandIDstart = rHandIDstart + 21
-
- openPoseHandIds['op_thumb'] = np.array([0, 1, 2, 3, 4, ])
- openPoseHandIds['op_index'] = np.array([0, 5, 6, 7, 8, ])
- openPoseHandIds['op_bird']= np.array([0, 9, 10, 11, 12, ])
- openPoseHandIds['op_ring']= np.array([0, 13, 14, 15, 16, ])
- openPoseHandIds['op_pinky'] = np.array([0, 17, 18, 19, 20, ])
-
-
- rHand_dict = copy.deepcopy(openPoseHandIds.copy()) #copy.deepcopy() is necessary to make sure the dicts are independent of each other
- lHand_dict = copy.deepcopy(rHand_dict)
-
- for key in rHand_dict:
- rHand_dict[key] += rHandIDstart
- lHand_dict[key] += lHandIDstart
-
- dict_of_openPoseSegmentIdx_dicts['op_rHand'] = rHand_dict
- dict_of_openPoseSegmentIdx_dicts['op_lHand'] = lHand_dict
-
-
- #how to face --> :D <--
- openPoseFaceIDs = dict()
- faceIDStart = 67
- #define face parts
- openPoseFaceIDs['op_jaw'] = np.arange(0,16) + faceIDStart
- openPoseFaceIDs['op_rBrow'] = np.arange(17,21) + faceIDStart
- openPoseFaceIDs['op_lBrow'] = np.arange(22,26) + faceIDStart
- openPoseFaceIDs['op_noseRidge'] = np.arange(27,30) + faceIDStart
- openPoseFaceIDs['op_noseBot'] = np.arange(31,35) + faceIDStart
- openPoseFaceIDs['op_rEye'] = np.concatenate((np.arange(36,41), [36])) + faceIDStart
- openPoseFaceIDs['op_lEye'] = np.concatenate((np.arange(42,47), [42])) + faceIDStart
- openPoseFaceIDs['op_upperLip'] = np.concatenate((np.arange(48,54), np.flip(np.arange(60, 64)), [48])) + faceIDStart
- openPoseFaceIDs['op_lowerLip'] = np.concatenate(([60], np.arange(64,67), np.arange(54, 59), [48], [60])) + faceIDStart
- openPoseFaceIDs['op_rPupil'] = np.array([68]) + faceIDStart
- openPoseFaceIDs['op_lPupil'] = np.array([69]) + faceIDStart #nice
-
- dict_of_openPoseSegmentIdx_dicts['op_face'] = openPoseFaceIDs
-
- return dict_of_openPoseSegmentIdx_dicts, dict_of_op_skel_lineColor
-
-
-
-###
-### β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ
-### β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ
-### β–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ
-### β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ
-### β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ
-###
-###
-def formatMediaPipeStickIndices():
- """
- generate dictionary of arrays, each containing the 'connect-the-dots' order to draw a given body segment
-
- returns:
- mediaPipeBodySegmentIds= a dictionary of arrays containing indices of individual body segments (Note, a lot of markerless mocap comp sci types like to say 'pose' instead of 'body'. They also use 'pose' to refer to camera 6 DoF position sometimes. Comp sci is frustrating like that lol)
- mediaPipeHandIds = a dictionary of arrays containing indices of individual hand segments, along with offset to know where to start in the 'skel_fr_mar_xyz.shape[1]' part of the array
- dict_of_mp_skel_lineColor = a dictionary of arrays, each containing the color (RGBA) to use for a given body segment
- """
- dict_of_mediaPipeSegmentIdx_dicts = dict()
-
- #make body dictionary
- mediaPipeBodySegmentIds = dict()
- mediaPipeBodySegmentIds['mp_head'] = [8, 6, 5, 4, 0, 10, 9, 0, 1, 2, 3, 7 ]
- mediaPipeBodySegmentIds['mp_tors'] = [12, 11, 24, 23, 12]
- mediaPipeBodySegmentIds['mp_rArm'] = [12, 14, 16, 18, 20, 16, 22 ]
- mediaPipeBodySegmentIds['mp_lArm'] = [11, 13, 15, 17, 19, 15, 21]
- mediaPipeBodySegmentIds['mp_rLeg'] = [24, 26, 28, 30, 32, 28, ]
- mediaPipeBodySegmentIds['mp_lLeg'] = [23, 25, 27, 29, 31, 27, ]
- dict_of_mediaPipeSegmentIdx_dicts['mp_body'] = mediaPipeBodySegmentIds
-
- #make colors dictionary
- mediaPipeBodyColor = np.array([125,106,0])/255
- mediaPipeRightColor = np.array([230, 0, 169])/255
- mediaPipeLeftColor = np.array([0, 176, 176])/255
- dict_of_mp_skel_lineColor = dict()
-
- dict_of_mp_skel_lineColor['mp_head'] = np.append(mediaPipeBodyColor, .5)
- dict_of_mp_skel_lineColor['mp_tors'] = np.append(mediaPipeBodyColor, 1)
- dict_of_mp_skel_lineColor['mp_rArm'] = np.append(mediaPipeRightColor, 1)
- dict_of_mp_skel_lineColor['mp_lArm'] = np.append(mediaPipeLeftColor, 1)
- dict_of_mp_skel_lineColor['mp_rLeg'] = np.append(mediaPipeRightColor, 1)
- dict_of_mp_skel_lineColor['mp_lLeg'] = np.append(mediaPipeLeftColor, 1)
-
-
- # Make some handy maps ;D
- mediaPipeHandIds = dict()
- rHandIDstart = 33
- lHandIDstart = rHandIDstart + 21
-
- mediaPipeHandIds['mp_thumb'] = np.array([0, 1, 2, 3, 4, ])
- mediaPipeHandIds['mp_index'] = np.array([0, 5, 6, 7, 8, ])
- mediaPipeHandIds['mp_bird']= np.array([0, 9, 10, 11, 12, ])
- mediaPipeHandIds['mp_ring']= np.array([0, 13, 14, 15, 16, ])
- mediaPipeHandIds['mp_pinky'] = np.array([0, 17, 18, 19, 20, ])
-
-
- rHand_dict = copy.deepcopy(mediaPipeHandIds.copy()) #copy.deepcopy() is necessary to make sure the dicts are independent of each other
- lHand_dict = copy.deepcopy(rHand_dict)
-
- for key in rHand_dict:
- rHand_dict[key] += rHandIDstart
- lHand_dict[key] += lHandIDstart
-
- dict_of_mediaPipeSegmentIdx_dicts['mp_rHand'] = rHand_dict
- dict_of_mediaPipeSegmentIdx_dicts['mp_lHand'] = lHand_dict
-
-
- # #how to face --> :D <--
- # mediaPipeFaceIDs = dict()
- # faceIDStart = 67
- # #define face parts
- # mediaPipeFaceIDs['mp_jaw'] = np.arange(0,16) + faceIDStart
- # mediaPipeFaceIDs['mp_rBrow'] = np.arange(17,21) + faceIDStart
- # mediaPipeFaceIDs['mp_lBrow'] = np.arange(22,26) + faceIDStart
- # mediaPipeFaceIDs['mp_noseRidge'] = np.arange(27,30) + faceIDStart
- # mediaPipeFaceIDs['mp_noseBot'] = np.arange(31,35) + faceIDStart
- # mediaPipeFaceIDs['mp_rEye'] = np.concatenate((np.arange(36,41), [36])) + faceIDStart
- # mediaPipeFaceIDs['mp_lEye'] = np.concatenate((np.arange(42,47), [42])) + faceIDStart
- # mediaPipeFaceIDs['mp_upperLip'] = np.concatenate((np.arange(48,54), np.flip(np.arange(60, 64)), [48])) + faceIDStart
- # mediaPipeFaceIDs['mp_lowerLip'] = np.concatenate(([60], np.arange(64,67), np.arange(54, 59), [48], [60])) + faceIDStart
- # mediaPipeFaceIDs['mp_rPupil'] = np.array([68]) + faceIDStart
- # mediaPipeFaceIDs['mp_lPupil'] = np.array([69]) + faceIDStart #nice
-
- # dict_of_mediaPipeSegmentIdx_dicts['mp_face'] = mediaPipeFaceIDs
-
- return dict_of_mediaPipeSegmentIdx_dicts, dict_of_mp_skel_lineColor
-
-
-if __name__ == '__main__':
- MatplotlibLaserSkeleton()
diff --git a/jon_scratch/matplotlib_laser_skeleton/__init__.py b/jon_scratch/matplotlib_laser_skeleton/__init__.py
deleted file mode 100644
index e69de29b..00000000
diff --git a/jon_scratch/matplotlib_laser_skeleton/matplotlib_laser_skeleton.py b/jon_scratch/matplotlib_laser_skeleton/matplotlib_laser_skeleton.py
deleted file mode 100644
index 715328c8..00000000
--- a/jon_scratch/matplotlib_laser_skeleton/matplotlib_laser_skeleton.py
+++ /dev/null
@@ -1,68 +0,0 @@
-from pathlib import Path
-
-import keyboard
-import matplotlib.pyplot as plt
-import matplotlib
-import numpy as np
-from mediapipe.python.solutions import holistic as mp_holistic
-
-matplotlib.use('qtagg')
-
-mediapipe_body_pose_connections = [this_connection for this_connection in mp_holistic.POSE_CONNECTIONS]
-
-
-class MatplotlibLaserSkeleton:
- def __init__(self, file_path):
- self.fig = None
- self.ax3d = None
- self.mediapipe_all_fr_mar_xyz = None
- self.file_path = Path(file_path)
- self.load_mediapipe_data()
-
- def load_mediapipe_data(self):
- mediapipe_data_path = self.file_path / 'DataArrays' / 'mediaPipeSkel_3d.npy'
- self.mediapipe_all_fr_mar_xyz = np.load(str(mediapipe_data_path))
-
- def play_laser_skeleton_animation(self, start_frame: int = 0, end_frame: int = None):
- if end_frame is None:
- end_frame = self.mediapipe_all_fr_mar_xyz.shape[0]
-
- self.create_figure()
-
- for frame_number in range(start_frame, end_frame):
- plt.cla()
- self.plot_mediapipe_skeleton(frame_number)
- plt.show()
- plt.pause(0.001)
- if keyboard.is_pressed('esc'):
- print('You Pressed Escape!')
- plt.close('all')
- break # finishing the loop
-
- def create_figure(self):
- plt.ion()
- self.fig = plt.figure()
- self.ax3d = self.fig.add_subplot(111, projection='3d')
- self.set_axis_limits()
-
- def set_axis_limits(self):
- median_position = np.nanmedian(self.mediapipe_all_fr_mar_xyz, axis=0)
- median_position = np.nanmedian(median_position, axis=0)
- stddev_position = np.nanstd(median_position, axis=0)
- axis_range = 1000
- self.ax3d.set_xlim(median_position[0] - axis_range, median_position[0] + axis_range)
- self.ax3d.set_ylim(median_position[1] - axis_range, median_position[1] + axis_range)
- self.ax3d.set_zlim(median_position[2] - axis_range, median_position[2] + axis_range)
-
- def plot_mediapipe_skeleton(self, frame_number: int):
- print(f'Plotting frame {frame_number}')
- self.ax3d.plot(self.mediapipe_all_fr_mar_xyz[frame_number, :, 0],
- self.mediapipe_all_fr_mar_xyz[frame_number, :, 1],
- self.mediapipe_all_fr_mar_xyz[frame_number, :, 2],
- color='k', marker='o', linestyle='none', markersize=1)
-
-
-if __name__ == '__main__':
- session_path = Path('C:/Users/jonma/Dropbox/FreeMoCapProject/FreeMocap_Data/sesh_2022-02-15_11_54_28_pupil_maybe')
- matplotlib_laser_skeleton = MatplotlibLaserSkeleton(session_path)
- matplotlib_laser_skeleton.play_laser_skeleton_animation(start_frame=1000, end_frame=1200)
diff --git a/jon_scratch/multi_camera_handler.py b/jon_scratch/multi_camera_handler.py
deleted file mode 100644
index fabdbb40..00000000
--- a/jon_scratch/multi_camera_handler.py
+++ /dev/null
@@ -1,264 +0,0 @@
-#%%
-import logging
-from typing import List
-import threading
-import queue
-import time
-import datetime
-
-from pathlib import Path
-
-from pydantic import BaseModel
-import cv2
-import numpy as np
-import matplotlib.pyplot as plt
-import pandas as pd
-
-from opencv_camera import OpenCVCamera
-
-from rich import print, inspect
-
-
-
-
-logger = logging.getLogger(__name__)
-logger.level = logging.INFO
-
-MAX_NUMBER_OF_CAMERAS = 20
-
-freemocap_data_path = Path('C:/Users/jonma/Dropbox/FreeMoCapProject/FreeMocap_Data')
-sessionID = datetime.datetime.now().strftime("sesh_%Y-%m-%d_%H_%M_%S_mch")
-session_path = freemocap_data_path / sessionID
-session_path.mkdir(parents=True, exist_ok=True)
-
-def stuff_incoming_frames_into_a_queue(camera: OpenCVCamera, thread_queue: queue.Queue):
-
- print('stuff_incoming_frames_into_a_queue starting for {}'.format(camera.name))
-
- while thread_exit_event.is_set() is False:
- success, image, timestamp_ns = camera.get_next_frame()
- logger.info('{} grabbed a frame at timestamp {}'.format(camera.name, timestamp_ns/1e9))
- camera.opencv_video_writer_object.write(image)
- if not success:
- logger.error('{} failed to grab a frame at timestamp {}'.format(camera.name, timestamp_ns/1e9))
- thread_queue.put((success, camera.port_number, camera.name, image, timestamp_ns))
-
-
-
-
-def start_camera_thread(camera: OpenCVCamera, incoming_frames_queue: queue.Queue):
- print('run_camera_in_thread starting for {}'.format(camera.name))
- cam_vid_filename = camera.name +'_synchronized.mp4'
- camera_save_path = session_path / cam_vid_filename
- camera.initialize_video_writer(str(camera_save_path))
- camera_thread = threading.Thread(
- target=stuff_incoming_frames_into_a_queue,
- args=(camera, incoming_frames_queue),
- name=camera.name+'-thread')
- camera_thread.start()
- return camera_thread
-
-def display_image_on_its_cv2_named_window(cam_window_name: str, image: np.ndarray, ):
- cv2.imshow(cam_window_name, image)
- key = cv2.waitKey(1)
-
- if key == 27: #esc key kills all streams, I think
- thread_exit_event.set()
-
- if thread_exit_event.is_set():
- cv2.destroyAllWindows()
-
-def create_video_viewing_window(camera_name:str = 'Cam', window_location = (0,0)):
- window_name = camera_name + " - Press ESC to exit"
- cv2.namedWindow(window_name)
- cv2.moveWindow(window_name, window_location[0], window_location[1])
- return window_name
-
-
-
-
-if __name__ == '__main__':
- #%% connect to all available cameras
-
- camera_found_bool = True
- camera_list = []
- this_port_number = -1
- while camera_found_bool and len(camera_list) < 5:
- this_port_number+=1
- camera = OpenCVCamera(port_number=this_port_number)
- camera_found_bool = camera.connect()
- if camera_found_bool:
- camera_list.append(camera)
-
- number_of_cameras = len(camera_list)
-
-
- global thread_exit_event
- thread_exit_event = threading.Event()
- loop_count = 0
- camera_thread_list = [None]*len(camera_list)
- incoming_frames_queue = queue.Queue()
-
- #%% set some things up before we start streaming
- # setting up to grab incoming timestamps etc
- dict_of_timestamp_lists = {}
- dict_of_fps_mean_lists = {}
- dict_of_fps_std_lists = {}
- for this_camera in camera_list:
- dict_of_timestamp_lists[this_camera.name] = []
- dict_of_fps_mean_lists[this_camera.name] = []
- dict_of_fps_std_lists[this_camera.name] = []
-
- # #create cv2 named windows where we'll display incoming frames
- cam_window_name_dict = {}
- display_image_scale_factor = 2
- scaled_image_width = int(camera_list[0].resolution_width/display_image_scale_factor)
- scaled_image_height = int(camera_list[0].resolution_height/display_image_scale_factor)
- window_buffer = 50
- for this_camera in camera_list:
- #tile windows across monitor
- window_location_x = this_camera.port_number*scaled_image_width
- window_location_y=0
- if window_location_x+scaled_image_width > 1920:
- window_location_x -= 1920
- window_location_y = scaled_image_height+window_buffer
- elif window_location_x+scaled_image_width > 1920*2:
- window_location_x -= 1920*2
- window_location_y = scaled_image_height*2
- print('Creating window for {} at ({},{})'.format(this_camera.name, str(window_location_x), str(window_location_y)))
- cam_window_name_dict[this_camera.name] = create_video_viewing_window(this_camera.name, (window_location_x, window_location_y))
-
- # multi_cam_widow_name = create_video_viewing_window('MultiCamera')
-
- # #were going to scale down each incoming camera image and tile it, so we only have to display one big thing (which is faster than displaying many small things)
- # multi_image_number_of_tiles_per_side = int(np.ceil(np.sqrt(number_of_cameras)))
- # num_extra_spots_in_multi_image = multi_image_number_of_tiles_per_side - number_of_cameras
- # display_image_scale_factor = 2
- # scaled_image_width = int(camera_list[0].resolution_width/display_image_scale_factor)
- # scaled_image_height = int(camera_list[0].resolution_height/display_image_scale_factor)
-
- # scaled_image_black_frame = np.zeros((scaled_image_height, scaled_image_width, 3))
- # multi_image_holder_list_of_lists = []
-
- # for iter in range(multi_image_number_of_tiles_per_side):
- # blank_row = [scaled_image_black_frame.copy() for each in range(multi_image_number_of_tiles_per_side)]
- # multi_image_holder_list_of_lists.append(blank_row)
-
- # each_cameras_multi_image_address = []
- # for this_cam_num in range(number_of_cameras):
- # this_cam_row = int(np.floor(this_cam_num/multi_image_number_of_tiles_per_side))
- # this_cam_col = this_cam_num - this_cam_row*multi_image_number_of_tiles_per_side
- # each_cameras_multi_image_address.append((this_cam_row, this_cam_col))
-
-
-
- #%%
- ###########################################################################################
- ###########################################################################################
- ##
- ## Start the camera threads (THIS IS WHERE THE MAGIC HAPPENS)
- ##
- ###########################################################################################
- ###########################################################################################
-
- for this_camera in camera_list:
- camera_thread_list[this_camera.port_number] = start_camera_thread(this_camera, incoming_frames_queue)
-
- #
- # start the MainThread loop
- approx_start_time = time.time()
- end_after_seconds = 20 #or on pressing ESC
- qsize = []
- while not thread_exit_event.is_set():
- time_elapsed = time.time() - approx_start_time
- this_qsize = incoming_frames_queue.qsize()
- qsize.append(this_qsize)
- print('Time remaining: {:3.2f} - Queueue size: {:3.0f} '.format(end_after_seconds - time_elapsed, this_qsize))
- if time_elapsed > end_after_seconds:
- thread_exit_event.set()
- cv2.destroyAllWindows()
-
- if not incoming_frames_queue.empty():
- this_frame_tuple = incoming_frames_queue.get() #<- grab the most recent frame_tuple and do stuff with it
- this_success_bool, this_camera_number, this_camera_name, this_image, this_timestamp_ns = this_frame_tuple
- this_timestamp_sec = this_timestamp_ns/1e9
- dict_of_timestamp_lists[this_camera_name].append(this_timestamp_sec)
-
- elif qsize[-1] < 10: #only display images if queue isn't over filled
- # this_cam_address = each_cameras_multi_image_address[this_camera_number]
- # print(this_cam_address)
- # resized_image = cv2.resize(this_image, (scaled_image_width, scaled_image_height))
- # multi_image_holder_list_of_lists[this_cam_address[0]][this_cam_address[1]] = resized_image
-
- # each_row_of_multi_im = []
- # for this_row in range(multi_image_number_of_tiles_per_side):
- # each_row_of_multi_im.append(np.hstack(multi_image_holder_list_of_lists[this_row]))
- # this_multi_im = np.vstack(each_row_of_multi_im)
- # this_multi_im = cv2.normalize(src=this_multi_im, dst=None, alpha=0, beta=255, norm_type=cv2.NORM_MINMAX, dtype=cv2.CV_8U)
- # display_image_on_its_cv2_named_window(multi_cam_widow_name, this_multi_im)
- image_height, image_width, image_channels = this_image.shape
- scale_height = int(image_height/display_image_scale_factor)
- scale_width = int(image_width/display_image_scale_factor)
- display_image_on_its_cv2_named_window(cam_window_name_dict[this_camera_name], cv2.resize(this_image, (scale_width, scale_height)))
-
- #%%
-
- list_lengths = [len(this_thing) for this_thing in dict_of_timestamp_lists ]
- for this_camera in camera_list:
- this_cam_timestamps = np.array(dict_of_timestamp_lists[this_camera.name])
-
- number_of_frames = np.min([len(dict_of_timestamp_lists[this_key]) for this_key in dict_of_timestamp_lists ]) #truncate all timestamp lists to match frame count of shortest
- out_timestamp_dict = {}
-
- for this_cam_num, this_camera in enumerate(camera_list):
- out_timestamp_dict[this_camera.name] = np.array(dict_of_timestamp_lists[this_camera.name][:number_of_frames])
- out_dataframe = pd.DataFrame(out_timestamp_dict)
- out_dataframe.to_csv('~/timestamps.csv')
-
- #%% Plot up them bad bois
- # where 'bad boi' is defined as a timestamp from each camera
- # plt.ion() #<- allows for fiddling, but need to set breakpoint and call plt.show() to see the plots
- figure = plt.figure(3214, figsize=(18,5))
- ax_timestamps = figure.add_subplot(141)
- ax_timestamps.set_xlabel('frame number')
- ax_timestamps.set_ylabel('timestamp (unix epoch, sec)')
-
- ax_frame_duration = figure.add_subplot(142)
- ax_frame_duration.set_xlabel('frame number')
- ax_frame_duration.set_ylabel('framerate (1/np.diff(timestamp, frames/sec)')
- ax_frame_duration.set_ylim(0, .1)
-
- ax_histogram = figure.add_subplot(143)
- ax_histogram.set_xlabel('bins (fps)')
- ax_histogram.set_ylabel('histogram count(out of {} frames'.format(number_of_frames))
-
- ax_qsize = figure.add_subplot(144)
- ax_qsize.set_xlabel('frame/loop count')
- ax_qsize.set_ylabel('incoming frames queueue size')
- ax_qsize.plot(qsize, '-',linewidth=.5, alpha=.5)
- ax_qsize.plot(qsize, 'k.')
-
- for this_camera in camera_list:
- this_cam_timestamps = out_timestamp_dict[this_camera.name]
- this_cam_frame_duration = np.diff(out_timestamp_dict[this_camera.name])
- this_cam_framerate = 1/this_cam_frame_duration
-
- ax_timestamps.plot(this_cam_timestamps, 'o',markersize=1, alpha=.5, label=this_camera.name)
- ax_frame_duration.plot(this_cam_frame_duration, '-o', markersize=1, alpha=.5, label=this_camera.name)
- ax_histogram.hist(this_cam_framerate, bins=np.arange(0,50,1), alpha=.5,label=this_camera.name)
-
- #reference lines (i.e. 'ideal' numbers)
- ideal_framerate = 30
- approx_start_time = this_cam_timestamps[0] #just for the last camera, but it's fine for this visualization
- ideal_end_time = approx_start_time + number_of_frames/ideal_framerate
- ideal_timestamps = np.linspace(approx_start_time, ideal_end_time, number_of_frames)
-
- ideal_line_label = 'ideal for {}fps'.format(ideal_framerate)
- ax_frame_duration.plot([ 0, number_of_frames], [1/ideal_framerate, 1/ideal_framerate],'--', label=ideal_line_label, color='black')
- ax_histogram.vlines(ideal_framerate, 0, number_of_frames, linestyles='dashed', label=ideal_line_label)
- ax_timestamps.plot(ideal_timestamps, '--', color='black', label=ideal_line_label)
- ax_frame_duration.legend()
-
- plt.show()
- plt.pause(0.1)#put a breakpoint here to view/interact with figure if `plt.ion()` is active
-
diff --git a/jon_scratch/opencv_camera.py b/jon_scratch/opencv_camera.py
deleted file mode 100644
index 34b344a1..00000000
--- a/jon_scratch/opencv_camera.py
+++ /dev/null
@@ -1,137 +0,0 @@
-import logging
-import platform
-import time
-
-import numpy as np
-import cv2
-from pydantic import BaseModel
-
-logger = logging.getLogger(__name__)
-logger.level = logging.INFO
-
-
-class NoCameraAvailableException(Exception):
- pass
-
-
-class FailedFrameGrabException(Exception):
- pass
-
-
-class TweakedModel(BaseModel):
- class Config:
- arbitrary_types_allowed = True
-
-
-# OpenCV Implementation of interacting with a camera
-class OpenCVCamera(TweakedModel):
- port_number: int = 0
- name: str = "Camera0" # `camera{}`.format(port_number)
- exposure: int = -8
- resolution_width: int = 1280
- resolution_height: int = 720
- framerate: int = 30
- opencv_video_capture_object: cv2.VideoCapture = None
- opencv_video_writer_object: cv2.VideoWriter = None
-
- def initialize_video_writer(
- self,
- output_file_path: str,
- ):
- self.opencv_video_writer_object = cv2.VideoWriter(
- output_file_path,
- cv2.VideoWriter_fourcc("M", "J", "P", "G"),
- self.framerate,
- (self.resolution_width, self.resolution_height),
- )
-
- logger.info("Initialized video writer for {}".format(self.name))
-
- def connect(self) -> bool:
- if platform.system() == "Windows":
- cap_backend = cv2.CAP_DSHOW
- else:
- cap_backend = cv2.CAP_ANY
-
- self.opencv_video_capture_object = cv2.VideoCapture(
- self.port_number, cap_backend
- )
- success, image = self.opencv_video_capture_object.read()
-
- # set camera stream paramters
- self.opencv_video_capture_object.set(cv2.CAP_PROP_EXPOSURE, self.exposure)
- self.opencv_video_capture_object.set(
- cv2.CAP_PROP_FRAME_WIDTH, self.resolution_width
- )
- self.opencv_video_capture_object.set(
- cv2.CAP_PROP_FRAME_HEIGHT, self.resolution_height
- )
- self.opencv_video_capture_object.set(
- cv2.CAP_PROP_FOURCC, cv2.VideoWriter_fourcc("M", "J", "P", "G")
- )
-
- if success:
- logger.error("Camera found at port number {}".format(self.port_number))
- self.name = "Camera{}".format(self.port_number)
- return success
- else:
- # raise NoCameraAvailableException()
- logger.error(
- "Could not connect to a camera at port# {}".format(self.port_number)
- )
- return success
-
- def get_next_frame(self):
-
- timestamp_ns_pre_grab = time.time_ns()
- # Why grab not read? see -> https://stackoverflow.com/questions/57716962/difference-between-video-capture-read-and-grab
- grab_success = self.opencv_video_capture_object.grab()
- timestamp_ns_post_grab = time.time_ns()
- timestamp_ns = (timestamp_ns_pre_grab + timestamp_ns_post_grab) / 2
-
- if grab_success:
- success, image = self.opencv_video_capture_object.retrieve()
- # logger.info('{} successfully grabbed a frame at timestamp {}'.format(self.name, timestamp_ns/1e9))
- return success, image, timestamp_ns
-
- return False, None, None
-
- def close(self):
- self.opencv_video_capture_object.release()
- logger.info("Closed camera{}".format(self.name))
-
-
-if __name__ == "__main__":
- from rich.console import Console
-
- console = Console()
- timestamps = []
- try:
- # Test the camera
- camera = OpenCVCamera()
- camera.connect()
-
- while True:
- success, image, timestamp_ns = camera.get_next_frame()
- timestamps.append(timestamp_ns / 1e9)
- if success:
- mean_fps = 1 / np.mean(np.diff(timestamps))
- console.print(
- "{} grabbed a frame at timestamp {} : mean fps = {}".format(
- camera.name, timestamp_ns / 1e9, mean_fps
- )
- )
- else:
- console.print(
- "{} failed to grab a frame at timestamp {} : mean fps = {}".format(
- camera.name, timestamp_ns / 1e9, mean_fps
- )
- )
- cv2.imshow(camera.name + "- Press ESC to close", image)
- exit_key = cv2.waitKey(1)
- if exit_key == 27:
- break
- cv2.destroyAllWindows()
- camera.close()
- except:
- console.print_exception()
diff --git a/jon_scratch/pupil_calibration_pipeline/__init__.py b/jon_scratch/pupil_calibration_pipeline/__init__.py
deleted file mode 100644
index e69de29b..00000000
diff --git a/jon_scratch/pupil_calibration_pipeline/data_classes/__init__.py b/jon_scratch/pupil_calibration_pipeline/data_classes/__init__.py
deleted file mode 100644
index e69de29b..00000000
diff --git a/jon_scratch/pupil_calibration_pipeline/data_classes/freemocap_session_data_class.py b/jon_scratch/pupil_calibration_pipeline/data_classes/freemocap_session_data_class.py
deleted file mode 100644
index 703763e6..00000000
--- a/jon_scratch/pupil_calibration_pipeline/data_classes/freemocap_session_data_class.py
+++ /dev/null
@@ -1,23 +0,0 @@
-from dataclasses import dataclass
-from typing import List
-
-import numpy as np
-
-from jon_scratch.pupil_calibration_pipeline.data_classes.pupil_dataclass_and_handler import PupilLabsDataClass
-from jon_scratch.pupil_calibration_pipeline.data_classes.rotation_data_class import RotationDataClass
-
-
-@dataclass
-class FreemocapSessionDataClass:
- session_id: str = None
- timestamps: np.ndarray = None
- mediapipe_skel_fr_mar_dim: np.ndarray = None
- right_eye_pupil_labs_data: PupilLabsDataClass = None
- left_eye_pupil_labs_data: PupilLabsDataClass = None
- head_rotation_data: RotationDataClass = None
- right_eye_socket_rotation_data: RotationDataClass = None
- left_eye_socket_rotation_data: RotationDataClass = None
- right_gaze_vector_endpoint_fr_xyz: np.ndarray = None
- left_gaze_vector_endpoint_fr_xyz: np.ndarray = None
-
-
diff --git a/jon_scratch/pupil_calibration_pipeline/data_classes/pupil_dataclass_and_handler.py b/jon_scratch/pupil_calibration_pipeline/data_classes/pupil_dataclass_and_handler.py
deleted file mode 100644
index 43c0c35a..00000000
--- a/jon_scratch/pupil_calibration_pipeline/data_classes/pupil_dataclass_and_handler.py
+++ /dev/null
@@ -1,90 +0,0 @@
-from dataclasses import dataclass
-from pathlib import Path
-from typing import Union
-
-import numpy as np
-import pandas as pd
-
-
-@dataclass
-class PupilLabsDataClass:
- def __init__(self,
- timestamps=None,
- theta=None,
- phi=None,
- pupil_center_normal_x=None,
- pupil_center_normal_y=None,
- pupil_center_normal_z=None,
- eye_d=None,
- method=None):
- self.timestamps = timestamps
- self.theta = theta
- self.phi = phi
- self.pupil_center_normal_x = pupil_center_normal_x
- self.pupil_center_normal_y = pupil_center_normal_y
- self.pupil_center_normal_z = pupil_center_normal_z
- self.eye_d = eye_d
- self.method = method
-
-
-class PupilDataHandler:
- """
- Class for handling data from Pupil Labs eye tracker
- """
-
- def __init__(self, pupil_dataframe: pd.DataFrame = None):
- if pupil_dataframe is not None:
- self.load_from_dataframe(pupil_dataframe)
-
- def load_from_file(self, file_path: Union[str, Path]):
- pupil_dataframe = pd.read_csv(file_path)
- self.load_from_dataframe(pupil_dataframe)
-
- def load_from_dataframe(self, pupil_dataframe: pd.DataFrame):
- pupil_dataframe = pupil_dataframe
-
- # resituate pupil data so that the pupil normal direction is situated on the origin (instead of the arbitrary eye-camera-based eyeball sphere center)
- # ... I think... I need to check this. Their docs are a bit unclear about the origin of the pupil normal direction.
- # pupil_center_normal_x = np.array(pupil_dataframe['sphere_center_x']) - np.array(pupil_dataframe['circle_3d_normal_x'])
- # pupil_center_normal_y = np.array(pupil_dataframe['sphere_center_y']) - np.array(pupil_dataframe['circle_3d_normal_y'])
- # pupil_center_normal_z = np.array(pupil_dataframe['sphere_center_z']) - np.array(pupil_dataframe['circle_3d_normal_z'])
- pupil_center_normal_x = np.array(pupil_dataframe['circle_3d_normal_x'])
- pupil_center_normal_y = np.array(pupil_dataframe['circle_3d_normal_y'])
- pupil_center_normal_z = np.array(pupil_dataframe['circle_3d_normal_z'])
-
- self.pupil_data = PupilLabsDataClass(timestamps=np.array(pupil_dataframe['pupil_timestamp']),
- theta=np.array(pupil_dataframe['theta']),
- phi=np.array(pupil_dataframe['phi']),
- pupil_center_normal_x=pupil_center_normal_x,
- pupil_center_normal_y=pupil_center_normal_y,
- pupil_center_normal_z=pupil_center_normal_z,
- eye_d=pupil_dataframe['eye_id'],
- method=pupil_dataframe['method'])
-
- def convert_to_unix_timestamps(self, pupil_recording_info_json: dict):
- self.pupil_data.timestamps = self.pupil_data.timestamps - pupil_recording_info_json['start_time_synced_s'] + \
- pupil_recording_info_json[
- 'start_time_system_s']
-
- def get_eye_data(self, eye_str: str):
- """
- get data for the right eye
-
- pull out data according to `eye_d` (right_eye == 0, left_eye==1) and tracking method (because pupil interleaves 2d and 3d data)
- """
- if eye_str == 'right':
- eye_d = 0
-
- if eye_str == 'left':
- eye_d = 1
-
- this_eye_logical_indicies = np.logical_and(self.pupil_data.eye_d == eye_d,
- self.pupil_data.method != '2d c++')
- return PupilLabsDataClass(
- timestamps=self.pupil_data.timestamps[this_eye_logical_indicies],
- theta=self.pupil_data.theta[this_eye_logical_indicies],
- phi=self.pupil_data.phi[this_eye_logical_indicies],
- pupil_center_normal_x=self.pupil_data.pupil_center_normal_x[this_eye_logical_indicies],
- pupil_center_normal_y=self.pupil_data.pupil_center_normal_y[this_eye_logical_indicies],
- pupil_center_normal_z=self.pupil_data.pupil_center_normal_z[this_eye_logical_indicies],
- )
diff --git a/jon_scratch/pupil_calibration_pipeline/data_classes/rotation_data_class.py b/jon_scratch/pupil_calibration_pipeline/data_classes/rotation_data_class.py
deleted file mode 100644
index 421f3019..00000000
--- a/jon_scratch/pupil_calibration_pipeline/data_classes/rotation_data_class.py
+++ /dev/null
@@ -1,13 +0,0 @@
-from dataclasses import dataclass
-from typing import List
-
-import numpy as np
-
-
-@dataclass
-class RotationDataClass:
- rotation_matricies: List[np.ndarray]
- local_origin_fr_xyz: np.ndarray = np.array([0, 0, 0])
- x_hat_norm_fr_xyz: np.ndarray = np.array([1, 0, 0])
- y_hat_norm_fr_xyz: np.ndarray = np.array([0, 1, 0])
- z_hat_norm_fr_xyz: np.ndarray = np.array([0, 0, 1])
\ No newline at end of file
diff --git a/jon_scratch/pupil_calibration_pipeline/load_pupil_data_blender_script.py b/jon_scratch/pupil_calibration_pipeline/load_pupil_data_blender_script.py
deleted file mode 100644
index 777f6310..00000000
--- a/jon_scratch/pupil_calibration_pipeline/load_pupil_data_blender_script.py
+++ /dev/null
@@ -1,83 +0,0 @@
-import bpy
-import numpy as np
-import sys
-from pathlib import Path
-
-print("loading gaze data as empties")
-
-def load_gaze_data(gaze_fr_xyz:np.ndarray, eye_empty_name:str):
-
- this_eyeball_empty = bpy.data.objects[eye_empty_name]
-
- bpy.ops.object.empty_add(type='SPHERE')
- this_gaze_empty = bpy.context.active_object
- print(f'loading {eye_empty_name} gaze data...')
- for frame_num in range(r_gaze_eye_in_head_xyz.shape[0]):
-
- this_gaze_empty.location = (gaze_fr_xyz[frame_num,0],
- gaze_fr_xyz[frame_num,1],
- gaze_fr_xyz[frame_num,2])
- this_gaze_empty.scale = (0.01, 0.01, 0.01)
-
- this_gaze_empty.name = eye_empty_name + '_gaze_empty'
-
- this_gaze_empty.keyframe_insert(data_path='location',frame=frame_num)
-
- bpy.ops.object.armature_add(enter_editmode=False, align='WORLD', location=(0, 0, 0), scale=(1, 1, 1))
- this_gaze_armature = bpy.context.active_object
- this_gaze_armature.name = eye_empty_name + '_gaze_armature'
-
- this_gaze_bone_name = eye_empty_name + '_gaze_bone'
- this_gaze_bone = this_gaze_armature.data.bones[0]
- this_gaze_bone.name = this_gaze_bone_name
-
- # #create gaze bone
- # this_gaze_edit_bone= this_gaze_armature.data.edit_bones[0] # note this is using EDIT_bones, not regular bones b/c blender is a wild wacky place
- # this_gaze_edit_bone.tail = this_eyeball_empty.location
- # this_gaze_edit_bone.head = this_gaze_empty.location
-
- #track gaze bone to gaze empty
- this_gaze_pose_bone = this_gaze_armature.pose.bones[0]
-
- this_gaze_constraint = this_gaze_pose_bone.constraints.new('COPY_LOCATION')
- this_gaze_constraint.target = this_eyeball_empty
- this_gaze_constraint = this_gaze_pose_bone.constraints.new('DAMPED_TRACK')
- this_gaze_constraint.target = this_gaze_empty
-
-try:
- ##% Session path
- # #get session path as command line argument
- argv = sys.argv
- argv = argv[argv.index("--") + 1:]
- session_path = argv[0]
-
- if len(argv)>1:
- good_clean_frame_number = int(argv[1])
- else:
- good_clean_frame_number = 0
-except:
- print('we appear to be running from the Blender Scripting tab! Manually enter your `session_path` at line 23')
- session_path = Path(r'C:\Users\jonma\Dropbox\FreeMoCapProject\FreeMocap_Data\sesh_2022-05-07_17_15_05_pupil_wobble_juggle_0')
-
-
-data_arrays_path = session_path / 'DataArrays'
-
-path_to_right_eye_gaze_xyz_npy = data_arrays_path / 'right_eye_gaze_fr_xyz.npy'
-path_to_left_eye_gaze_xyz_npy = data_arrays_path / 'left_eye_gaze_fr_xyz.npy'
-
-
-# right eye
-print(f'loading right_eye_data...')
-r_gaze_eye_in_head_xyz = np.load(path_to_right_eye_gaze_xyz_npy)
-r_gaze_eye_in_head_xyz *= .001 #convert to meters
-load_gaze_data(r_gaze_eye_in_head_xyz, 'right_eye')
-
-# right eye
-print(f'loading left_eye_data...')
-l_gaze_eye_in_head_xyz = np.load(path_to_left_eye_gaze_xyz_npy)
-l_gaze_eye_in_head_xyz *= .001 #convert to meters
-load_gaze_data(l_gaze_eye_in_head_xyz, 'left_eye')
-
-
-
-print('done!')
\ No newline at end of file
diff --git a/jon_scratch/pupil_calibration_pipeline/pupil_freemocap_calibration_pipeline_orchestrator.py b/jon_scratch/pupil_calibration_pipeline/pupil_freemocap_calibration_pipeline_orchestrator.py
deleted file mode 100644
index 908c9439..00000000
--- a/jon_scratch/pupil_calibration_pipeline/pupil_freemocap_calibration_pipeline_orchestrator.py
+++ /dev/null
@@ -1,157 +0,0 @@
-import copy
-import logging
-from pathlib import Path
-from typing import Union
-import numpy as np
-from rich import inspect
-from jon_scratch.pupil_calibration_pipeline.data_classes.freemocap_session_data_class import FreemocapSessionDataClass
-from jon_scratch.pupil_calibration_pipeline.rotation_matrix_calculator import RotationMatrixCalculator
-from jon_scratch.pupil_calibration_pipeline.pupil_freemocap_synchronizer import PupilFreemocapSynchronizer
-from jon_scratch.pupil_calibration_pipeline.qt_gl_laser_skeleton_visualizer import QtGlLaserSkeletonVisualizer
-from jon_scratch.pupil_calibration_pipeline.session_data_loader import SessionDataLoader
-from jon_scratch.pupil_calibration_pipeline.vor_calibrator import VorCalibrator
-
-logger = logging.getLogger(__name__)
-logger.setLevel(logging.INFO)
-
-
-class PupilFreemocapCalibrationPipelineOrchestrator:
- session_data_loader: SessionDataLoader = None
- raw_session_data = FreemocapSessionDataClass()
- vor_frame_start: int = None,
- vor_frame_end: int = None
-
- def __init__(self, session_path: Union[Path, str], debug: bool = False, vor_frame_start: int = None,
- vor_frame_end: int = None):
- logger.info(f'initializing pupil-freemocap calibration pipeline orchestrator for session: {session_path}')
- self.session_path = session_path
- self.session_id = self.session_path.stem
- self.raw_session_data.session_id = self.session_id
- self.session_data_loader = SessionDataLoader(self.session_path)
- self.debug = debug
-
- if vor_frame_start is not None:
- self.vor_frame_start = vor_frame_start
- if vor_frame_end is not None:
- self.vor_frame_end = vor_frame_end
-
- def run(self):
- logger.info(f'loading session data from {self.session_data_loader.session_path}')
-
- ####
- # load raw freemocap data
- ####
- self.raw_session_data.timestamps = self.session_data_loader.load_freemocap_unix_timestamps()
- logger.info(
- f'self.raw_session_data.freemocap_timestamps.shape: {self.raw_session_data.timestamps.shape}')
-
- self.raw_session_data.mediapipe_skel_fr_mar_dim = self.session_data_loader.load_mediapipe_data()
- logger.info(
- f'self.raw_session_data.mediapipe_skel_fr_mar_dim.shape: {self.raw_session_data.mediapipe_skel_fr_mar_dim.shape}')
-
- ####
- # load pupil data
- ####
- pupil_data_handler = self.session_data_loader.load_pupil_data()
- self.raw_session_data.right_eye_pupil_labs_data = pupil_data_handler.get_eye_data('right')
- self.raw_session_data.left_eye_pupil_labs_data = pupil_data_handler.get_eye_data('left')
-
- ####
- # Synchronize pupil data with freemocap data - results in synchronized_session_data (each stream has exactly the same number of frames)
- ####
- synchronized_session_data = PupilFreemocapSynchronizer(self.raw_session_data).synchronize(
- vor_frame_start=self.vor_frame_start,
- vor_frame_end=self.vor_frame_end,
- debug=False, )
-
- logger.info(
- 'synchronization complete - I should add a test to make sure everything has the same number of frames')
-
- ####
- # Calculate Head Rotation matrix for each frame (gaze data will be rotated by head_rot, then calibrated_offset_rot)
- ####
- rotation_matrix_calculator = RotationMatrixCalculator(synchronized_session_data.mediapipe_skel_fr_mar_dim)
-
- synchronized_session_data.head_rotation_data = rotation_matrix_calculator.calculate_head_rotation_matricies(
- debug=False)
-
- synchronized_session_data.right_eye_socket_rotation_data = rotation_matrix_calculator.calculate_eye_rotation_matricies(
- eye='right',
- debug=False,
- )
-
- synchronized_session_data.left_eye_socket_rotation_data = rotation_matrix_calculator.calculate_eye_rotation_matricies(
- 'left',
- debug=False,
- )
-
- logger.info(
- f'len(synchronized_session_data.head_rotation_data.head_rotation_matricies): {len(synchronized_session_data.head_rotation_data.rotation_matricies)}')
-
- ####
- # Perform Vestibular-Ocular-Reflex based calibration (see methods from (Matthis et al, 2018 and 2022) for deetos)
- ####
- vor_calibrator = VorCalibrator(synchronized_session_data.mediapipe_skel_fr_mar_dim.copy(),
- vor_start_frame=self.vor_frame_start,
- vor_end_frame=self.vor_frame_end,
- debug=False)
- right_index_fingertip_idx = 41 # pretty sure this is right?
- fixation_point_fr_xyz = synchronized_session_data.mediapipe_skel_fr_mar_dim[
- self.vor_frame_start:self.vor_frame_end,
- right_index_fingertip_idx,
- :]
- # right eye
- synchronized_session_data.right_gaze_vector_endpoint_fr_xyz = vor_calibrator.calibrate(
- copy.deepcopy(synchronized_session_data.right_eye_pupil_labs_data),
- copy.deepcopy(synchronized_session_data.right_eye_socket_rotation_data),
- copy.deepcopy(synchronized_session_data.head_rotation_data),
- fixation_point_fr_xyz)
- # left eye
- synchronized_session_data.left_gaze_vector_endpoint_fr_xyz = vor_calibrator.calibrate(
- synchronized_session_data.left_eye_pupil_labs_data,
- synchronized_session_data.left_eye_socket_rotation_data,
- copy.deepcopy(synchronized_session_data.head_rotation_data),
- fixation_point_fr_xyz)
-
- # save that data
- self.save_gaze_data(synchronized_session_data)
- ####
- # Play laser skeleton animation (as both a cool thing and a debug tool)
- ####
-
- qt_gl_laser_skeleton = QtGlLaserSkeletonVisualizer(session_data=synchronized_session_data,
- move_data_to_origin=True, )
- # start_frame=self.vor_frame_start,
- # end_frame=self.vor_frame_end)
- qt_gl_laser_skeleton.start_animation()
-
- def save_gaze_data(self, synchronized_session_data):
- data_save_path = self.session_path / 'DataArrays'
-
- # right eye
- save_right_eye_data_path = data_save_path / 'right_eye_gaze_fr_xyz.npy'
- np.save(save_right_eye_data_path, synchronized_session_data.right_gaze_vector_endpoint_fr_xyz)
-
- # left eye
- save_left_eye_data_path = data_save_path / 'left_eye_gaze_fr_xyz.npy'
- np.save(save_left_eye_data_path, synchronized_session_data.left_gaze_vector_endpoint_fr_xyz)
-
-
-if __name__ == '__main__':
- # session_id = 'sesh_2022-05-07_17_15_05_pupil_wobble_juggle_0'
- # vor_frame_start_in = 614
- # vor_frame_end_in = 1073
-
- session_id = 'sesh_2022-02-15_11_54_28_pupil_maybe'
- vor_frame_start_in = 1200
- vor_frame_end_in = 1500
-
- data_path = Path('C:/Users/jonma/Dropbox/FreeMoCapProject/FreeMocap_Data/')
- this_session_path = data_path / session_id
-
-
- pupil_freemocap_calibration_pipeline_orchestrator = PupilFreemocapCalibrationPipelineOrchestrator(this_session_path,
- vor_frame_start=vor_frame_start_in,
- vor_frame_end=vor_frame_end_in)
- pupil_freemocap_calibration_pipeline_orchestrator.run()
- print('done :D ')
diff --git a/jon_scratch/pupil_calibration_pipeline/pupil_freemocap_synchronizer.py b/jon_scratch/pupil_calibration_pipeline/pupil_freemocap_synchronizer.py
deleted file mode 100644
index 42f19211..00000000
--- a/jon_scratch/pupil_calibration_pipeline/pupil_freemocap_synchronizer.py
+++ /dev/null
@@ -1,288 +0,0 @@
-import logging
-
-import numpy as np
-from matplotlib import pyplot as plt
-import matplotlib
-
-from jon_scratch.pupil_calibration_pipeline.data_classes.freemocap_session_data_class import FreemocapSessionDataClass
-from jon_scratch.pupil_calibration_pipeline.data_classes.pupil_dataclass_and_handler import PupilLabsDataClass
-
-matplotlib.use('qt5agg')
-logger = logging.getLogger(__name__)
-
-
-class PupilFreemocapSynchronizer:
- """
- synchronize pupil and freemocap timestamps, return synchronized session data (exactly the same number of synchronized frames in each data stream
- """
-
- def __init__(self, raw_session_data: FreemocapSessionDataClass):
- self.raw_session_data = raw_session_data
- self.synchronized_session_data: FreemocapSessionDataClass = None
-
- def synchronize(self, debug: bool = False, vor_frame_start: int = None, vor_frame_end: int = None):
- """
- align freemocap and pupil timestamps and clip the starts and ends of the various data traces so that everything covers the same timespacn
- """
- # find start and end frames shared by all datastreams
- freemocap_timestamps = self.raw_session_data.timestamps
- right_eye_timestamps = self.raw_session_data.right_eye_pupil_labs_data.timestamps
- left_eye_timestamps = self.raw_session_data.left_eye_pupil_labs_data.timestamps
-
- start_time_unix = np.max((freemocap_timestamps[0], right_eye_timestamps[0], left_eye_timestamps[0]))
- end_time_unix = np.min((freemocap_timestamps[-1], right_eye_timestamps[-1], left_eye_timestamps[-1]))
-
- # freemocap
- if any(freemocap_timestamps >= start_time_unix):
- freemocap_start_frame = np.where(freemocap_timestamps >= start_time_unix)[0][0]
- else:
- freemocap_start_frame = 0
-
- if any(freemocap_timestamps <= end_time_unix):
- freemocap_end_frame = np.where(freemocap_timestamps <= end_time_unix)[0][-1]
- else:
- freemocap_end_frame = len(freemocap_timestamps)
-
- # right eye
- if any(right_eye_timestamps >= start_time_unix):
- right_eye_start_frame = np.where(right_eye_timestamps >= start_time_unix)[0][0]
- else:
- right_eye_start_frame = 0
-
- if any(right_eye_timestamps <= end_time_unix):
- right_eye_end_frame = np.where(right_eye_timestamps <= end_time_unix)[0][-1]
- else:
- right_eye_end_frame = len(right_eye_timestamps)
-
- # left eye
- if any(left_eye_timestamps >= start_time_unix):
- left_eye_start_frame = np.where(left_eye_timestamps >= start_time_unix)[0][0]
- else:
- left_eye_start_frame = 0
-
- if any(left_eye_timestamps <= end_time_unix):
- left_eye_end_frame = np.where(left_eye_timestamps <= end_time_unix)[0][-1]
- else:
- left_eye_end_frame = len(left_eye_timestamps)
-
- self.right_eye_start_frame = right_eye_start_frame
- self.right_eye_end_frame = right_eye_end_frame
- self.left_eye_start_frame = left_eye_start_frame
- self.left_eye_end_frame = left_eye_end_frame
-
- # rebase time onto freemocap's framerate (b/c it's slower than pupil) <- sloppy, assumes mocap slower than eye tracker, which is untrue for, say, GoPros
- self.synchronized_timestamps = self.raw_session_data.timestamps[freemocap_start_frame:freemocap_end_frame ]
-
- logger.warning(
- "SLOPPY ASSUMPTION: assuming freemocap framerate is always slower than eye tracker (true for webcams, not true for GoPros)")
-
- self.clip_eye_data()
- self.resample_eye_data()
- # self.normalize_eye_data()
-
-
- self.synchronized_timestamps = self.synchronized_timestamps - self.synchronized_timestamps[0]
-
- assert (self.synchronized_timestamps.shape[0] == self.right_eye_theta.shape[0])
- assert (self.synchronized_timestamps.shape[0] == self.left_eye_theta.shape[0])
-
- if debug:
- self.show_debug_plots(vor_frame_start, vor_frame_end)
-
- synchronized_right_eye_data = PupilLabsDataClass(timestamps=self.synchronized_timestamps,
- theta=self.right_eye_theta,
- phi=self.right_eye_phi,
- pupil_center_normal_x=self.right_eye_pupil_center_normal_x,
- pupil_center_normal_y=self.right_eye_pupil_center_normal_y,
- pupil_center_normal_z=self.right_eye_pupil_center_normal_z,
- eye_d=0)
- synchronized_left_eye_data = PupilLabsDataClass(timestamps=self.synchronized_timestamps,
- theta=self.left_eye_theta,
- phi=self.left_eye_phi,
- pupil_center_normal_x=self.left_eye_pupil_center_normal_x,
- pupil_center_normal_y=self.left_eye_pupil_center_normal_y,
- pupil_center_normal_z=self.left_eye_pupil_center_normal_z,
- eye_d=1)
-
- synchronized_session_data = FreemocapSessionDataClass(timestamps=self.synchronized_timestamps,
- mediapipe_skel_fr_mar_dim=self.raw_session_data.mediapipe_skel_fr_mar_dim[
- freemocap_start_frame:freemocap_end_frame,
- :, :],
- right_eye_pupil_labs_data=synchronized_right_eye_data,
- left_eye_pupil_labs_data=synchronized_left_eye_data)
- return synchronized_session_data
-
- def clip_eye_data(self):
- self.right_eye_timestamps_clipped = self.raw_session_data.right_eye_pupil_labs_data.timestamps[
- self.right_eye_start_frame:self.right_eye_end_frame]
-
- self.right_eye_pupil_center_normal_x_clipped = self.raw_session_data.right_eye_pupil_labs_data.pupil_center_normal_x[
- self.right_eye_start_frame:self.right_eye_end_frame]
-
- self.right_eye_pupil_center_normal_y_clipped = self.raw_session_data.right_eye_pupil_labs_data.pupil_center_normal_y[
- self.right_eye_start_frame:self.right_eye_end_frame]
-
- self.right_eye_pupil_center_normal_z_clipped = self.raw_session_data.right_eye_pupil_labs_data.pupil_center_normal_z[
- self.right_eye_start_frame:self.right_eye_end_frame]
-
- self.right_eye_theta_clipped = self.raw_session_data.right_eye_pupil_labs_data.theta[
- self.right_eye_start_frame:self.right_eye_end_frame]
-
- self.right_eye_phi_clipped = self.raw_session_data.right_eye_pupil_labs_data.phi[
- self.right_eye_start_frame:self.right_eye_end_frame]
-
- self.left_eye_timestamps_clipped = self.raw_session_data.left_eye_pupil_labs_data.timestamps[
- self.left_eye_start_frame:self.left_eye_end_frame]
-
- self.left_eye_pupil_center_normal_x_clipped = self.raw_session_data.left_eye_pupil_labs_data.pupil_center_normal_x[
- self.left_eye_start_frame:self.left_eye_end_frame]
-
- self.left_eye_pupil_center_normal_y_clipped = self.raw_session_data.left_eye_pupil_labs_data.pupil_center_normal_y[
- self.left_eye_start_frame:self.left_eye_end_frame]
-
- self.left_eye_pupil_center_normal_z_clipped = self.raw_session_data.left_eye_pupil_labs_data.pupil_center_normal_z[
- self.left_eye_start_frame:self.left_eye_end_frame]
-
- self.left_eye_theta_clipped = self.raw_session_data.left_eye_pupil_labs_data.theta[
- self.left_eye_start_frame:self.left_eye_end_frame]
-
- self.left_eye_phi_clipped = self.raw_session_data.left_eye_pupil_labs_data.phi[
- self.left_eye_start_frame:self.left_eye_end_frame]
-
- def resample_eye_data(self):
- freemocap_timestamps = self.synchronized_timestamps
- right_eye_timestamps = self.right_eye_timestamps_clipped
- left_eye_timestamps = self.left_eye_timestamps_clipped
-
- self.right_eye_pupil_center_normal_x = np.interp(freemocap_timestamps, right_eye_timestamps,
- self.right_eye_pupil_center_normal_x_clipped)
- self.right_eye_pupil_center_normal_y = np.interp(freemocap_timestamps, right_eye_timestamps,
- self.right_eye_pupil_center_normal_y_clipped)
- self.right_eye_pupil_center_normal_z = np.interp(freemocap_timestamps, right_eye_timestamps,
- self.right_eye_pupil_center_normal_z_clipped)
- self.right_eye_theta = np.interp(freemocap_timestamps, right_eye_timestamps,
- self.right_eye_theta_clipped)
- self.right_eye_phi = np.interp(freemocap_timestamps, right_eye_timestamps,
- self.right_eye_phi_clipped)
-
- self.left_eye_pupil_center_normal_x = np.interp(freemocap_timestamps, left_eye_timestamps,
- self.left_eye_pupil_center_normal_x_clipped)
- self.left_eye_pupil_center_normal_y = np.interp(freemocap_timestamps, left_eye_timestamps,
- self.left_eye_pupil_center_normal_y_clipped)
- self.left_eye_pupil_center_normal_z = np.interp(freemocap_timestamps, left_eye_timestamps,
- self.left_eye_pupil_center_normal_z_clipped)
- self.left_eye_theta = np.interp(freemocap_timestamps, left_eye_timestamps,
- self.left_eye_theta_clipped)
- self.left_eye_phi = np.interp(freemocap_timestamps, left_eye_timestamps,
- self.left_eye_phi_clipped)
-
- def normalize_eye_data(self):
- self.right_eye_pupil_center_normal_x = self.right_eye_pupil_center_normal_x / np.linalg.norm(
- self.right_eye_pupil_center_normal_x)
- self.right_eye_pupil_center_normal_y = self.right_eye_pupil_center_normal_y / np.linalg.norm(
- self.right_eye_pupil_center_normal_y)
- self.right_eye_pupil_center_normal_z = self.right_eye_pupil_center_normal_z / np.linalg.norm(
- self.right_eye_pupil_center_normal_z)
-
- self.left_eye_pupil_center_normal_x = self.left_eye_pupil_center_normal_x / np.linalg.norm(
- self.left_eye_pupil_center_normal_x)
- self.left_eye_pupil_center_normal_y = self.left_eye_pupil_center_normal_y / np.linalg.norm(
- self.left_eye_pupil_center_normal_y)
- self.left_eye_pupil_center_normal_z = self.left_eye_pupil_center_normal_z / np.linalg.norm(
- self.left_eye_pupil_center_normal_z)
-
- def show_debug_plots(self, vor_frame_start, vor_frame_end):
-
- ###########################
- # Plot Raw Data
- ###########################
- fig = plt.figure(num=653412, figsize=(10, 20))
- fig.suptitle('Raw data')
- ax1 = fig.add_subplot(411)
- ax1.plot(self.raw_session_data.right_eye_pupil_labs_data.timestamps,
- self.raw_session_data.right_eye_pupil_labs_data.pupil_center_normal_x, '.-',
- label='right_eye_pupil_center_normal_x')
- ax1.plot(self.raw_session_data.right_eye_pupil_labs_data.timestamps,
- self.raw_session_data.right_eye_pupil_labs_data.pupil_center_normal_y, '.-',
- label='right_eye_pupil_center_normal_y')
- ax1.plot(self.raw_session_data.right_eye_pupil_labs_data.timestamps,
- self.raw_session_data.right_eye_pupil_labs_data.pupil_center_normal_z, '.-',
- label='right_eye_pupil_center_normal_z')
- ax1.legend(loc='upper left')
-
- ax2 = fig.add_subplot(412)
- ax2.plot(self.raw_session_data.right_eye_pupil_labs_data.timestamps,
- self.raw_session_data.right_eye_pupil_labs_data.theta, '.-',
- label='right_eye_theta')
- ax2.plot(self.raw_session_data.right_eye_pupil_labs_data.timestamps,
- self.raw_session_data.right_eye_pupil_labs_data.phi, '.-',
- label='right_eye_phi')
- ax2.legend(loc='upper left')
-
- ax3 = fig.add_subplot(413)
- ax3.plot(self.synchronized_timestamps, self.left_eye_pupil_center_normal_x, '.-',
- label='left_eye_pupil_center_normal_x')
- ax3.plot(self.synchronized_timestamps, self.left_eye_pupil_center_normal_y, '.-',
- label='left_eye_pupil_center_normal_y')
- ax3.plot(self.synchronized_timestamps, self.left_eye_pupil_center_normal_z, '.-',
- label='left_eye_pupil_center_normal_z')
- ax3.legend(loc='upper left')
-
- ax4 = fig.add_subplot(414)
- ax4.plot(self.raw_session_data.left_eye_pupil_labs_data.timestamps,
- self.raw_session_data.left_eye_pupil_labs_data.theta, '.-',
- label='left_eye_theta')
- ax4.plot(self.raw_session_data.left_eye_pupil_labs_data.timestamps,
- self.raw_session_data.left_eye_pupil_labs_data.phi, '.-',
- label='left_eye_phi')
- ax4.legend(loc='upper left')
-
- ###########################
- # Plot synchronized data
- ###########################
-
- fig = plt.figure(num=65341, figsize=(10, 20))
- fig.suptitle('Synchronized data')
- ax1 = fig.add_subplot(411)
- ax1.plot(self.synchronized_timestamps[vor_frame_start:vor_frame_end],
- self.right_eye_pupil_center_normal_x[vor_frame_start:vor_frame_end], '.-',
- label='right_eye_pupil_center_normal_x')
- ax1.plot(self.synchronized_timestamps[vor_frame_start:vor_frame_end],
- self.right_eye_pupil_center_normal_y[vor_frame_start:vor_frame_end], '.-',
- label='right_eye_pupil_center_normal_y')
- ax1.plot(self.synchronized_timestamps[vor_frame_start:vor_frame_end],
- self.right_eye_pupil_center_normal_z[vor_frame_start:vor_frame_end], '.-',
- label='right_eye_pupil_center_normal_z')
- ax1.legend(loc='upper left')
-
- ax2 = fig.add_subplot(412)
- ax2.plot(self.synchronized_timestamps[vor_frame_start:vor_frame_end],
- self.right_eye_theta[vor_frame_start:vor_frame_end], '.-',
- label='right_eye_theta')
- ax2.plot(self.synchronized_timestamps[vor_frame_start:vor_frame_end],
- self.right_eye_phi[vor_frame_start:vor_frame_end], '.-',
- label='right_eye_phi')
- ax2.legend(loc='upper left')
-
- ax3 = fig.add_subplot(413)
- ax3.plot(self.synchronized_timestamps[vor_frame_start:vor_frame_end],
- self.left_eye_pupil_center_normal_x[vor_frame_start:vor_frame_end], '.-',
- label='left_eye_pupil_center_normal_x')
- ax3.plot(self.synchronized_timestamps[vor_frame_start:vor_frame_end],
- self.left_eye_pupil_center_normal_y[vor_frame_start:vor_frame_end], '.-',
- label='left_eye_pupil_center_normal_y')
- ax3.plot(self.synchronized_timestamps[vor_frame_start:vor_frame_end],
- self.left_eye_pupil_center_normal_z[vor_frame_start:vor_frame_end], '.-',
- label='left_eye_pupil_center_normal_z')
- ax3.legend(loc='upper left')
-
- ax4 = fig.add_subplot(414)
- ax4.plot(self.synchronized_timestamps[vor_frame_start:vor_frame_end],
- self.left_eye_theta[vor_frame_start:vor_frame_end], '.-',
- label='left_eye_theta')
- ax4.plot(self.synchronized_timestamps[vor_frame_start:vor_frame_end],
- self.left_eye_phi[vor_frame_start:vor_frame_end], '.-',
- label='left_eye_phi')
- ax4.legend(loc='upper left')
-
- plt.show()
diff --git a/jon_scratch/pupil_calibration_pipeline/qt_gl_laser_skeleton_visualizer.py b/jon_scratch/pupil_calibration_pipeline/qt_gl_laser_skeleton_visualizer.py
deleted file mode 100644
index acd103a0..00000000
--- a/jon_scratch/pupil_calibration_pipeline/qt_gl_laser_skeleton_visualizer.py
+++ /dev/null
@@ -1,447 +0,0 @@
-# adapted from - https://gist.github.com/markjay4k/da2f55e28514be7160a7c5fbf95bd243
-import logging
-from pathlib import Path
-from typing import Union, List
-
-from pyqtgraph.Qt import QtCore, QtGui
-import pyqtgraph.opengl as gl
-import pyqtgraph as pg
-import numpy as np
-import sys
-from mediapipe.python.solutions import holistic as mp_holistic
-
-from jon_scratch.pupil_calibration_pipeline.data_classes.freemocap_session_data_class import FreemocapSessionDataClass
-from jon_scratch.pupil_calibration_pipeline.data_classes.rotation_data_class import RotationDataClass
-from jon_scratch.pupil_calibration_pipeline.session_data_loader import SessionDataLoader
-
-logger = logging.getLogger(__name__)
-
-
-class QtGlLaserSkeletonVisualizer():
- session_path: Path = None
-
- def __init__(self,
- session_data: FreemocapSessionDataClass = None,
- mediapipe_skel_fr_mar_xyz: np.ndarray = None,
- start_frame: int = None,
- end_frame: int = None,
- move_data_to_origin: bool = True):
-
- self.session_data = session_data
- if self.session_data is not None:
- self.mediapipe_fr_mar_xyz = session_data.mediapipe_skel_fr_mar_dim
- elif mediapipe_skel_fr_mar_xyz is not None:
- self.mediapipe_fr_mar_xyz = mediapipe_skel_fr_mar_xyz
- else:
- raise ValueError("Must provide either session data or mediapipe skeleton data")
-
- if move_data_to_origin:
- self.move_data_to_origin()
-
- if start_frame is None:
- self.start_frame_number = 0
- else:
- self.start_frame_number = start_frame
- if end_frame is None:
- self.end_frame_number = self.mediapipe_fr_mar_xyz.shape[0]
- else:
- self.end_frame_number = end_frame
-
- self.current_frame_number = self.start_frame_number
-
- def initialize_display_window(self):
- self.create_app_window()
- self.create_grid_planes()
- self.get_mediapipe_connections()
- self.initialize_skel_dottos()
- self.initialize_skel_lines()
- if self.session_data is not None:
- self.initialize_head_axes()
- self.initialize_eye_socket_axes()
- if self.session_data.right_gaze_vector_endpoint_fr_xyz is not None:
- self.initialize_gaze_lasers()
- self.initialize_gaze_laser_tails(tail_length=30)
-
- def create_app_window(self):
- self.app = pg.mkQApp("Laser Skeleton")
- self.gl_view_widget = gl.GLViewWidget()
- self.gl_view_widget.opts['distance'] = 2000
- self.gl_view_widget.setWindowTitle('FreeMoCap - Laser Skeleton')
- self.gl_view_widget.setGeometry(0, 110, 1920, 1080)
- self.gl_view_widget.show()
-
- def create_grid_planes(self):
- grid_scale = 2e3
- # create the background grids
- grid_plane_x = gl.GLGridItem()
- grid_plane_x.setSize(grid_scale, grid_scale, grid_scale)
- grid_plane_x.setSpacing(grid_scale / 10, grid_scale / 10, grid_scale / 10)
- grid_plane_x.rotate(90, 0, 1, 0)
- grid_plane_x.translate(-grid_scale, 0, 0)
- self.gl_view_widget.addItem(grid_plane_x)
-
- grid_plane_y = gl.GLGridItem()
- grid_plane_y.setSize(grid_scale, grid_scale, grid_scale)
- grid_plane_y.setSpacing(grid_scale / 10, grid_scale / 10, grid_scale / 10)
- grid_plane_y.rotate(90, 1, 0, 0)
- grid_plane_y.translate(0, -grid_scale, 0)
- self.gl_view_widget.addItem(grid_plane_y)
-
- grid_plane_z = gl.GLGridItem()
- grid_plane_z.setSize(grid_scale, grid_scale, grid_scale)
- grid_plane_z.setSpacing(grid_scale / 10, grid_scale / 10, grid_scale / 10)
- grid_plane_z.translate(0, 0, -grid_scale)
- self.gl_view_widget.addItem(grid_plane_z)
-
- def get_mediapipe_connections(self):
- self.mediapipe_body_connections = [this_connection for this_connection in mp_holistic.POSE_CONNECTIONS]
- self.mediapipe_hand_connections = [this_connection for this_connection in mp_holistic.HAND_CONNECTIONS]
- self.mediapipe_face_connections = [this_connection for this_connection in mp_holistic.FACEMESH_TESSELATION]
-
- def initialize_skel_dottos(self):
- self.skeleton_scatter_item = gl.GLScatterPlotItem(
- pos=self.mediapipe_fr_mar_xyz[self.current_frame_number, :, :], color=(0, 1, 1, 1), size=10,
- pxMode=False
- )
- self.gl_view_widget.addItem(self.skeleton_scatter_item)
-
- def initialize_skel_lines(self):
- self.skeleton_connections_list = []
- for this_connection in self.mediapipe_body_connections:
- this_skel_line = gl.GLLinePlotItem(
- pos=self.mediapipe_fr_mar_xyz[self.current_frame_number, this_connection, :])
- self.skeleton_connections_list.append(this_skel_line)
- self.gl_view_widget.addItem(this_skel_line)
-
- def initialize_gaze_lasers(self):
- # right eye
- this_frame_right_gaze_origin = self.session_data.right_eye_socket_rotation_data.local_origin_fr_xyz[0, :]
- this_frame_right_gaze_endpoint = self.session_data.right_gaze_vector_endpoint_fr_xyz[0, :]
- this_frame_right_gaze_laser = np.array([this_frame_right_gaze_origin, this_frame_right_gaze_endpoint])
-
- self.right_gaze_vector_line_item = gl.GLLinePlotItem(pos=this_frame_right_gaze_laser,
- color=(1, 0, 1, 1),
- width=3)
-
- self.gl_view_widget.addItem(self.right_gaze_vector_line_item)
-
- # left eye
- this_frame_left_gaze_origin = self.session_data.left_eye_socket_rotation_data.local_origin_fr_xyz[0, :]
- this_frame_left_gaze_endpoint = self.session_data.left_gaze_vector_endpoint_fr_xyz[0, :]
- this_frame_left_gaze_laser = np.array([this_frame_left_gaze_origin, this_frame_left_gaze_endpoint])
-
- self.left_gaze_vector_line_item = gl.GLLinePlotItem(pos=this_frame_left_gaze_laser,
- color=(0, 1, 1, 1),
- width=3)
-
- self.gl_view_widget.addItem(self.left_gaze_vector_line_item)
-
- def initialize_gaze_laser_tails(self, tail_length):
- self.tail_length = tail_length
- dummy_tail = np.empty((self.tail_length, 3))
- dummy_tail[:] = np.nan
- self.right_gaze_laser_tail_line_item = gl.GLLinePlotItem(pos=dummy_tail, color=(1, 0, 1, .5), width=2)
- self.left_gaze_laser_tail_line_item = gl.GLLinePlotItem(pos=dummy_tail, color=(0, 1, 1, .5), width=2)
-
- self.gl_view_widget.addItem(self.right_gaze_laser_tail_line_item)
- self.gl_view_widget.addItem(self.left_gaze_laser_tail_line_item)
-
- def initialize_eye_socket_axes(self):
- self.eye_axes_scale = 1e2 / 2
-
- # right eye
- self.right_eye_socket_axes_x_vector_line_item = self.create_axis_vector_line_item(0,
- self.session_data.right_eye_socket_rotation_data,
- dimension='x',
- scale=self.eye_axes_scale,
- color=(1, 0, 0, 1),
- width=3)
- self.right_eye_socket_axes_y_vector_line_item = self.create_axis_vector_line_item(0,
- self.session_data.right_eye_socket_rotation_data,
- dimension='y',
- scale=self.eye_axes_scale,
- color=(0, 1, 0, 1),
- width=3)
- self.right_eye_socket_axes_z_vector_line_item = self.create_axis_vector_line_item(0,
- self.session_data.right_eye_socket_rotation_data,
- dimension='z',
- scale=self.eye_axes_scale,
- color=(0, 0, 1, 1),
- width=3)
-
- self.gl_view_widget.addItem(self.right_eye_socket_axes_x_vector_line_item)
- self.gl_view_widget.addItem(self.right_eye_socket_axes_y_vector_line_item)
- self.gl_view_widget.addItem(self.right_eye_socket_axes_z_vector_line_item)
-
- # left eye
- self.left_eye_socket_axes_x_vector_line_item = self.create_axis_vector_line_item(0,
- self.session_data.left_eye_socket_rotation_data,
- dimension='x',
- scale=self.eye_axes_scale,
- color=(1, 0, 0, 1),
- width=3)
- self.left_eye_socket_axes_y_vector_line_item = self.create_axis_vector_line_item(0,
- self.session_data.left_eye_socket_rotation_data,
- dimension='y',
- scale=self.eye_axes_scale,
- color=(0, 1, 0, 1),
- width=3)
- self.left_eye_socket_axes_z_vector_line_item = self.create_axis_vector_line_item(0,
- self.session_data.left_eye_socket_rotation_data,
- dimension='z',
- scale=self.eye_axes_scale,
- color=(0, 0, 1, 1),
- width=3)
-
- self.gl_view_widget.addItem(self.left_eye_socket_axes_x_vector_line_item)
- self.gl_view_widget.addItem(self.left_eye_socket_axes_y_vector_line_item)
- self.gl_view_widget.addItem(self.left_eye_socket_axes_z_vector_line_item)
-
- def initialize_head_axes(self):
- self.head_axes_scale = 1e2
-
- first_frame_head_center_xyz = self.session_data.head_rotation_data.local_origin_fr_xyz[0, :]
-
- self.head_axes_x_vector_line_item = self.create_axis_vector_line_item(0,
- self.session_data.head_rotation_data,
- dimension='x',
- scale=self.head_axes_scale,
- color=(1, 0, 0, 1),
- width=3)
- self.head_axes_y_vector_line_item = self.create_axis_vector_line_item(0,
- self.session_data.head_rotation_data,
- dimension='y',
- scale=self.head_axes_scale,
- color=(0, 1, 0, 1),
- width=3)
- self.head_axes_z_vector_line_item = self.create_axis_vector_line_item(0,
- self.session_data.head_rotation_data,
- dimension='z',
- scale=self.head_axes_scale,
- color=(0, 0, 1, 1),
- width=3)
-
- self.gl_view_widget.addItem(self.head_axes_x_vector_line_item)
- self.gl_view_widget.addItem(self.head_axes_y_vector_line_item)
- self.gl_view_widget.addItem(self.head_axes_z_vector_line_item)
-
- def create_axis_vector_line_item(self,
- frame_number: int,
- rotation_data: RotationDataClass,
- dimension: Union[str, int] = None,
- scale: Union[int, float] = 1,
- color=(1, 1, 1, 1),
- width=3,
- ) -> np.ndarray:
-
- this_frame_axis_vector_xyz = self.unit_vector_from_rotation_matrix(frame_number,
- rotation_data,
- dimension=dimension,
- scale=scale)
- this_frame_axis_vector_line_item = gl.GLLinePlotItem(pos=this_frame_axis_vector_xyz,
- color=color,
- width=width)
- self.gl_view_widget.addItem(this_frame_axis_vector_line_item)
- return this_frame_axis_vector_line_item
-
- def unit_vector_from_rotation_matrix(self,
- frame_number: int,
- rotation_data: RotationDataClass,
- dimension: Union[str, int] = None,
- scale: Union[int, float] = 1,
- ) -> np.ndarray:
-
- try:
- if dimension == 'x':
- dimension = 0
- elif dimension == 'y':
- dimension = 1
- elif dimension == 'z':
- dimension = 2
-
- if dimension > rotation_data.rotation_matricies[0].shape[1]:
- raise ValueError(
- 'dimension must be `x`, `y`, `z`, or an integer less than the number of dimensions in the rotation matrix')
- except:
- raise ValueError('something weird about the `dimension` argument')
-
- this_rot_mat = rotation_data.rotation_matricies[frame_number]
- this_axis_vector_endpoint_xyz = rotation_data.local_origin_fr_xyz[frame_number, :] + (
- this_rot_mat[dimension, :] * scale)
- this_axis_vector_origin_xyz = rotation_data.local_origin_fr_xyz[frame_number, :]
-
- this_axis_vector_line_xyz = np.array([this_axis_vector_origin_xyz, this_axis_vector_endpoint_xyz])
-
- return this_axis_vector_line_xyz
-
- def update(self):
- self.update_frame_number()
- if self.current_frame_number % 10 == 0:
- print(f'frame number: {self.current_frame_number}')
-
-
- self.update_skeleton()
- if self.session_data is not None:
- self.update_head_axis_lines()
- self.update_eye_axis_lines()
- if self.session_data.right_gaze_vector_endpoint_fr_xyz is not None:
- self.update_gaze_lasers()
- self.update_gaze_laser_tails()
-
- def update_skeleton(self):
- # skel dottos
- self.skeleton_scatter_item.setData(
- pos=self.mediapipe_fr_mar_xyz[self.current_frame_number, :, :]
- )
-
- #skel lines
- for this_skeleton_line_number, this_connection in enumerate(self.mediapipe_body_connections):
- self.skeleton_connections_list[this_skeleton_line_number].setData(
- pos=self.mediapipe_fr_mar_xyz[self.current_frame_number, this_connection, :]
- )
-
- def update_head_axis_lines(self):
- # X
- this_frame_head_axis_x_vector_xyz = self.unit_vector_from_rotation_matrix(self.current_frame_number,
- self.session_data.head_rotation_data,
- dimension='x',
- scale=self.head_axes_scale)
- self.head_axes_x_vector_line_item.setData(pos=this_frame_head_axis_x_vector_xyz)
-
- # Y
- this_frame_head_axis_y_vector_xyz = self.unit_vector_from_rotation_matrix(self.current_frame_number,
- self.session_data.head_rotation_data,
- dimension='y',
- scale=self.head_axes_scale)
- self.head_axes_y_vector_line_item.setData(pos=this_frame_head_axis_y_vector_xyz)
-
- # Z
- this_frame_head_axis_z_vector_xyz = self.unit_vector_from_rotation_matrix(self.current_frame_number,
- self.session_data.head_rotation_data,
- dimension='z',
- scale=self.head_axes_scale)
- self.head_axes_z_vector_line_item.setData(pos=this_frame_head_axis_z_vector_xyz)
-
- def update_eye_axis_lines(self):
- # right right eye
- # X
- this_frame_right_eye_socket_axis_x_vector_xyz = self.unit_vector_from_rotation_matrix(self.current_frame_number,
- self.session_data.right_eye_socket_rotation_data,
- dimension='x',
- scale=self.eye_axes_scale)
- self.right_eye_socket_axes_x_vector_line_item.setData(pos=this_frame_right_eye_socket_axis_x_vector_xyz)
-
- # Y
- this_frame_right_eye_socket_axis_y_vector_xyz = self.unit_vector_from_rotation_matrix(self.current_frame_number,
- self.session_data.right_eye_socket_rotation_data,
- dimension='y',
- scale=self.eye_axes_scale)
- self.right_eye_socket_axes_y_vector_line_item.setData(pos=this_frame_right_eye_socket_axis_y_vector_xyz)
-
- # Z
- this_frame_right_eye_socket_axis_z_vector_xyz = self.unit_vector_from_rotation_matrix(self.current_frame_number,
- self.session_data.right_eye_socket_rotation_data,
- dimension='z',
- scale=self.eye_axes_scale)
- self.right_eye_socket_axes_z_vector_line_item.setData(pos=this_frame_right_eye_socket_axis_z_vector_xyz)
-
- # left eye
- # X
- this_frame_left_eye_socket_axis_x_vector_xyz = self.unit_vector_from_rotation_matrix(self.current_frame_number,
- self.session_data.left_eye_socket_rotation_data,
- dimension='x',
- scale=self.eye_axes_scale)
- self.left_eye_socket_axes_x_vector_line_item.setData(pos=this_frame_left_eye_socket_axis_x_vector_xyz)
-
- # Y
- this_frame_left_eye_socket_axis_y_vector_xyz = self.unit_vector_from_rotation_matrix(self.current_frame_number,
- self.session_data.left_eye_socket_rotation_data,
- dimension='y',
- scale=self.eye_axes_scale)
- self.left_eye_socket_axes_y_vector_line_item.setData(pos=this_frame_left_eye_socket_axis_y_vector_xyz)
-
- # Z
- this_frame_left_eye_socket_axis_z_vector_xyz = self.unit_vector_from_rotation_matrix(self.current_frame_number,
- self.session_data.left_eye_socket_rotation_data,
- dimension='z',
- scale=self.eye_axes_scale)
- self.left_eye_socket_axes_z_vector_line_item.setData(pos=this_frame_left_eye_socket_axis_z_vector_xyz)
-
- def update_gaze_lasers(self):
- # right eye
- this_right_gaze_laser_line = np.array(
- [self.session_data.right_eye_socket_rotation_data.local_origin_fr_xyz[self.current_frame_number, :],
- self.session_data.right_gaze_vector_endpoint_fr_xyz[self.current_frame_number, :]])
- self.right_gaze_vector_line_item.setData(pos=this_right_gaze_laser_line)
-
- # left eye
- this_left_gaze_laser_line = np.array(
- [self.session_data.left_eye_socket_rotation_data.local_origin_fr_xyz[self.current_frame_number, :],
- self.session_data.left_gaze_vector_endpoint_fr_xyz[self.current_frame_number, :]])
-
- self.left_gaze_vector_line_item.setData(pos=this_left_gaze_laser_line)
-
- def update_gaze_laser_tails(self):
- if self.current_frame_number < self.tail_length:
- return
-
- # right eye
- this_right_gaze_laser_tail = self.session_data.right_gaze_vector_endpoint_fr_xyz[
- self.current_frame_number - self.tail_length: self.current_frame_number, :]
- self.right_gaze_laser_tail_line_item.setData(pos=this_right_gaze_laser_tail)
-
- # left eye
- this_left_gaze_laser_tail = self.session_data.left_gaze_vector_endpoint_fr_xyz[
- self.current_frame_number - self.tail_length: self.current_frame_number, :]
- self.left_gaze_laser_tail_line_item.setData(pos=this_left_gaze_laser_tail)
-
- def update_frame_number(self):
- self.current_frame_number += 1
- if self.current_frame_number >= self.end_frame_number:
- self.current_frame_number = self.start_frame_number
-
- def start(self):
- print('starting animation')
- pg.exec()
-
- def start_animation(self):
- print('initializing display window')
- self.initialize_display_window()
- timer = QtCore.QTimer()
- timer.timeout.connect(self.update)
- timer.start(33)
- self.start()
-
- def move_data_to_origin(self):
- mean_position_xyz = np.nanmedian(np.nanmedian(self.mediapipe_fr_mar_xyz, axis=0), axis=0)
-
- self.mediapipe_fr_mar_xyz[:, :, 0] -= mean_position_xyz[0]
- self.mediapipe_fr_mar_xyz[:, :, 1] -= mean_position_xyz[1]
- self.mediapipe_fr_mar_xyz[:, :, 2] -= mean_position_xyz[2]
-
- if self.session_data is not None:
- self.session_data.head_rotation_data.local_origin_fr_xyz[:, 0] -= mean_position_xyz[0]
- self.session_data.head_rotation_data.local_origin_fr_xyz[:, 1] -= mean_position_xyz[1]
- self.session_data.head_rotation_data.local_origin_fr_xyz[:, 2] -= mean_position_xyz[2]
-
- if self.session_data.right_gaze_vector_endpoint_fr_xyz is not None:
- self.session_data.right_gaze_vector_endpoint_fr_xyz[:, 0] -= mean_position_xyz[0]
- self.session_data.right_gaze_vector_endpoint_fr_xyz[:, 1] -= mean_position_xyz[1]
- self.session_data.right_gaze_vector_endpoint_fr_xyz[:, 2] -= mean_position_xyz[2]
-
- self.session_data.left_gaze_vector_endpoint_fr_xyz[:, 0] -= mean_position_xyz[0]
- self.session_data.left_gaze_vector_endpoint_fr_xyz[:, 1] -= mean_position_xyz[1]
- self.session_data.left_gaze_vector_endpoint_fr_xyz[:, 2] -= mean_position_xyz[2]
-
-
-if __name__ == '__main__':
- # session_id = 'sesh_2022-02-15_11_54_28_pupil_maybe'
- session_id = 'sesh_2022-05-03_13_43_00_JSM_treadmill_day2_t0'
- data_path = Path('C:/Users/jonma/Dropbox/FreeMoCapProject/FreeMocap_Data/')
- session_path = data_path / session_id
-
- session_data_loader = SessionDataLoader(session_path)
- mediapipe_skel_fr_mar_xyz_in = session_data_loader.load_mediapipe_data(move_to_origin=True)
- print(f'mediapipe_skel_fr_mar_xyz.shape: {mediapipe_skel_fr_mar_xyz_in.shape}')
- qt_gl_laser_skeleton = QtGlLaserSkeletonVisualizer(mediapipe_skel_fr_mar_xyz=mediapipe_skel_fr_mar_xyz_in, )
- qt_gl_laser_skeleton.start_animation()
diff --git a/jon_scratch/pupil_calibration_pipeline/rotation_matrix_calculator.py b/jon_scratch/pupil_calibration_pipeline/rotation_matrix_calculator.py
deleted file mode 100644
index 162bd161..00000000
--- a/jon_scratch/pupil_calibration_pipeline/rotation_matrix_calculator.py
+++ /dev/null
@@ -1,284 +0,0 @@
-import logging
-from typing import List
-
-import numpy as np
-
-import matplotlib.pyplot as plt
-import matplotlib
-import keyboard
-
-from jon_scratch.pupil_calibration_pipeline.data_classes.rotation_data_class import RotationDataClass
-
-logger = logging.getLogger(__name__)
-logger.setLevel(logging.INFO)
-
-matplotlib.use('qt5agg')
-
-
-def pin_point_new_origin(point_xyz, new_origin_xyz):
- return point_xyz - new_origin_xyz
-
-
-def normalize_length(point_xyz):
- return point_xyz / get_norm_length(point_xyz, axis=1)[:, None]
-
-
-def get_norm_length(point_xyz, axis=1):
- return np.linalg.norm(point_xyz, axis=axis)
-
-
-class RotationMatrixCalculator:
- mediapipe_skeleton_fr_mar_xyz: np.ndarray
-
- def __init__(self, mediapipe_skeleton_fr_mar_xyz):
- self.mediapipe_skeleton_fr_mar_xyz = mediapipe_skeleton_fr_mar_xyz
-
- def calculate_head_rotation_matricies(self,
- normalize_length_by_x: bool = False,
- debug: bool = False):
- """
- # Calculate head rotation matricies
-
- calculate orthonormal basis vectors of the head on each frame, stack them on top of each other to make 3x3 rotation matricies, because apparently that's how that works?!
-
- 1 - calculate `head_center_xyz` as mean of left and right ear markers
- 2 - define x+ as vector between `head_center_xyz` and `nose_xyz`- normalize to get `x_hat`
- 3 - define y+ as vector between `head_center_xyz` and `left_ear_xyz` - normalize to get `y_hat_temp` (will be replaced later, to ensure orthogonal \)
- 4 - define z+ as cross product of `x_hat` and `y_hat`
- 5 - replace `y_hat_temp` with `z_hat` crossed wtih `x_hat` (Pretty sure that makes it right handed...)
-
- Stack x_hat, y_hat, and z_hat on top of each other, and that's your head rotation matrix on that frame
-
- """
- nose_id = 0
- left_ear_id = 7
- right_ear_id = 8
-
- nose_xyz = self.mediapipe_skeleton_fr_mar_xyz[:, nose_id, :].copy()
- right_ear_xyz = self.mediapipe_skeleton_fr_mar_xyz[:, right_ear_id, :].copy()
- left_ear_xyz = self.mediapipe_skeleton_fr_mar_xyz[:, left_ear_id, :].copy()
- head_center_xyz = (right_ear_xyz + left_ear_xyz) / 2
-
- head_rotation_data = self.define_basis_vectors(center_point_fr_xyz=head_center_xyz,
- x_direction_fr_xyz=nose_xyz,
- y_direction_fr_xyz=left_ear_xyz,
- normalize_length_by_x=normalize_length_by_x)
- if debug:
- self.show_head_rotation_debug_plot(head_rotation_data)
-
- return head_rotation_data
-
- def calculate_eye_rotation_matricies(self,
- eye: str,
- normalize_length_by_x: bool = False,
- debug: bool = False,
- ) -> List[np.ndarray]:
- nose_index = 0
- if eye == 'left':
- inner_eye_index = 1
- eye_mid_index = 2
- outer_eye_index = 3
- x_direction_fr_xyz = self.mediapipe_skeleton_fr_mar_xyz[:, inner_eye_index,
- :] # this will make Z+ point forward
- elif eye == 'right':
- inner_eye_index = 4
- eye_mid_index = 5
- outer_eye_index = 6
- x_direction_fr_xyz = self.mediapipe_skeleton_fr_mar_xyz[:, outer_eye_index,
- :] # this will make Z+ point forward
- else:
- raise ValueError('`eye` must be "left" or "right"')
-
- y_direction_fr_xyz = self.mediapipe_skeleton_fr_mar_xyz[:, nose_index, :]
-
- eye_mid_fr_xyz = self.mediapipe_skeleton_fr_mar_xyz[:, eye_mid_index, :]
-
- eye_socket_rotation_data = self.define_basis_vectors(center_point_fr_xyz=eye_mid_fr_xyz,
- x_direction_fr_xyz=x_direction_fr_xyz,
- y_direction_fr_xyz=y_direction_fr_xyz,
- normalize_length_by_x = normalize_length_by_x)
-
- return eye_socket_rotation_data
-
- def define_basis_vectors(self,
- center_point_fr_xyz: np.ndarray = None,
- x_direction_fr_xyz: np.ndarray = None,
- y_direction_fr_xyz: np.ndarray = None,
- z_direction_fr_xyz: np.ndarray = None,
- normalize_length_by_x: bool = True) -> RotationDataClass:
- """
- create orthonormal basis vectors based on a center point and at least TWO of the following = a point defining X direction, a point defining Y direction, and a point defining Z direction
- """
-
- x_known = True
- y_known = True
- z_known = True
-
- if x_direction_fr_xyz is None:
- x_known = False
- x_direction_fr_xyz = np.empty(center_point_fr_xyz.shape)
- x_direction_fr_xyz[:] = np.nan
-
- if y_direction_fr_xyz is None:
- y_known = False
- y_direction_fr_xyz = np.empty(center_point_fr_xyz.shape)
- y_direction_fr_xyz[:] = np.nan
-
- if z_direction_fr_xyz is None:
- z_known = False
- z_direction_fr_xyz = np.empty(center_point_fr_xyz.shape)
- z_direction_fr_xyz[:] = np.nan
-
- if sum([x_known, y_known, z_known]) < 2:
- raise ValueError(
- "Must specify at least two of the following: x_direction_fr_xyz, y_direction_fr_xyz, z_direction_fr_xyz")
-
- if center_point_fr_xyz is not None: # if center point is specified, then use it to zero out the x,y,z directions vectors
- zero_x_direction_xyz = pin_point_new_origin(x_direction_fr_xyz, center_point_fr_xyz)
- zero_y_direction_xyz = pin_point_new_origin(y_direction_fr_xyz, center_point_fr_xyz)
- zero_z_direction_xyz = pin_point_new_origin(z_direction_fr_xyz, center_point_fr_xyz)
- else:
- zero_x_direction_xyz = x_direction_fr_xyz
- zero_y_direction_xyz = y_direction_fr_xyz
- zero_z_direction_xyz = z_direction_fr_xyz
-
- x_hat_xyz = None
- y_hat_xyz = None
- z_hat_xyz = None
-
- if x_known:
- x_norm_length = np.nanmean(get_norm_length(zero_x_direction_xyz))
- x_hat_xyz = normalize_length(zero_x_direction_xyz)
- if y_known: # we know x and y directions and need to find Z by X cross Y
- z_hat_xyz = normalize_length(np.cross(x_hat_xyz, zero_y_direction_xyz))
- y_hat_xyz = normalize_length(np.cross(z_hat_xyz, x_hat_xyz))
-
- else: # we know x and z directions and need to find Y by Z cross X
- y_hat_xyz = normalize_length(np.cross(zero_z_direction_xyz, x_hat_xyz))
- z_hat_xyz = normalize_length(np.cross(x_hat_xyz, y_hat_xyz))
-
- elif y_known: # we know y and z directions and need to find X by Y cross Z
- y_hat_xyz = normalize_length(zero_y_direction_xyz)
- x_hat_xyz = normalize_length(np.cross(y_hat_xyz, zero_z_direction_xyz))
- z_hat_xyz = normalize_length(np.cross(x_hat_xyz, y_hat_xyz))
-
- if normalize_length_by_x:
- x_hat_xyz = x_hat_xyz * x_norm_length
- y_hat_xyz = y_hat_xyz * x_norm_length
- z_hat_xyz = z_hat_xyz * x_norm_length
-
- # #umm, this shouldn't be necessary.... but it makes it work, so....
- # x_hat_xyz = -x_hat_xyz
- # y_hat_xyz = -y_hat_xyz
- # z_hat_xyz = z_hat_xyz
-
- # create 3x3 cosine rotation matricies by stacking X_hat, Y_hat, and Z_hat
- rotation_matricies = []
- frame_number = -1
- for this_x_hat_xyz, this_y_hat_xyz, this_z_hat_xyz in zip(x_hat_xyz, y_hat_xyz, z_hat_xyz):
- frame_number += 1
- if frame_number > 1000:
- f = 9
- this_rotation_matrix = np.squeeze(np.dstack((this_x_hat_xyz, this_y_hat_xyz, this_z_hat_xyz)))
-
- assert this_rotation_matrix.shape == (3, 3)
-
- if not np.isnan(this_x_hat_xyz).any():
- assert (this_rotation_matrix[:, 0] == this_x_hat_xyz).all()
-
- rotation_matricies.append(this_rotation_matrix)
-
- rotation_matricies = [np.transpose(this_rotation_martix) for this_rotation_martix in rotation_matricies]
-
- return RotationDataClass(rotation_matricies=rotation_matricies,
- local_origin_fr_xyz=center_point_fr_xyz,
- x_hat_norm_fr_xyz=x_hat_xyz,
- y_hat_norm_fr_xyz=y_hat_xyz,
- z_hat_norm_fr_xyz=z_hat_xyz,
- )
-
- def show_head_rotation_debug_plot(self, rotation_data: RotationDataClass):
- rotation_matricies = rotation_data.rotation_matricies
- local_origin_fr_xyz = rotation_data.local_origin_fr_xyz
-
- x_hat_xyz = np.asarray([this_rot_mat[0, :] for this_rot_mat in rotation_matricies])
- y_hat_xyz = np.asarray([this_rot_mat[1, :] for this_rot_mat in rotation_matricies])
- z_hat_xyz = np.asarray([this_rot_mat[2, :] for this_rot_mat in rotation_matricies])
-
- test_point_xyz_og = np.array((1, 1, 1))
- test_point_xyz_rot = np.empty(z_hat_xyz.shape)
- logger.warning('We shouldnt have to transpose the rotation matix here, need to fix this upstream')
-
- for frame_number in range(len(rotation_matricies)):
- # see https://peps.python.org/pep-0465/ for explanation of the `@` operator (which is a "matrix multiplication" operator)
- test_point_xyz_rot[frame_number, :] = np.transpose(rotation_matricies[frame_number]) @ test_point_xyz_og
-
- z_mediapipe_skeleton_fr_mar_xyz = np.empty(self.mediapipe_skeleton_fr_mar_xyz.shape)
- for this_marker_number in range(self.mediapipe_skeleton_fr_mar_xyz.shape[1]):
- z_mediapipe_skeleton_fr_mar_xyz[:, this_marker_number, :] = pin_point_new_origin(
- self.mediapipe_skeleton_fr_mar_xyz[:, this_marker_number, :],
- local_origin_fr_xyz)
- plt.close('all')
-
- fig = plt.figure(num=124)
- fig.suptitle('Head Rotation Matrix - Debug Plot - Press ESC to Quit')
- ax = fig.add_subplot(111, projection='3d')
-
- ax_range = np.nanmean(get_norm_length(x_hat_xyz)) * 2
-
- for frame_number in range(1200, x_hat_xyz.shape[0]):
- ax.clear()
-
- # plot head orthonormal basis vectors
- ax.plot(x_hat_xyz[frame_number - 30:frame_number, 0],
- x_hat_xyz[frame_number - 30:frame_number, 1],
- x_hat_xyz[frame_number - 30:frame_number, 2], 'r-')
-
- ax.plot(y_hat_xyz[frame_number - 30:frame_number, 0],
- y_hat_xyz[frame_number - 30:frame_number, 1],
- y_hat_xyz[frame_number - 30:frame_number, 2], 'g-')
-
- ax.plot(z_hat_xyz[frame_number - 30:frame_number, 0],
- z_hat_xyz[frame_number - 30:frame_number, 1],
- z_hat_xyz[frame_number - 30:frame_number, 2], 'b-')
-
- ax.plot([0, x_hat_xyz[frame_number, 0]],
- [0, x_hat_xyz[frame_number, 1]],
- [0, x_hat_xyz[frame_number, 2]], 'r-o', label='x_hat')
-
- ax.plot([0, y_hat_xyz[frame_number, 0]],
- [0, y_hat_xyz[frame_number, 1]],
- [0, y_hat_xyz[frame_number, 2]], 'g-o', label='y_hat')
-
- ax.plot([0, z_hat_xyz[frame_number, 0]],
- [0, z_hat_xyz[frame_number, 1]],
- [0, z_hat_xyz[frame_number, 2]], 'b-o', label='z_hat')
-
- # plot test point rotated with head rotation matricies
-
- ax.plot(test_point_xyz_rot[frame_number - 30:frame_number, 0],
- test_point_xyz_rot[frame_number - 30:frame_number, 1],
- test_point_xyz_rot[frame_number - 30:frame_number, 2], 'k-')
-
- ax.plot([0, test_point_xyz_rot[frame_number, 0]],
- [0, test_point_xyz_rot[frame_number, 1]],
- [0, test_point_xyz_rot[frame_number, 2]], 'k-o', label='test point')
-
- # plot a friendly skeleton
- ax.scatter(z_mediapipe_skeleton_fr_mar_xyz[frame_number, :, 0],
- z_mediapipe_skeleton_fr_mar_xyz[frame_number, :, 1],
- z_mediapipe_skeleton_fr_mar_xyz[frame_number, :, 2],
- 'ko')
-
- ax.set_xlim([-ax_range, ax_range])
- ax.set_ylim([-ax_range, ax_range])
- ax.set_zlim([-ax_range, ax_range])
-
- ax.legend()
- plt.pause(.01)
-
- if keyboard.is_pressed('esc'):
- print('You Pressed Escape!')
- break # finishing the loop
-
- plt.close(fig)
diff --git a/jon_scratch/pupil_calibration_pipeline/session_data_loader.py b/jon_scratch/pupil_calibration_pipeline/session_data_loader.py
deleted file mode 100644
index fb20ed00..00000000
--- a/jon_scratch/pupil_calibration_pipeline/session_data_loader.py
+++ /dev/null
@@ -1,107 +0,0 @@
-import json
-import logging
-from pathlib import Path
-from typing import Union
-import numpy as np
-import pandas as pd
-
-from jon_scratch.pupil_calibration_pipeline.data_classes.pupil_dataclass_and_handler import PupilLabsDataClass, PupilDataHandler
-
-logger = logging.getLogger(__name__)
-
-
-class SessionDataLoader:
- _session_path: Path = None
-
- def __init__(self, session_path):
-
- self._session_path = Path(session_path)
-
- @property
- def session_path(self):
- return self._session_path
-
-
- def load_freemocap_unix_timestamps(self):
- """
- load/calculate the unix timestamps for the freemocap data (as mean of each camera's timestamp on each frame)
-
- """
- freemocap_unix_timestamp_path = self.session_path / 'unix_synced_timestamps.csv'
- freemocap_unix_timestamps_dataframe = pd.read_csv(freemocap_unix_timestamp_path)
- each_cam_timestamps_list = []
- camera_names = [column_name for column_name in list(freemocap_unix_timestamps_dataframe.columns) if
- 'Cam' in column_name]
-
- for this_camera_name in camera_names:
- each_cam_timestamps_list.append(np.array(freemocap_unix_timestamps_dataframe[this_camera_name]))
-
- cameras_timestamp_array = np.stack(each_cam_timestamps_list, axis=1)
- cameras_timestamp_array[cameras_timestamp_array == -1] = np.nan # replace -1 with nan
-
- freemocap_timestamps = np.nanmean(cameras_timestamp_array, axis=1)
- return freemocap_timestamps
-
- def load_mediapipe_data(self,
- session_path: Union[Path, str] = None,
- include_hands: bool = True,
- include_face: bool = False,
- move_to_origin: bool = False, ) -> np.ndarray:
-
- if session_path is not None:
- self.session_path(session_path)
-
- if self._session_path is None:
- raise ValueError('Session path is not specified - Can\'t load mediapipe data without a session path')
-
- mediapipe_data_path = self.session_path / 'DataArrays' / 'mediaPipeSkel_3d_smoothed.npy'
- logger.info(f'loading mediapipe data from {mediapipe_data_path}')
- mediapipe_fr_mar_xyz = np.load(str(mediapipe_data_path))
-
- if move_to_origin:
- mean_position_xyz = np.nanmedian(np.nanmedian(mediapipe_fr_mar_xyz, axis=0), axis=0)
- mediapipe_fr_mar_xyz[:, :, 0] -= mean_position_xyz[0]
- mediapipe_fr_mar_xyz[:, :, 1] -= mean_position_xyz[1]
- mediapipe_fr_mar_xyz[:, :, 2] -= mean_position_xyz[2]
-
- if include_face:
- return mediapipe_fr_mar_xyz # body + hands + face
-
- if include_hands:
- return mediapipe_fr_mar_xyz[:, :75, :] # body + hands, but not face
-
- return mediapipe_fr_mar_xyz[:, :33, :] # just the body marker
-
- def load_pupil_data(self)->PupilDataHandler:
- """
- # load in data recorded with a Pupil Labs eye tracker.
- - pupil data from `pupil_positions.csv` in the **pupil exports** folder
- - definitions in `pupil_gaze_positions_info.txt` of same folder
- - pupil start time from `info.player.json` for syncing
- """
- pupil_data_path = self.session_path / 'pupil_000'
- pupil_data_exports_path = pupil_data_path / 'exports' / '000'
- pupil_positions_path = pupil_data_exports_path / 'pupil_positions.csv'
- pupil_recording_info_path = pupil_data_path / 'info.player.json'
- freemocap_unix_timestamp_path = self.session_path / 'unix_synced_timestamps.csv'
-
- logger.info(f'loading pupil data from {pupil_positions_path}')
- pupil_dataframe = pd.read_csv(pupil_positions_path)
- pupil_recording_info_json = json.load(open(pupil_recording_info_path))
- freemocap_unix_timestamps_dataframe = pd.read_csv(freemocap_unix_timestamp_path)
-
- pupil_data_handler = PupilDataHandler(pupil_dataframe)
- pupil_data_handler.convert_to_unix_timestamps(pupil_recording_info_json)
-
- return pupil_data_handler
-
-
-if __name__ == '__main__':
- data_path = Path('C:/Users/jonma/Dropbox/FreeMoCapProject/FreeMocap_Data/')
- session_path = data_path / 'sesh_2022-02-15_11_54_28_pupil_maybe'
-
- session_data_loader = SessionDataLoader(session_path)
- pupil_data = session_data_loader.load_pupil_data()
- print('pupil data loaded, but I don\'t have an easy way to print out the shape of things yet, lol')
- mediapipe_skel_fr_mar_xyz = session_data_loader.load_mediapipe_data()
- print(f'mediapipe_skel_fr_mar_xyz.shape: {mediapipe_skel_fr_mar_xyz.shape}')
diff --git a/jon_scratch/pupil_calibration_pipeline/spherical_coordiate_converters/__init__.py b/jon_scratch/pupil_calibration_pipeline/spherical_coordiate_converters/__init__.py
deleted file mode 100644
index e69de29b..00000000
diff --git a/jon_scratch/pupil_calibration_pipeline/spherical_coordiate_converters/cart2sph_and_sph2cart.py b/jon_scratch/pupil_calibration_pipeline/spherical_coordiate_converters/cart2sph_and_sph2cart.py
deleted file mode 100644
index 473a4354..00000000
--- a/jon_scratch/pupil_calibration_pipeline/spherical_coordiate_converters/cart2sph_and_sph2cart.py
+++ /dev/null
@@ -1,15 +0,0 @@
-#copied from https://stackoverflow.com/questions/30084174/efficient-matlab-cart2sph-and-sph2cart-functions-in-python
-import numpy as np
-
-
-def cart2sph(x,y,z):
- azimuth = np.arctan2(y,x)
- elevation = np.arctan2(z,np.sqrt(x**2 + y**2))
- r = np.sqrt(x**2 + y**2 + z**2)
- return azimuth, elevation, r
-
-def sph2cart(azimuth,elevation,r):
- x = r * np.cos(elevation) * np.cos(azimuth)
- y = r * np.cos(elevation) * np.sin(azimuth)
- z = r * np.sin(elevation)
- return x, y, z
\ No newline at end of file
diff --git a/jon_scratch/pupil_calibration_pipeline/vor_calibrator.py b/jon_scratch/pupil_calibration_pipeline/vor_calibrator.py
deleted file mode 100644
index f9d4c71e..00000000
--- a/jon_scratch/pupil_calibration_pipeline/vor_calibrator.py
+++ /dev/null
@@ -1,282 +0,0 @@
-import logging
-from typing import Union, List
-
-import keyboard
-import numpy as np
-from scipy import optimize
-from matplotlib import pyplot as plt
-import matplotlib
-from scipy.spatial.transform import Rotation
-
-from jon_scratch.pupil_calibration_pipeline.data_classes.freemocap_session_data_class import FreemocapSessionDataClass
-from jon_scratch.pupil_calibration_pipeline.data_classes.pupil_dataclass_and_handler import PupilLabsDataClass
-from jon_scratch.pupil_calibration_pipeline.data_classes.rotation_data_class import RotationDataClass
-from jon_scratch.pupil_calibration_pipeline.spherical_coordiate_converters.cart2sph_and_sph2cart import cart2sph, \
- sph2cart
-
-matplotlib.use('qt5agg')
-logger = logging.getLogger(__name__)
-
-
-class VorCalibrator:
- """
- Calibrate synchronized eye data from a Pupil Labs eye tracker with FreeMoCap skeleton
- see methods sections of (Matthis, Yates, and Hayhoe, Current Biology, 2018) and (Matthis, Muller, Bonnen, Hayehoe, PLoS Computation Biology 2022) for details
- """
-
- def __init__(self, mediapipe_skel_fr_mar_xyz: np.ndarray,
- vor_start_frame: int = None,
- vor_end_frame: int = None,
- debug: bool = False):
- self.debug = debug
- self.mediapipe_skel_fr_mar_xyz = mediapipe_skel_fr_mar_xyz
- if vor_start_frame is not None:
- self.vor_start_frame = vor_start_frame
- if vor_end_frame is None:
- raise ValueError("Must specify vor_end_frame if vor_start_frame is specified")
- self.vor_end_frame = vor_end_frame
-
- def calibrate(self,
- pupil_labs_eye_data: PupilLabsDataClass,
- eye_socket_rotation_data: RotationDataClass,
- head_rotation_data: RotationDataClass,
- fixation_point_fr_xyz: np.ndarray) -> np.ndarray:
-
- if not fixation_point_fr_xyz.shape[1] == 3:
- raise Exception("fixation_point_fr_xyz must be a numpy array with 3 columns")
-
- eye_socket_origin_fr_xyz = eye_socket_rotation_data.local_origin_fr_xyz
- eye_socket_rotation_matricies = eye_socket_rotation_data.rotation_matricies
-
- head_rotation_matricies = head_rotation_data.rotation_matricies
-
- # gaze_unit_vector_end_point_fr_xyz = eye_socket_rotation_data.z_hat_norm_fr_xyz
- self.fixation_distance = self.get_distance_between_two_points(fixation_point_fr_xyz,
- eye_socket_origin_fr_xyz[
- self.vor_start_frame:self.vor_end_frame, :])
-
- # not sure why I need to do this, but Karl Muller did it so it's likely necessary
- gaze_y = -pupil_labs_eye_data.pupil_center_normal_y
- gaze_x = pupil_labs_eye_data.pupil_center_normal_z
- gaze_z = pupil_labs_eye_data.pupil_center_normal_x
-
- gaze_x = gaze_x * np.nanmean(self.fixation_distance)
- gaze_y = gaze_y * np.nanmean(self.fixation_distance)
- gaze_z = gaze_z * np.nanmean(self.fixation_distance)
-
- use_dummy_gaze_data = False
- if use_dummy_gaze_data:
- gaze_x = np.zeros(pupil_labs_eye_data.pupil_center_normal_x.shape) * np.nanmedian(self.fixation_distance)
- gaze_y = np.zeros(pupil_labs_eye_data.pupil_center_normal_y.shape) * np.nanmedian(self.fixation_distance)
- gaze_z = np.ones(pupil_labs_eye_data.pupil_center_normal_z.shape) * np.nanmedian(self.fixation_distance)
-
- self.uncalibrated_gaze_vector_endpoint_fr_xyz = self.rotate_gaze_lasers([0, 0, 0],
- eye_socket_origin_fr_xyz,
- eye_socket_rotation_matricies,
- head_rotation_matricies,
- gaze_x,
- gaze_y,
- gaze_z)
-
- self.calibrated_rotational_offset = self.calculate_optimal_rotational_offset(eye_socket_origin_fr_xyz,
- eye_socket_rotation_matricies,
- head_rotation_matricies,
- fixation_point_fr_xyz,
- gaze_x,
- gaze_y,
- gaze_z)
-
- gaze_vector_endpoint_fr_xyz = self.rotate_gaze_lasers(self.calibrated_rotational_offset,
- eye_socket_origin_fr_xyz,
- eye_socket_rotation_matricies,
- head_rotation_matricies,
- gaze_x,
- gaze_y,
- gaze_z
- )
-
- return gaze_vector_endpoint_fr_xyz
-
- def calculate_optimal_rotational_offset(self,
- eye_socket_origin_fr_xyz: np.ndarray,
- eye_socket_rotation_matricies: List[np.ndarray],
- head_rotation_matricies,
- fixation_point_fr_xyz: np.ndarray,
- gaze_x: np.ndarray,
- gaze_y: np.ndarray,
- gaze_z: np.ndarray) -> List[float]:
- """
- Calculate the optimal rotational offset to apply to Pupil Labs eye tracker data in order to minimize the distance
- between teh end of the gaze vector and the fixation point on each frame
- (based on the VOR calibration methods described in Matthis, Yates, and Hayhoe, Current Biology, 2018 and Matthis, Muller, Bonnen, Hayhoe, PLoS Computation Biology 2022)
-
- """
- initial_rotational_offset_guess = [0, 0, 0]
-
- vor_frames = np.arange(self.vor_start_frame, self.vor_end_frame)
-
- optimization_results = optimize.least_squares(self.get_error_for_a_given_rotational_offset_guess,
- initial_rotational_offset_guess,
- args=(eye_socket_origin_fr_xyz[vor_frames, :],
- eye_socket_rotation_matricies[
- self.vor_start_frame:self.vor_end_frame],
- head_rotation_matricies[
- self.vor_start_frame:self.vor_end_frame],
- fixation_point_fr_xyz,
- gaze_x[vor_frames],
- gaze_y[vor_frames],
- gaze_z[vor_frames],),
- gtol=1e-10,
- verbose=2)
- calibrated_rotational_offset = optimization_results.x
- return calibrated_rotational_offset
-
- def get_error_for_a_given_rotational_offset_guess(self,
- rotational_offset_guess,
- eye_socket_origin_fr_xyz,
- eye_socket_rotation_matricies,
- head_rotation_matricies,
- fixation_point_fr_xyz,
- gaze_x,
- gaze_y,
- gaze_z):
-
- gaze_laser_endpoint_during_vor_fr_xyz = self.rotate_gaze_lasers(rotational_offset_guess,
- eye_socket_origin_fr_xyz,
- eye_socket_rotation_matricies,
- head_rotation_matricies,
- gaze_x,
- gaze_y,
- gaze_z)
-
- distance_between_gaze_endpoint_and_fixation_point_fr_xyz = self.get_distance_between_two_points(
- gaze_laser_endpoint_during_vor_fr_xyz,
- fixation_point_fr_xyz)
- distance_error = np.sqrt(np.nanmean(distance_between_gaze_endpoint_and_fixation_point_fr_xyz ** 2))
-
- gaze_tip_velocity_fr_xyz = np.diff(gaze_laser_endpoint_during_vor_fr_xyz, axis=0)
- mean_gaze_tip_velocity_per_frame = np.nanmean(gaze_tip_velocity_fr_xyz, axis=0)
- velocity_error = np.sqrt(np.nanmean(mean_gaze_tip_velocity_per_frame ** 2))
-
- error = distance_error + velocity_error
-
- if self.debug:
- self.plot_optimization_error(error, gaze_laser_endpoint_during_vor_fr_xyz, eye_socket_origin_fr_xyz,
- fixation_point_fr_xyz)
- return error
-
- def plot_optimization_error(self, error, gaze_laser_endpoint_during_vor_fr_xyz, eye_socket_origin_fr_xyz,
- fixation_point_fr_xyz):
- figure_number = 13451
-
- if not plt.fignum_exists(figure_number):
- fig = plt.figure(figure_number)
- ax = fig.add_subplot(111, projection='3d')
- else:
- fig = plt.gcf()
- ax = plt.gca()
-
- mean_eye_origin_x = np.nanmean(eye_socket_origin_fr_xyz[:, 0])
- mean_eye_origin_y = np.nanmean(eye_socket_origin_fr_xyz[:, 1])
- mean_eye_origin_z = np.nanmean(eye_socket_origin_fr_xyz[:, 2])
-
- fig.suptitle(f'error: {error}')
- ax_range = 1e3
- ax.clear()
-
- ax.plot(mean_eye_origin_x, mean_eye_origin_y, mean_eye_origin_z, 'mh', label='mean eye origin')
-
- ax.plot(self.uncalibrated_gaze_vector_endpoint_fr_xyz[self.vor_start_frame:self.vor_end_frame, 0],
- self.uncalibrated_gaze_vector_endpoint_fr_xyz[self.vor_start_frame:self.vor_end_frame, 1],
- self.uncalibrated_gaze_vector_endpoint_fr_xyz[self.vor_start_frame:self.vor_end_frame, 2], 'k-o',
- label='original gaze xyz')
-
- ax.plot(gaze_laser_endpoint_during_vor_fr_xyz[:, 0],
- gaze_laser_endpoint_during_vor_fr_xyz[:, 1],
- gaze_laser_endpoint_during_vor_fr_xyz[:, 2], 'r-o',
- label='gaze_rotated_by_guess_then_head_rotation_xyz')
-
- ax.plot(fixation_point_fr_xyz[:, 0],
- fixation_point_fr_xyz[:, 1],
- fixation_point_fr_xyz[:, 2], 'b-o', label='mean_fixation_point_xyz')
-
- ax.set_xlim([mean_eye_origin_x - ax_range, mean_eye_origin_x + ax_range])
- ax.set_ylim([mean_eye_origin_y - ax_range, mean_eye_origin_y + ax_range])
- ax.set_zlim([mean_eye_origin_z - ax_range, mean_eye_origin_z + ax_range])
- ax.legend()
- plt.pause(.01)
-
- if keyboard.is_pressed('esc'):
- print('You Pressed Escape!')
- self.debug = False
- plt.close(fig)
-
- def get_distance_between_two_points(self, local_origin_fr_xyz, fixation_point_fr_xyz):
- return np.linalg.norm(local_origin_fr_xyz - fixation_point_fr_xyz, axis=1)
-
- def create_unrotated_gaze_lasers_from_eye_rotation_matrixies(self,
- gaze_vector_start_point_fr_xyz: np.ndarray,
- gaze_unit_vector_end_point_fr_xyz: np.ndarray,
- calbration_distance,
- ) -> np.ndarray:
- """
- Creates an unrotated gaze laser for each frame in the skeleton/gaze data. Returns a vector the same length as the calibration_distance, shooting our of the skeletons eye_sockets (as if they eyes were paralyzed).
- """
- if not gaze_vector_start_point_fr_xyz.shape == gaze_unit_vector_end_point_fr_xyz.shape:
- raise Exception(
- "`gaze_vector_start_point_fr_xyz` and `gaze_unit_vector_end_point_fr_xyz` must have the same shape")
-
- # scale gaze vector so it's the same norm/length as the calibration distance
- gaze_unit_vector_end_point_fr_xyz = gaze_unit_vector_end_point_fr_xyz * calbration_distance
-
- # move it from an zero-centered reference frame to the eye socket reference frame
- gaze_vector_end_point_fr_xyz = gaze_unit_vector_end_point_fr_xyz + gaze_vector_start_point_fr_xyz
-
- return gaze_vector_end_point_fr_xyz
-
- def rotate_gaze_lasers(self,
- rotational_offset,
- gaze_vector_start_point_fr_xyz,
- eye_socket_rotation_matricies,
- head_rotation_matricies,
- gaze_x,
- gaze_y,
- gaze_z) -> np.ndarray:
- """"
- - pin gaze to origin
- - rotate gaze vector by `calibrated_rotational_offset`
- - rotate by measured eye movemens (from pupil labs)
- - translate gaze vector back to the eye socket (by adding eyeball center xyz)
- """
-
- # - rotate gaze vector by `calibrated_rotational_offset`
- offset_x_euler = rotational_offset[0]
- offset_y_euler = rotational_offset[1]
- offset_z_euler = rotational_offset[2]
- offset_rotation_matrix_guess = Rotation.from_euler('xyz',
- (offset_x_euler, offset_y_euler, offset_z_euler)).as_matrix()
-
- original_gaze_fr_xyz = np.array([gaze_x, gaze_y, gaze_z])
-
- # rotate gaze vector by rotational offset to align pupil labs gaze with the eye sockets gaze
- gaze_rotated_by_guess_fr_xyz = [
- offset_rotation_matrix_guess @ original_gaze_fr_xyz[:, this_frame_number] for
- this_frame_number in
- range(original_gaze_fr_xyz.shape[1])]
- gaze_rotated_by_guess_fr_xyz = np.array(gaze_rotated_by_guess_fr_xyz)
-
- # THEN rotate gaze vector by eye_socket_rotation_matrix to align it with the eye sockets gaze direction (i think)
- gaze_fr_xyz = [
- np.transpose(head_rotation_matricies[this_frame_number]) @ gaze_rotated_by_guess_fr_xyz[
- this_frame_number, :] for
- this_frame_number in
- range(gaze_rotated_by_guess_fr_xyz.shape[0])]
- gaze_fr_xyz = np.array(gaze_fr_xyz)
-
- # 6 - translate gaze vector back to the eye socket (by adding eyeball center xyz)
- gaze_laser_fr_xyz = np.empty(gaze_fr_xyz.shape)
- gaze_laser_fr_xyz[:, 0] = gaze_fr_xyz[:, 0] + gaze_vector_start_point_fr_xyz[:, 0]
- gaze_laser_fr_xyz[:, 1] = gaze_fr_xyz[:, 1] + gaze_vector_start_point_fr_xyz[:, 1]
- gaze_laser_fr_xyz[:, 2] = gaze_fr_xyz[:, 2] + gaze_vector_start_point_fr_xyz[:, 2]
-
- return gaze_laser_fr_xyz
diff --git a/jon_scratch/run_window.py b/jon_scratch/run_window.py
deleted file mode 100644
index f32c0d27..00000000
--- a/jon_scratch/run_window.py
+++ /dev/null
@@ -1,8 +0,0 @@
-import time
-import cv2
-
-while True:
- cv2.namedWindow("test")
- key = cv2.waitKey(0)
- if key == 27:
- break
diff --git a/jon_scratch/sleap/__init__.py b/jon_scratch/sleap/__init__.py
deleted file mode 100644
index e69de29b..00000000
diff --git a/jon_scratch/sleap/load_sleap_tracks_to_blender.py b/jon_scratch/sleap/load_sleap_tracks_to_blender.py
deleted file mode 100644
index e48ed557..00000000
--- a/jon_scratch/sleap/load_sleap_tracks_to_blender.py
+++ /dev/null
@@ -1,37 +0,0 @@
-import bpy
-import numpy as np
-
-print("loading gaze data as empties")
-
-path_to_sleap_xyz_npy_path = r"C:\Users\jonma\Dropbox\FreeMoCapProject\FreeMocap_Data\sesh_2022-05-07_17_15_05_pupil_wobble_juggle_0\DataArrays\sleap_3d_points.npy"
-sleap_fr_mar_xyz = np.load(path_to_sleap_xyz_npy_path)
-
-
-print(f'shape of sleap_fr_mar_xyz: {sleap_fr_mar_xyz.shape}')
-
-sleap_fr_mar_x = sleap_fr_mar_xyz[:,:,0]*.001
-sleap_fr_mar_y = sleap_fr_mar_xyz[:,:,1]*.001
-sleap_fr_mar_z = sleap_fr_mar_xyz[:,:,2]*.001
-
-#%%
-print(f'loading sleap_data...')
-
-
-for this_sleap_track_num in range(sleap_fr_mar_xyz.shape[1]):
- bpy.ops.object.empty_add(type='PLAIN_AXES')
- this_empty = bpy.context.active_object
- print(this_empty)
- for frame_num in range(sleap_fr_mar_xyz.shape[0]):
- if frame_num % 100 == 0:
- print(f'frame {frame_num}')
-
- this_empty.location = (sleap_fr_mar_x[frame_num, this_sleap_track_num],
- sleap_fr_mar_y[frame_num, this_sleap_track_num],
- sleap_fr_mar_z[frame_num, this_sleap_track_num])
- this_empty.scale = (0.1, 0.1, .1)
-
- # this_empty.name = 'right_eye_gaze'
- bpy.context.view_layer.update()
- this_empty.keyframe_insert(data_path='location',frame=frame_num)
-
-print('done!')
\ No newline at end of file
diff --git a/jon_scratch/sleap/sleap_freemocap_processing copy.ipynb b/jon_scratch/sleap/sleap_freemocap_processing copy.ipynb
deleted file mode 100644
index ef40f088..00000000
--- a/jon_scratch/sleap/sleap_freemocap_processing copy.ipynb
+++ /dev/null
@@ -1,505 +0,0 @@
-{
- "cells": [
- {
- "cell_type": "markdown",
- "metadata": {
- "collapsed": false,
- "pycharm": {
- "name": "#%% md\n"
- }
- },
- "source": [
- "# notebook to post-process results from SLEAP into freemocap format\n",
- "\n",
- "expected processing steps:\n",
- "\n",
- "1 - load data from SLEAP h5's (one per video, produced by SLEAP's GUI process)\n",
- "2 - Reformat into standard freemocap 2d npy format (dimensions: camera, frame, marker, XY)\n",
- "2a,b - save and test by producing annotated videos\n",
- "3 - triangulate using anipose triangulation\n",
- "4 - save triangulation results to freemocap formated 3d npy (frame, marker, XYZ) (and another npy for reprojection error)"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 9,
- "metadata": {
- "collapsed": false,
- "pycharm": {
- "name": "#%%\n"
- }
- },
- "outputs": [
- {
- "ename": "ModuleNotFoundError",
- "evalue": "No module named 'sleap'",
- "output_type": "error",
- "traceback": [
- "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",
- "\u001b[1;31mModuleNotFoundError\u001b[0m Traceback (most recent call last)",
- "\u001b[1;32m~\\AppData\\Local\\Temp\\ipykernel_61232\\3622061885.py\u001b[0m in \u001b[0;36m<module>\u001b[1;34m\u001b[0m\n\u001b[0;32m 3\u001b[0m \u001b[1;32mfrom\u001b[0m \u001b[0mpathlib\u001b[0m \u001b[1;32mimport\u001b[0m \u001b[0mPath\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m 4\u001b[0m \u001b[1;32mfrom\u001b[0m \u001b[0maniposelib\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mcameras\u001b[0m \u001b[1;32mimport\u001b[0m \u001b[0mCameraGroup\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m----> 5\u001b[1;33m \u001b[1;32mimport\u001b[0m \u001b[0msleap\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m",
- "\u001b[1;31mModuleNotFoundError\u001b[0m: No module named 'sleap'"
- ]
- }
- ],
- "source": [
- "import numpy as np\n",
- "import h5py\n",
- "from pathlib import Path\n",
- "from aniposelib.cameras import CameraGroup\n",
- "import sleap"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": []
- },
- {
- "cell_type": "code",
- "execution_count": 7,
- "metadata": {
- "collapsed": false,
- "pycharm": {
- "name": "#%%\n"
- }
- },
- "outputs": [],
- "source": [
- "session_id = 'sesh_2022-05-07_17_15_05_pupil_wobble_juggle_0'\n",
- "\n",
- "freemocap_data_folder = Path('C:/Users/jonma/Dropbox/FreeMoCapProject/FreeMocap_Data')\n",
- "\n",
- "session_folder_path = freemocap_data_folder / session_id\n",
- "\n",
- "calibration_file_name = session_id + '_calibration.toml'\n",
- "camera_calibration_file_path = session_folder_path / calibration_file_name\n",
- "\n",
- "sleap_data_path = session_folder_path / 'sleap_data'\n",
- "sleap_h5_files_path = sleap_data_path / 'output_h5_files'\n",
- "\n",
- "sleap_predictions_file = sleap_data_path / 'labels.v000.slp'"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 8,
- "metadata": {},
- "outputs": [
- {
- "ename": "NameError",
- "evalue": "name 'sleap' is not defined",
- "output_type": "error",
- "traceback": [
- "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",
- "\u001b[1;31mNameError\u001b[0m Traceback (most recent call last)",
- "\u001b[1;32m~\\AppData\\Local\\Temp\\ipykernel_61232\\726452517.py\u001b[0m in \u001b[0;36m<module>\u001b[1;34m\u001b[0m\n\u001b[1;32m----> 1\u001b[1;33m \u001b[0msleap_labels_object\u001b[0m \u001b[1;33m=\u001b[0m \u001b[0msleap\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mload_file\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mstr\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0msleap_predictions_file\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m\u001b[0;32m 2\u001b[0m \u001b[0msleap_labels_object\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n",
- "\u001b[1;31mNameError\u001b[0m: name 'sleap' is not defined"
- ]
- }
- ],
- "source": [
- "sleap_labels_object = sleap.load_file(str(sleap_predictions_file))\n",
- "sleap_labels_object"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 3,
- "metadata": {
- "collapsed": false,
- "pycharm": {
- "name": "#%%\n"
- }
- },
- "outputs": [],
- "source": [
- "anipose_camera_calibration_object = CameraGroup.load(camera_calibration_file_path)"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 4,
- "metadata": {
- "collapsed": false,
- "pycharm": {
- "name": "#%%\n"
- }
- },
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "===filename===\n",
- "C:\\Users\\jonma\\Dropbox\\FreeMoCapProject\\FreeMocap_Data\\sesh_2022-05-07_17_15_05_pupil_wobble_juggle_0\\sleap_data\\output_h5_files\\labels_v000_analysis_video_0.h5\n",
- "\n",
- "===HDF5 datasets===\n",
- "['edge_inds', 'edge_names', 'instance_scores', 'node_names', 'point_scores', 'track_names', 'track_occupancy', 'tracking_scores', 'tracks']\n",
- "\n",
- "===locations data shape===\n",
- "(5090, 10, 2, 1)\n",
- "\n",
- "===nodes===\n",
- "0: red_ball\n",
- "1: green_ball\n",
- "2: orange_ball\n",
- "3: wobble_0\n",
- "4: wobble_1\n",
- "5: wobble_2\n",
- "6: wobble_3\n",
- "7: wobble_4\n",
- "8: wheel_center\n",
- "9: wheel_edge\n",
- "\n",
- "===filename===\n",
- "C:\\Users\\jonma\\Dropbox\\FreeMoCapProject\\FreeMocap_Data\\sesh_2022-05-07_17_15_05_pupil_wobble_juggle_0\\sleap_data\\output_h5_files\\labels_v000_analysis_video_1.h5\n",
- "\n",
- "===HDF5 datasets===\n",
- "['edge_inds', 'edge_names', 'instance_scores', 'node_names', 'point_scores', 'track_names', 'track_occupancy', 'tracking_scores', 'tracks']\n",
- "\n",
- "===locations data shape===\n",
- "(5090, 10, 2, 1)\n",
- "\n",
- "===nodes===\n",
- "0: red_ball\n",
- "1: green_ball\n",
- "2: orange_ball\n",
- "3: wobble_0\n",
- "4: wobble_1\n",
- "5: wobble_2\n",
- "6: wobble_3\n",
- "7: wobble_4\n",
- "8: wheel_center\n",
- "9: wheel_edge\n",
- "\n",
- "===filename===\n",
- "C:\\Users\\jonma\\Dropbox\\FreeMoCapProject\\FreeMocap_Data\\sesh_2022-05-07_17_15_05_pupil_wobble_juggle_0\\sleap_data\\output_h5_files\\labels_v000_analysis_video_2.h5\n",
- "\n",
- "===HDF5 datasets===\n",
- "['edge_inds', 'edge_names', 'instance_scores', 'node_names', 'point_scores', 'track_names', 'track_occupancy', 'tracking_scores', 'tracks']\n",
- "\n",
- "===locations data shape===\n",
- "(5090, 10, 2, 1)\n",
- "\n",
- "===nodes===\n",
- "0: red_ball\n",
- "1: green_ball\n",
- "2: orange_ball\n",
- "3: wobble_0\n",
- "4: wobble_1\n",
- "5: wobble_2\n",
- "6: wobble_3\n",
- "7: wobble_4\n",
- "8: wheel_center\n",
- "9: wheel_edge\n",
- "\n",
- "===filename===\n",
- "C:\\Users\\jonma\\Dropbox\\FreeMoCapProject\\FreeMocap_Data\\sesh_2022-05-07_17_15_05_pupil_wobble_juggle_0\\sleap_data\\output_h5_files\\labels_v000_analysis_video_3.h5\n",
- "\n",
- "===HDF5 datasets===\n",
- "['edge_inds', 'edge_names', 'instance_scores', 'node_names', 'point_scores', 'track_names', 'track_occupancy', 'tracking_scores', 'tracks']\n",
- "\n",
- "===locations data shape===\n",
- "(5090, 10, 2, 1)\n",
- "\n",
- "===nodes===\n",
- "0: red_ball\n",
- "1: green_ball\n",
- "2: orange_ball\n",
- "3: wobble_0\n",
- "4: wobble_1\n",
- "5: wobble_2\n",
- "6: wobble_3\n",
- "7: wobble_4\n",
- "8: wheel_center\n",
- "9: wheel_edge\n",
- "\n",
- "===filename===\n",
- "C:\\Users\\jonma\\Dropbox\\FreeMoCapProject\\FreeMocap_Data\\sesh_2022-05-07_17_15_05_pupil_wobble_juggle_0\\sleap_data\\output_h5_files\\labels_v000_analysis_video_4.h5\n",
- "\n",
- "===HDF5 datasets===\n",
- "['edge_inds', 'edge_names', 'instance_scores', 'node_names', 'point_scores', 'track_names', 'track_occupancy', 'tracking_scores', 'tracks']\n",
- "\n",
- "===locations data shape===\n",
- "(5090, 10, 2, 1)\n",
- "\n",
- "===nodes===\n",
- "0: red_ball\n",
- "1: green_ball\n",
- "2: orange_ball\n",
- "3: wobble_0\n",
- "4: wobble_1\n",
- "5: wobble_2\n",
- "6: wobble_3\n",
- "7: wobble_4\n",
- "8: wheel_center\n",
- "9: wheel_edge\n",
- "\n"
- ]
- }
- ],
- "source": [
- "\n",
- "\n",
- "per_video_labels_fr_point_xy = []\n",
- "per_video_label_names = []\n",
- "for this_h5_file in sleap_h5_files_path.glob('*.h5'):\n",
- " with h5py.File(this_h5_file, \"r\") as f:\n",
- " dset_names = list(f.keys())\n",
- " locations = f[\"tracks\"][:].T\n",
- " node_names = [n.decode() for n in f[\"node_names\"][:]]\n",
- "\n",
- " per_video_labels_fr_point_xy.append(locations)\n",
- " per_video_label_names.append(node_names)\n",
- " print(\"===filename===\")\n",
- " print(this_h5_file)\n",
- " print()\n",
- "\n",
- " print(\"===HDF5 datasets===\")\n",
- " print(dset_names)\n",
- " print()\n",
- "\n",
- " print(\"===locations data shape===\")\n",
- " print(locations.shape)\n",
- " print()\n",
- "\n",
- " print(\"===nodes===\")\n",
- " for i, name in enumerate(node_names):\n",
- " print(f\"{i}: {name}\")\n",
- " print()\n",
- "\n",
- "\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 5,
- "metadata": {
- "collapsed": false,
- "pycharm": {
- "name": "#%%\n"
- }
- },
- "outputs": [],
- "source": [
- "number_of_videos = len(per_video_labels_fr_point_xy)\n",
- "number_of_frames = len(per_video_labels_fr_point_xy[0])\n",
- "number_of_markers = len(per_video_labels_fr_point_xy[0][0])\n",
- "sleap2d_nCams_nFrames_nImgPts_XY = np.empty((number_of_videos, number_of_frames, number_of_markers, 2))"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "put data into freemocap 2d_npy format"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 6,
- "metadata": {
- "collapsed": false,
- "pycharm": {
- "name": "#%%\n"
- }
- },
- "outputs": [
- {
- "data": {
- "text/plain": [
- "(5, 5090, 10, 2)"
- ]
- },
- "execution_count": 6,
- "metadata": {},
- "output_type": "execute_result"
- }
- ],
- "source": [
- "for this_video_number in range(len(per_video_labels_fr_point_xy)):\n",
- " sleap2d_nCams_nFrames_nImgPts_XY[this_video_number,:,:,:] = np.squeeze(per_video_labels_fr_point_xy[this_video_number])\n",
- "\n",
- "sleap2d_nCams_nFrames_nImgPts_XY.shape"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "load anipose calibration cgroup whosit"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 7,
- "metadata": {
- "collapsed": false,
- "pycharm": {
- "name": "#%%\n"
- }
- },
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "Reconstructing 3d points...\n"
- ]
- },
- {
- "name": "stderr",
- "output_type": "stream",
- "text": [
- "100%|β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ| 50900/50900 [00:08<00:00, 6245.40it/s]\n"
- ]
- }
- ],
- "source": [
- "\n",
- "sleap_flattened_nCams_nTotalPoints_XY = sleap2d_nCams_nFrames_nImgPts_XY.reshape(number_of_videos, -1, 2) # reshape data to collapse across 'frames' so it becomes [numCams, numFrames*numPoints, XY]\n",
- "\n",
- "print('Reconstructing 3d points...')\n",
- "sleap_data3d_flat = anipose_camera_calibration_object.triangulate(sleap_flattened_nCams_nTotalPoints_XY, progress=True)\n",
- "\n",
- "sleap_data_reprojerr_flat = anipose_camera_calibration_object.reprojection_error( sleap_data3d_flat, sleap_flattened_nCams_nTotalPoints_XY, mean=True)\n",
- "\n",
- "##return:\n",
- "sleap_fr_mar_xyz = sleap_data3d_flat.reshape(number_of_frames, number_of_markers, 3)\n",
- "sleap_fr_mar_reprojectionError = sleap_data_reprojerr_flat.reshape(number_of_frames, number_of_markers)\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 8,
- "metadata": {},
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "sleap_fr_mar_xyz.shape: (5090, 10, 3)\n",
- "sleap_fr_mar_reprojectionError.shape: (5090, 10)\n"
- ]
- }
- ],
- "source": [
- "\n",
- "print(f'sleap_fr_mar_xyz.shape: {sleap_fr_mar_xyz.shape}')\n",
- "print(f'sleap_fr_mar_reprojectionError.shape: {sleap_fr_mar_reprojectionError.shape}')"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 9,
- "metadata": {},
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "Using matplotlib backend: TkAgg\n"
- ]
- }
- ],
- "source": [
- "import matplotlib.pyplot as plt\n",
- "%matplotlib \n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 10,
- "metadata": {},
- "outputs": [],
- "source": [
- "plt.close('all')\n",
- "fig = plt.figure()\n",
- "\n",
- "for this_marker_number in range(sleap_fr_mar_xyz.shape[1]):\n",
- " ax = fig.add_subplot(5,2,this_marker_number+1)\n",
- " ax.plot(sleap_fr_mar_xyz[:,this_marker_number,:])"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "save sleap data to `DataArrays` folder "
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 11,
- "metadata": {},
- "outputs": [],
- "source": [
- "session_data_arrays_path = session_folder_path / 'DataArrays'\n",
- "\n",
- "sleap_3d_save_path = session_data_arrays_path / 'sleap_3d_points.npy'\n",
- "sleap_reproj_err_save_path = session_data_arrays_path / 'sleap_reprojection_error.npy'\n",
- "label_name_csv_path = session_data_arrays_path / 'sleap_label_names.csv'\n",
- "\n",
- "np.save(sleap_3d_save_path, sleap_fr_mar_xyz)\n",
- "np.save(sleap_reproj_err_save_path, sleap_fr_mar_reprojectionError)\n",
- "\n",
- "import csv\n",
- "with open(label_name_csv_path,'w') as label_name_file:\n",
- " wr = csv.writer(label_name_file)\n",
- " wr.writerow(node_names)"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 17,
- "metadata": {},
- "outputs": [
- {
- "data": {
- "text/plain": [
- "(5090,)"
- ]
- },
- "execution_count": 17,
- "metadata": {},
- "output_type": "execute_result"
- }
- ],
- "source": [
- "sleap_fr_mar_xyz[:,5,0].shape"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": []
- }
- ],
- "metadata": {
- "interpreter": {
- "hash": "122c9931a57dd91c579842728ee2ee1c7ffefd770186c077f442b22e7e57f48e"
- },
- "kernelspec": {
- "display_name": "Python 3.7.13 ('freemocap-env')",
- "language": "python",
- "name": "python3"
- },
- "language_info": {
- "codemirror_mode": {
- "name": "ipython",
- "version": 3
- },
- "file_extension": ".py",
- "mimetype": "text/x-python",
- "name": "python",
- "nbconvert_exporter": "python",
- "pygments_lexer": "ipython3",
- "version": "3.7.13"
- }
- },
- "nbformat": 4,
- "nbformat_minor": 0
-}
diff --git a/jon_scratch/sleap/sleap_freemocap_processing.ipynb b/jon_scratch/sleap/sleap_freemocap_processing.ipynb
deleted file mode 100644
index 07072623..00000000
--- a/jon_scratch/sleap/sleap_freemocap_processing.ipynb
+++ /dev/null
@@ -1,529 +0,0 @@
-{
- "cells": [
- {
- "cell_type": "markdown",
- "metadata": {
- "collapsed": false,
- "pycharm": {
- "name": "#%% md\n"
- }
- },
- "source": [
- "# notebook to post-process results from SLEAP into freemocap format\n",
- "\n",
- "expected processing steps:\n",
- "\n",
- "1 - load data from SLEAP h5's (one per video, produced by SLEAP's GUI process)\n",
- "2 - Reformat into standard freemocap 2d npy format (dimensions: camera, frame, marker, XY)\n",
- "2a,b - save and test by producing annotated videos\n",
- "3 - triangulate using anipose triangulation\n",
- "4 - save triangulation results to freemocap formated 3d npy (frame, marker, XYZ) (and another npy for reprojection error)"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "outputs": [],
- "source": [
- "import numpy as np\n",
- "import h5py\n",
- "from pathlib import Path\n",
- "from aniposelib.cameras import CameraGroup\n"
- ],
- "metadata": {
- "collapsed": false,
- "pycharm": {
- "name": "#%%\n"
- }
- }
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "outputs": [],
- "source": [
- "session_id = 'sesh_2022-05-07_17_15_05_pupil_wobble_juggle_0'\n",
- "\n",
- "freemocap_data_folder = Path('C:/Users/jonma/Dropbox/FreeMoCapProject/FreeMocap_Data')\n",
- "\n",
- "session_folder_path = freemocap_data_folder / session_id\n",
- "\n",
- "calibration_file_name = session_id + '_calibration.toml'\n",
- "camera_calibration_file_path = session_folder_path / calibration_file_name\n",
- "\n",
- "sleap_data_path = session_folder_path / 'sleap_data'\n",
- "sleap_h5_files_path = sleap_data_path / 'output_h5_files'\n",
- "\n",
- "sleap_predictions_file = sleap_data_path / 'labels.v000.slp'"
- ],
- "metadata": {
- "collapsed": false,
- "pycharm": {
- "name": "#%%\n"
- }
- }
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "outputs": [],
- "source": [
- "anipose_camera_calibration_object = CameraGroup.load(camera_calibration_file_path)"
- ],
- "metadata": {
- "collapsed": false,
- "pycharm": {
- "name": "#%%\n"
- }
- }
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "outputs": [],
- "source": [
- "\n",
- "\n",
- "per_video_labels_fr_point_xy = []\n",
- "per_video_label_names = []\n",
- "for this_h5_file in sleap_h5_files_path.glob('*.h5'):\n",
- " with h5py.File(this_h5_file, \"r\") as f:\n",
- " dset_names = list(f.keys())\n",
- " locations = f[\"tracks\"][:].T\n",
- " node_names = [n.decode() for n in f[\"node_names\"][:]]\n",
- "\n",
- " per_video_labels_fr_point_xy.append(locations)\n",
- " per_video_label_names.append(node_names)\n",
- " print(\"===filename===\")\n",
- " print(this_h5_file)\n",
- " print()\n",
- "\n",
- " print(\"===HDF5 datasets===\")\n",
- " print(dset_names)\n",
- " print()\n",
- "\n",
- " print(\"===locations data shape===\")\n",
- " print(locations.shape)\n",
- " print()\n",
- "\n",
- " print(\"===nodes===\")\n",
- " for i, name in enumerate(node_names):\n",
- " print(f\"{i}: {name}\")\n",
- " print()\n",
- "\n",
- "\n"
- ],
- "metadata": {
- "collapsed": false,
- "pycharm": {
- "name": "#%%\n"
- }
- }
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "outputs": [],
- "source": [
- "number_of_videos = len(per_video_labels_fr_point_xy)\n",
- "number_of_frames = len(per_video_labels_fr_point_xy[0])\n",
- "number_of_markers = len(per_video_labels_fr_point_xy[0][0])\n",
- "sleap2d_nCams_nFrames_nImgPts_XY = np.empty((number_of_videos, number_of_frames, number_of_markers, 2))"
- ],
- "metadata": {
- "collapsed": false,
- "pycharm": {
- "name": "#%%\n"
- }
- }
- },
- {
- "cell_type": "markdown",
- "source": [
- "put data into freemocap 2d_npy format"
- ],
- "metadata": {
- "collapsed": false,
- "pycharm": {
- "name": "#%% md\n"
- }
- }
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "outputs": [],
- "source": [
- "for this_video_number in range(len(per_video_labels_fr_point_xy)):\n",
- " sleap2d_nCams_nFrames_nImgPts_XY[this_video_number,:,:,:] = np.squeeze(per_video_labels_fr_point_xy[this_video_number])\n",
- "\n",
- "sleap2d_nCams_nFrames_nImgPts_XY.shape"
- ],
- "metadata": {
- "collapsed": false,
- "pycharm": {
- "name": "#%%\n"
- }
- }
- },
- {
- "cell_type": "markdown",
- "source": [
- "load anipose calibration cgroup whosit"
- ],
- "metadata": {
- "collapsed": false,
- "pycharm": {
- "name": "#%% md\n"
- }
- }
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "outputs": [],
- "source": [
- "\n",
- "sleap_flattened_nCams_nTotalPoints_XY = sleap2d_nCams_nFrames_nImgPts_XY.reshape(number_of_videos, -1, 2) # reshape data to collapse across 'frames' so it becomes [numCams, numFrames*numPoints, XY]\n",
- "\n",
- "print('Reconstructing 3d points...')\n",
- "sleap_data3d_flat = anipose_camera_calibration_object.triangulate(sleap_flattened_nCams_nTotalPoints_XY, progress=True)\n",
- "\n",
- "sleap_data_reprojerr_flat = anipose_camera_calibration_object.reprojection_error( sleap_data3d_flat, sleap_flattened_nCams_nTotalPoints_XY, mean=True)\n",
- "\n",
- "##return:\n",
- "sleap_fr_mar_xyz = sleap_data3d_flat.reshape(number_of_frames, number_of_markers, 3)\n",
- "sleap_fr_mar_reprojectionError = sleap_data_reprojerr_flat.reshape(number_of_frames, number_of_markers)\n"
- ],
- "metadata": {
- "collapsed": false,
- "pycharm": {
- "name": "#%%\n"
- }
- }
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "outputs": [],
- "source": [
- "\n",
- "print(f'sleap_fr_mar_xyz.shape: {sleap_fr_mar_xyz.shape}')\n",
- "print(f'sleap_fr_mar_reprojectionError.shape: {sleap_fr_mar_reprojectionError.shape}')"
- ],
- "metadata": {
- "collapsed": false,
- "pycharm": {
- "name": "#%%\n"
- }
- }
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "outputs": [],
- "source": [
- "import matplotlib.pyplot as plt\n",
- "%matplotlib \n"
- ],
- "metadata": {
- "collapsed": false,
- "pycharm": {
- "name": "#%%\n"
- }
- }
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "outputs": [],
- "source": [
- "plt.close('all')\n",
- "fig = plt.figure()\n",
- "\n",
- "for this_marker_number in range(sleap_fr_mar_xyz.shape[1]):\n",
- " ax = fig.add_subplot(5,2,this_marker_number+1)\n",
- " ax.plot(sleap_fr_mar_xyz[:,this_marker_number,:])"
- ],
- "metadata": {
- "collapsed": false,
- "pycharm": {
- "name": "#%%\n"
- }
- }
- },
- {
- "cell_type": "markdown",
- "source": [
- "save sleap data to `DataArrays` folder "
- ],
- "metadata": {
- "collapsed": false,
- "pycharm": {
- "name": "#%% md\n"
- }
- }
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "outputs": [],
- "source": [
- "session_data_arrays_path = session_folder_path / 'DataArrays'\n",
- "\n",
- "sleap_3d_save_path = session_data_arrays_path / 'sleap_3d_points.npy'\n",
- "sleap_reproj_err_save_path = session_data_arrays_path / 'sleap_reprojection_error.npy'\n",
- "label_name_csv_path = session_data_arrays_path / 'sleap_label_names.csv'\n",
- "\n",
- "np.save(sleap_3d_save_path, sleap_fr_mar_xyz)\n",
- "np.save(sleap_reproj_err_save_path, sleap_fr_mar_reprojectionError)\n",
- "\n",
- "import csv\n",
- "with open(label_name_csv_path,'w') as label_name_file:\n",
- " wr = csv.writer(label_name_file)\n",
- " wr.writerow(node_names)"
- ],
- "metadata": {
- "collapsed": false,
- "pycharm": {
- "name": "#%%\n"
- }
- }
- },
- {
- "cell_type": "markdown",
- "metadata": {
- "pycharm": {
- "name": "#%% md\n"
- }
- },
- "source": [
- "put data into freemocap 2d_npy format"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 12,
- "metadata": {
- "collapsed": false,
- "pycharm": {
- "name": "#%%\n"
- }
- },
- "outputs": [
- {
- "data": {
- "text/plain": [
- "(5, 5090, 10, 2)"
- ]
- },
- "execution_count": 12,
- "metadata": {},
- "output_type": "execute_result"
- }
- ],
- "source": [
- "for this_video_number in range(len(per_video_labels_fr_point_xy)):\n",
- " sleap2d_nCams_nFrames_nImgPts_XY[this_video_number,:,:,:] = np.squeeze(per_video_labels_fr_point_xy[this_video_number])\n",
- "\n",
- "sleap2d_nCams_nFrames_nImgPts_XY.shape"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {
- "pycharm": {
- "name": "#%% md\n"
- }
- },
- "source": [
- "load anipose calibration cgroup whosit"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 13,
- "metadata": {
- "collapsed": false,
- "pycharm": {
- "name": "#%%\n"
- }
- },
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "Reconstructing 3d points...\n"
- ]
- },
- {
- "name": "stderr",
- "output_type": "stream",
- "text": [
- "100%|β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ| 50900/50900 [00:07<00:00, 6795.51it/s]\n"
- ]
- }
- ],
- "source": [
- "\n",
- "sleap_flattened_nCams_nTotalPoints_XY = sleap2d_nCams_nFrames_nImgPts_XY.reshape(number_of_videos, -1, 2) # reshape data to collapse across 'frames' so it becomes [numCams, numFrames*numPoints, XY]\n",
- "\n",
- "print('Reconstructing 3d points...')\n",
- "sleap_data3d_flat = anipose_camera_calibration_object.triangulate(sleap_flattened_nCams_nTotalPoints_XY, progress=True)\n",
- "\n",
- "sleap_data_reprojerr_flat = anipose_camera_calibration_object.reprojection_error( sleap_data3d_flat, sleap_flattened_nCams_nTotalPoints_XY, mean=True)\n",
- "\n",
- "##return:\n",
- "sleap_fr_mar_xyz = sleap_data3d_flat.reshape(number_of_frames, number_of_markers, 3)\n",
- "sleap_fr_mar_reprojectionError = sleap_data_reprojerr_flat.reshape(number_of_frames, number_of_markers)\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 14,
- "metadata": {
- "pycharm": {
- "name": "#%%\n"
- }
- },
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "sleap_fr_mar_xyz.shape: (5090, 10, 3)\n",
- "sleap_fr_mar_reprojectionError.shape: (5090, 10)\n"
- ]
- }
- ],
- "source": [
- "\n",
- "print(f'sleap_fr_mar_xyz.shape: {sleap_fr_mar_xyz.shape}')\n",
- "print(f'sleap_fr_mar_reprojectionError.shape: {sleap_fr_mar_reprojectionError.shape}')"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 15,
- "metadata": {
- "pycharm": {
- "name": "#%%\n"
- }
- },
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "Using matplotlib backend: TkAgg\n"
- ]
- }
- ],
- "source": [
- "import matplotlib.pyplot as plt\n",
- "%matplotlib \n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 22,
- "metadata": {
- "pycharm": {
- "name": "#%%\n"
- }
- },
- "outputs": [],
- "source": [
- "plt.close('all')\n",
- "fig = plt.figure()\n",
- "\n",
- "for this_marker_number in range(sleap_fr_mar_xyz.shape[1]):\n",
- " ax = fig.add_subplot(5,2,this_marker_number+1)\n",
- " ax.plot(sleap_fr_mar_xyz[:,this_marker_number,:])"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {
- "pycharm": {
- "name": "#%% md\n"
- }
- },
- "source": [
- "save sleap data to `DataArrays` folder "
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {
- "pycharm": {
- "name": "#%%\n"
- }
- },
- "outputs": [],
- "source": [
- "session_data_arrays_path = session_folder_path / 'DataArrays'\n",
- "\n",
- "sleap_3d_save_path = session_data_arrays_path / 'sleap_3d_points.npy'\n",
- "sleap_reproj_err_save_path = session_data_arrays_path / 'sleap_reprojection_error.npy'\n",
- "label_name_csv_path = session_data_arrays_path / 'sleap_label_names.csv'\n",
- "\n",
- "np.save(sleap_3d_save_path, sleap_fr_mar_xyz)\n",
- "np.save(sleap_reproj_err_save_path, sleap_fr_mar_reprojectionError)\n",
- "\n",
- "import csv\n",
- "with open(label_name_csv_path,'w') as label_name_file:\n",
- " wr = csv.writer(label_name_file)\n",
- " wr.writerow(node_names)"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {
- "pycharm": {
- "name": "#%%\n"
- }
- },
- "outputs": [],
- "source": []
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {
- "pycharm": {
- "name": "#%%\n"
- }
- },
- "outputs": [],
- "source": []
- }
- ],
- "metadata": {
- "interpreter": {
- "hash": "122c9931a57dd91c579842728ee2ee1c7ffefd770186c077f442b22e7e57f48e"
- },
- "kernelspec": {
- "display_name": "Python 3.7.13 ('freemocap-env')",
- "language": "python",
- "name": "python3"
- },
- "language_info": {
- "codemirror_mode": {
- "name": "ipython",
- "version": 3
- },
- "file_extension": ".py",
- "mimetype": "text/x-python",
- "name": "python",
- "nbconvert_exporter": "python",
- "pygments_lexer": "ipython3",
- "version": "3.7.13"
- }
- },
- "nbformat": 4,
- "nbformat_minor": 0
-}
\ No newline at end of file
diff --git a/jon_scratch/tensorflow_gpu_tester.py b/jon_scratch/tensorflow_gpu_tester.py
deleted file mode 100644
index 583ba6e8..00000000
--- a/jon_scratch/tensorflow_gpu_tester.py
+++ /dev/null
@@ -1,2 +0,0 @@
-import tensorflow as tf
-print("Num GPUs Available: ", len(tf.config.list_physical_devices('GPU')))
diff --git a/package-lock.json b/package-lock.json
deleted file mode 100644
index 1f051745..00000000
--- a/package-lock.json
+++ /dev/null
@@ -1,6 +0,0 @@
-{
- "name": "freemocap",
- "lockfileVersion": 2,
- "requires": true,
- "packages": {}
-}
diff --git a/planning/alpha_pipline_planning_notes.md b/planning/alpha_pipline_planning_notes.md
deleted file mode 100644
index d44bf92c..00000000
--- a/planning/alpha_pipline_planning_notes.md
+++ /dev/null
@@ -1,131 +0,0 @@
-# five standard states/tasks of/for the software
-
-0 - Setup and preview
- - preview camera views
- - set parameters future recordings and not
-
- - parameters to configure
- - for a given recording session, we need to know -
- ## session settings
- - base `freemocap data folder`
- - `session ID` (will become a new folder in the base data folder)
- ## calibration settings
- - `record_new_calibration?` - bool
- - `load_previous_calibration?` - bool
- - `calibrate_in_recording?` - bool
- -
- ## how to process the data in realtime
- - which tracking algorithms to apply to the data
- ### mediapipe settings
- - model_complexity
- - min_threshold_to_track_skeleton
- - min_threshold_to_reconstruct
- ### maybe some deeplabcut stuff in the future
- - path to config yaml
- ### 3d reconstuction settings
- - `reconstruction_threshold`
-
- ## camera settings
- - webcam_id:int=0
- - exposure: int = -6
- - resolution_width: int = 800
- - resolution_height: int = 600
- - save_video: bool = True
- - fourcc: str = "MJPG"
- - rotate_image: None, 90, 180, 270 #how much to rotate the image
-
- -
-
-
-
-
-
-
-
-# 1 - Calibrate
-Detect charuco boards in syncrhonized images from each camera and then send to `aniposelib` to get camera calibration.
-
-Results in a `[session_id]_calibration.toml` file saved to `session_folder` that can be used to estimate 3d points from synchronized 2d views
-
-We might also want to save this `calibration.toml` somewhere under the name `previous_calibration.toml` that can be used as a default if no other calibration file is selected (i.e. so that folks can calibrate once and then record a number of sessions in a row, assuming that the cameras dont move between sessions. We can also check `reprojection_error` and throw a warning when the errors suggest that the system needs recalibrating)
-
-#### Notes
-
-uses `aniposelib` methods, or possibly the slightly tweaked versions in `freemocap/fmc_anipose`. We'll eventually want to alter these methods to better fit our needs (I talked to the original creator and he's super into the idea, and is happy to lend help when he can (but he's distracted writing his dissertation for the next few months))
-
-#### Potential Workflow(s) -
-- NOTE - this workflow assumes a distinct separation between `calibration` and `recording,`
- - that is, the user clicks "start calibrate" button, does calibration stuff, clicks "end calibration" button (or it auto-ends)
- - We could integrate this into the `record session` behavior, but that might be a bit more complicated?
-- Calibration steps
- 1. **User** - clicks "Start Calibration"
- - starts `recording` videos from each camera
- 2. **User** - shows charucoboard to each camera, trying to get overlapping, shared views of the full board between the different cameras
- - We'll need instructions of some kind to help Users calibrate
- - Some nice visualizations on the screen will go along way
- 3. **Code** - Keep track of 'shared views' for each camera
- - i.e. frames on which (say) `camera 1` and `camera 2` both have both detected the full charuco board would lead us to increment the `shared_full_board_views` for `Camera1` and `Camera2` by `+1`
- 4. **Code** - when you have enough shared views (i.e. each camera has at least `100` shared `shared_full_board_views`, send end the recorded videos to `aniposelib`
- - We might be able to send it as a bunch of `numpy` arrays, but I think default `anipose` might require them to be saved as `mp4` files first. That's annoying, but we can fix/upgrade that later
- - `aniposelib` will produce:
- - PRIMARY OUTPUT
- - `[session_id]_calibration.toml` containing camera calibration info
- - save to `session_folder` & internally under the name `previous_calibration.toml` (see above)
- - SECONDARY OUTPUT
- - `2D` and `3D` data from `charuco_board`
- - `reprojection_error` of detected boards
- - Can be used to do a `health/quality` check of the calibration
-
-
-# 2 - Run-time processing
-This is what happens when the User presses "Record" or whatever.
-Pre-reqs:
- - Connection to synchronized cameras that can produce `multi_image_payload` on demand in a `while recording == True:` kind of loop:
- - `multi_frame_payload`: a `tuple` or `Class` of `frame_payload` objects
- - one from each camera (or an `empty` one if there's a frame drop)
- - verified to have `timestamps` within +/- `frame_interval` (or +/- `frame_interval/2`?) of each other
- - a `calibration.toml` as produced by the `Calibration` step
-
-#### Top priority- Record videos
-- Record synchronized videos from all cameras
- - minimize frame drops
- - must not lose data if there's a crash
- - must be able to re-process previously recorded videos
- - OpenCV makes this easy, as the`cv2.VideoCapture` object treats videos, USB cameras, and IP cameras equivalently
-- Results in the same number of saved video files as there are cameras
- - each video has *precisely* the same number of frames (and those frames are synchronized
- - save as `mp4` (which are easist to work with, but can't be read if there's a crash)
- - or maybe `mkv` (harder to work with, but remain viable if there is a crash)
- - maybe save as `mkv` and convert to `mp4`?
-
-#### Secondary Priority- Track 2d skeletons and generate 3d skels for real-time interactive visualization and applications (e.g. VR and whatnot)
-- For each incoming `multi_frame_payload`, process each image with `mediapipe.holistic` (in the `detect_skeletons` functionality) to estimate the `2d_skeleton`
-- once you've got a skeleton for each camera's view, combine with `calibration.toml`to get a `3D_skeleton` estimate
-- Send that `3D_skeleton` data to whatever is running the `visualization` (PyQt/OpenGL, Three.JS, Blender, etc)
-- NOTE
- - The `2d_skeleton` tracking is computationally expensive, so this part will be limited by the power of the PC that's running to recording
- - powerful enough computers may be able to reconstruct `3d_skeletons` fast enough to generate a visualization that matches the `framerate` of the camera
- - weaker computers can either:
- - Skip frames, so the framerate of the 3d visualization will be less than the cameras
- - Process all frames, so the 3d visualization is lagged vs real-time
- - decrease `model_complexity` or down-res incoming images to speed up processing
- - (but still save the full-res images to `video_files`)
- - If we can run this on `GPU` it might massively increase performance
- -
-
-
-
-# 3 - Off-line processing
-- same as (2) but using previously (or externally )recorded videoes, to be processed at 'max accuracy, fuck speed' mode.
-- Basically, you do the best you can during run time, but you make sure to save all the videos at full-fps and full-resolution so that you can go back later and re-process them with as high of accuracy as possible.
-
-# 4 - post-processing and analysis
-- do stuff with data output from 3 and/or 4. This'll mostly dumping the 2D and 3D data from sections `2` and/or `3` into `pandas.dataframe >> csv` or various format for later processing
-- I'll probably want to build some basic post-processing clean-up and analysis capacity to this system, but we can cross that bridge when we get to it.
-
-
-## Questions for those Pyuvc people - Pupil Labs
-
-1. What is a good, robust way to detect cameras on a system regardless of Operating System?
-2. Also, whats a good way to get unique identifiers for camera devices regardless of Operating System?
-3. Whats a good way to retrieve camera data for N number of cameras without incurring steep processing penalties? (Threading, Multiprocessing, other techniques?)
\ No newline at end of file
diff --git a/requirements-dev.txt b/requirements-dev.txt
deleted file mode 100644
index 3b54a372..00000000
--- a/requirements-dev.txt
+++ /dev/null
@@ -1,14 +0,0 @@
-# These are required for developing the package (running the tests, building
-# the documentation) but not necessarily required for _using_ it.
-codecov
-coverage
-flake8
-pytest
-sphinx
-twine
-# These are dependencies of various sphinx extensions for documentation.
-ipython
-matplotlib
-numpydoc
-sphinx-copybutton
-sphinx_rtd_theme
diff --git a/runme_FreeMoCap.py b/runme_FreeMoCap.py
deleted file mode 100644
index 5269c96b..00000000
--- a/runme_FreeMoCap.py
+++ /dev/null
@@ -1,4 +0,0 @@
-import freemocap as fmc
-
-fmc.RunMe(charucoSquareSize = 73, stage = 3, sessionID = 'sesh_2022-04-27_15_35_15')
-
diff --git a/src/core_processor/mediapipe_skeleton_detector/mediapipe_skeleton_detector.py b/src/core_processor/mediapipe_skeleton_detector/mediapipe_skeleton_detector.py
index 09e3bfe6..d971aaf9 100644
--- a/src/core_processor/mediapipe_skeleton_detector/mediapipe_skeleton_detector.py
+++ b/src/core_processor/mediapipe_skeleton_detector/mediapipe_skeleton_detector.py
@@ -7,7 +7,6 @@ import cv2
import numpy as np
import mediapipe as mp
-from jon_scratch.opencv_camera import TweakedModel
from src.cameras.capture.dataclasses.frame_payload import FramePayload
from src.cameras.persistence.video_writer.video_recorder import VideoRecorder
from src.config.home_dir import get_session_folder_path, get_synchronized_videos_folder_path, \
diff --git a/src/freemocap_qt_gui/conference/workflows/record_videos.py b/src/freemocap_qt_gui/conference/workflows/record_videos.py
index aac01fea..9f17783b 100644
--- a/src/freemocap_qt_gui/conference/workflows/record_videos.py
+++ b/src/freemocap_qt_gui/conference/workflows/record_videos.py
@@ -1,17 +1,16 @@
-from PyQt6.QtWidgets import QHBoxLayout, QLabel, QVBoxLayout, QWidget, QPushButton, QCheckBox
+from PyQt6.QtWidgets import QCheckBox, QHBoxLayout, QLabel, QPushButton, QVBoxLayout, QWidget
-from jon_scratch.pupil_calibration_pipeline.qt_gl_laser_skeleton_visualizer import QtGlLaserSkeletonVisualizer
from src.cameras.save_synchronized_videos import save_synchronized_videos
-from src.config.home_dir import get_most_recent_session_id
-from src.core_processor.mediapipe_skeleton_detector.mediapipe_skeleton_detector import MediaPipeSkeletonDetector
-from src.freemocap_qt_gui.conference.app import get_qt_app
+from src.core_processor.mediapipe_skeleton_detector.mediapipe_skeleton_detector import \
+ MediaPipeSkeletonDetector
from src.freemocap_qt_gui.conference.workflows.single_camera import SingleCamera
-# from src.freemocap_qt_gui.conference.workflows.visualize_session import VisualizeSkeleton
from src.freemocap_qt_gui.refactored_gui.state.app_state import APP_STATE
from src.open_in_blender.open_session_in_blender import open_session_in_blender
-from src.pipelines.calibration_pipeline.calibration_pipeline_orchestrator import CalibrationPipelineOrchestrator
-from src.pipelines.session_pipeline.session_pipeline_orchestrator import SessionPipelineOrchestrator, \
- load_mediapipe2d_data, load_mediapipe3d_skeleton_data
+from src.pipelines.calibration_pipeline.calibration_pipeline_orchestrator import \
+ CalibrationPipelineOrchestrator
+from src.pipelines.session_pipeline.session_pipeline_orchestrator import \
+ SessionPipelineOrchestrator, \
+ load_mediapipe2d_data
class RecordVideos(QWidget):
@@ -38,7 +37,7 @@ class RecordVideos(QWidget):
container.addLayout(title_layout)
container.addLayout(video_stream_layout)
- #start/stop recording button layout
+ # start/stop recording button layout
record_button_layout = QHBoxLayout()
self._start_recording_button = QPushButton('Begin Recording')
self._stop_recording_button = QPushButton('Stop Recording')
@@ -51,10 +50,10 @@ class RecordVideos(QWidget):
record_button_layout.addWidget(self._stop_recording_button)
container.addLayout(record_button_layout)
- #post-recording buttons
+ # post-recording buttons
post_recording_button_layout = QHBoxLayout()
- self._detect_2d_skeletons_button = QPushButton("Detect 2d Skeletons in Videos")
+ self._detect_2d_skeletons_button = QPushButton("Detect 2d Skeletons in Videos")
self._reconstruct_3d_skeletons_button = QPushButton("Reconstruct 3d Skeletons")
self._visualize_freemocap_session_button = QPushButton("Visualize Freemocap Session")
self._open_in_blender_button = QPushButton("Open Session in Blender")
@@ -73,11 +72,11 @@ class RecordVideos(QWidget):
container.addWidget(self._process_automatically_checkbox)
- post_recording_button_layout.addWidget( self._process_automatically_checkbox)
- post_recording_button_layout.addWidget( self._detect_2d_skeletons_button)
- post_recording_button_layout.addWidget( self._reconstruct_3d_skeletons_button)
- post_recording_button_layout.addWidget( self._visualize_freemocap_session_button)
- post_recording_button_layout.addWidget( self._open_in_blender_button)
+ post_recording_button_layout.addWidget(self._process_automatically_checkbox)
+ post_recording_button_layout.addWidget(self._detect_2d_skeletons_button)
+ post_recording_button_layout.addWidget(self._reconstruct_3d_skeletons_button)
+ post_recording_button_layout.addWidget(self._visualize_freemocap_session_button)
+ post_recording_button_layout.addWidget(self._open_in_blender_button)
container.addLayout(post_recording_button_layout)
@@ -98,7 +97,6 @@ class RecordVideos(QWidget):
for cam in self._cam_widgets:
cam.should_record_frames = True
-
def _stop_recording_frames(self):
self._stop_recording_button.setEnabled(False)
self._detect_2d_skeletons_button.setEnabled(True)
@@ -112,7 +110,6 @@ class RecordVideos(QWidget):
if self._process_automatically_checkbox.isChecked():
self._detect_2d_skeletons()
-
def _detect_2d_skeletons(self):
print(f"tracking 2D mediapipe skeletons in videos from session: {APP_STATE.session_id}")
mediapipe_skeleton_detector = MediaPipeSkeletonDetector(APP_STATE.session_id)
@@ -124,18 +121,21 @@ class RecordVideos(QWidget):
if self._process_automatically_checkbox.isChecked():
self._reconstruct_3d_skeletons()
-
def _reconstruct_3d_skeletons(self):
print(f"Reconstruct 3D Skeletons : {APP_STATE.session_id}")
session_orchestrator = SessionPipelineOrchestrator(session_id=APP_STATE.session_id)
if APP_STATE.use_previous_calibration:
- session_orchestrator.anipose_camera_calibration_object = CalibrationPipelineOrchestrator().load_most_recent_calibration()
+ session_orchestrator.anipose_camera_calibration_object = \
+ CalibrationPipelineOrchestrator().load_most_recent_calibration()
else:
- session_orchestrator.anipose_camera_calibration_object = CalibrationPipelineOrchestrator().load_calibration_from_session_id(
- APP_STATE.session_id)
+ session_orchestrator.anipose_camera_calibration_object = \
+ CalibrationPipelineOrchestrator().load_calibration_from_session_id(
+ APP_STATE.session_id)
- session_orchestrator.mediapipe2d_numCams_numFrames_numTrackedPoints_XY = load_mediapipe2d_data(APP_STATE.session_id)
+ session_orchestrator.mediapipe2d_numCams_numFrames_numTrackedPoints_XY = \
+ load_mediapipe2d_data(
+ APP_STATE.session_id)
session_orchestrator.reconstruct3d_from_2d_data_offline()
self._reconstruct_3d_skeletons_button.setEnabled(False)
@@ -144,13 +144,14 @@ class RecordVideos(QWidget):
if self._process_automatically_checkbox.isChecked():
self._create_blender_scene_from_session_data()
-
def _visualize_freemocap_session(self):
pass
# mediapipe3d_data_payload = load_mediapipe3d_skeleton_data(APP_STATE.session_id)
#
- # mediapipe3d_skeleton_nFrames_nTrajectories_xyz = mediapipe3d_data_payload.data3d_numFrames_numTrackedPoints_XYZ
- # mediapipe3d_skeleton_nFrames_nTrajectories_reprojectionError = mediapipe3d_data_payload.data3d_numFrames_numTrackedPoint_reprojectionError
+ # mediapipe3d_skeleton_nFrames_nTrajectories_xyz =
+ # mediapipe3d_data_payload.data3d_numFrames_numTrackedPoints_XYZ
+ # mediapipe3d_skeleton_nFrames_nTrajectories_reprojectionError =
+ # mediapipe3d_data_payload.data3d_numFrames_numTrackedPoint_reprojectionError
#
# visualize_skeleton_dialog = VisualizeSkeleton(
# mediapipe_skel_fr_mar_xyz=mediapipe3d_skeleton_nFrames_nTrajectories_xyz)
@@ -161,4 +162,4 @@ class RecordVideos(QWidget):
def _create_blender_scene_from_session_data(self):
print(f"Open in Blender : {APP_STATE.session_id}")
- open_session_in_blender(APP_STATE.session_id)
\ No newline at end of file
+ open_session_in_blender(APP_STATE.session_id)
diff --git a/src/pipelines/session_pipeline/session_pipeline_orchestrator.py b/src/pipelines/session_pipeline/session_pipeline_orchestrator.py
index 8ef06b44..2e8e719c 100644
--- a/src/pipelines/session_pipeline/session_pipeline_orchestrator.py
+++ b/src/pipelines/session_pipeline/session_pipeline_orchestrator.py
@@ -1,5 +1,5 @@
-import time
import logging
+import time
import traceback
from pathlib import Path
from typing import Dict, Union
@@ -7,24 +7,24 @@ from typing import Dict, Union
import cv2
import numpy as np
-from jon_scratch.pupil_calibration_pipeline.qt_gl_laser_skeleton_visualizer import QtGlLaserSkeletonVisualizer
-from src.cameras.multicam_manager.cv_camera_manager import OpenCVCameraManager
from src.cameras.persistence.video_writer.save_options_dataclass import SaveOptions
from src.config.data_paths import freemocap_data_path
-from src.config.home_dir import create_session_id, get_session_folder_path, get_session_output_data_folder_path, \
- get_most_recent_session_id, create_session_folder, get_synchronized_videos_folder_path
-from src.core_processor.camera_calibration.camera_calibrator import CameraCalibrator
-from src.core_processor.timestamp_manager.timestamp_manager import TimestampManager
-from src.core_processor.mediapipe_skeleton_detector.mediapipe_skeleton_detector import MediaPipeSkeletonDetector, \
+from src.config.home_dir import create_session_folder, create_session_id, \
+ get_most_recent_session_id, get_session_output_data_folder_path
+from src.core_processor.mediapipe_skeleton_detector.mediapipe_skeleton_detector import \
+ MediaPipeSkeletonDetector, \
Mediapipe2dDataPayload
from src.core_processor.show_cam_window import show_cam_window
+from src.core_processor.timestamp_manager.timestamp_manager import TimestampManager
from src.core_processor.utils.image_fps_writer import write_fps_to_image
-from src.debug_plot_makers.simple_plot_3d_points import simple_plot_3d
-from src.pipelines.calibration_pipeline.calibration_pipeline_orchestrator import CalibrationPipelineOrchestrator
-from src.pipelines.calibration_pipeline.charuco_board_detection.charuco_board_detector import CharucoBoardDetector
-from src.pipelines.session_pipeline.data_classes.data3d_full_session_data import Data3dFullSessionPayload
-
-from src.pipelines.session_pipeline.data_classes.data_3d_single_frame_payload import Data3dMultiFramePayload
+from src.pipelines.calibration_pipeline.calibration_pipeline_orchestrator import \
+ CalibrationPipelineOrchestrator
+from src.pipelines.calibration_pipeline.charuco_board_detection.charuco_board_detector import \
+ CharucoBoardDetector
+from src.pipelines.session_pipeline.data_classes.data3d_full_session_data import \
+ Data3dFullSessionPayload
+from src.pipelines.session_pipeline.data_classes.data_3d_single_frame_payload import \
+ Data3dMultiFramePayload
from src.qt_visualizer_and_gui.qt_visualizer_and_gui import QTVisualizerAndGui
logger = logging.getLogger(__name__)
@@ -72,61 +72,27 @@ class SessionPipelineOrchestrator:
@mediapipe2d_numCams_numFrames_numTrackedPoints_XY.setter
def mediapipe2d_numCams_numFrames_numTrackedPoints_XY(self,
- mediapipe2d_numCams_numFrames_numTrackedPoints_XY: np.ndarray):
- self._mediapipe2d_numCams_numFrames_numTrackedPoints_XY = mediapipe2d_numCams_numFrames_numTrackedPoints_XY
+ mediapipe2d_numCams_numFrames_numTrackedPoints_XY: np.ndarray):
+ self._mediapipe2d_numCams_numFrames_numTrackedPoints_XY = \
+ mediapipe2d_numCams_numFrames_numTrackedPoints_XY
@property
def session_folder_path(self):
return freemocap_data_path / self._session_id
- async def process_by_cam_id(self, webcam_id: str, cb):
- with self._open_cv_camera_manager.start_capture_session_single_cam(
- webcam_id=webcam_id,
- ) as session_obj:
- fps_manager = TimestampManager(self._open_cv_camera_manager.available_webcam_ids)
- fps_manager.start_all()
- cv_cam = session_obj.cv_camera
- writer = session_obj.video_recorder
- try:
- while True:
- if not cv_cam.is_capturing_frames:
- logger.debug(f'Camera {webcam_id} is not capturing frames')
- continue
-
- if self.calibrate_cameras:
- charuco_frame_payload = self._camera_calibrator.calibrate(cv_cam)
-
- if cb and charuco_frame_payload.annotated_image is not None:
- writer.append_frame_payload_to_list(charuco_frame_payload.raw_frame_payload)
- await cb(charuco_frame_payload.annotated_image)
- except Exception as e:
- logger.error("Printing traceback")
- traceback.print_exc()
- raise e
- finally:
- writer = session_obj.video_recorder
- options = SaveOptions(
- writer_dir=Path().joinpath(
- cv_cam.session_writer_base_path,
- "charuco_board_detection",
- f"webcam_{cv_cam.webcam_id_as_str}",
- ),
- fps=fps_manager.median_frames_per_second_for_webcam(cv_cam.webcam_id_as_str),
- frame_width=cv_cam.image_width(),
- frame_height=cv_cam.image_height(),
- )
- writer.save_list_of_frames_to_video_file(options)
-
def calibrate_camera_capture_volume(self, use_most_recent_calibration: bool = False,
- load_calibration_from_session_id: str = None,
- charuco_square_size: int = 1,
- pin_camera_0_to_origin: bool = False):
+ load_calibration_from_session_id: str = None,
+ charuco_square_size: int = 1,
+ pin_camera_0_to_origin: bool = False):
if use_most_recent_calibration:
- self._anipose_camera_calibration_object = CalibrationPipelineOrchestrator().load_most_recent_calibration()
+ self._anipose_camera_calibration_object = CalibrationPipelineOrchestrator(
+
+ ).load_most_recent_calibration()
return
elif load_calibration_from_session_id is not None:
- calibration_orchestrator = CalibrationPipelineOrchestrator(load_calibration_from_session_id)
+ calibration_orchestrator = CalibrationPipelineOrchestrator(
+ load_calibration_from_session_id)
else: # create new calibration
calibration_orchestrator = CalibrationPipelineOrchestrator(self.session_id,
expected_framerate=self.expected_framerate)
@@ -135,31 +101,39 @@ class SessionPipelineOrchestrator:
show_camera_views_in_windows=True,
)
- self._anipose_camera_calibration_object = calibration_orchestrator.run_anipose_camera_calibration(
+ self._anipose_camera_calibration_object = \
+ calibration_orchestrator.run_anipose_camera_calibration(
charuco_square_size=charuco_square_size,
pin_camera_0_to_origin=pin_camera_0_to_origin)
def record_new_session(
- self,
- show_visualizer_gui=True,
- show_camera_views_in_windows=False,
- detect_mediapipe=False,
- detect_charuco=True,
- reconstruct_3d=True,
- save_video=True,
+ self,
+ show_visualizer_gui=True,
+ show_camera_views_in_windows=False,
+ detect_mediapipe=False,
+ detect_charuco=True,
+ reconstruct_3d=True,
+ save_video=True,
):
if reconstruct_3d:
try:
- self.anipose_camera_calibration_object = CalibrationPipelineOrchestrator().load_calibration_from_session_id(
+ self.anipose_camera_calibration_object = CalibrationPipelineOrchestrator(
+
+ ).load_calibration_from_session_id(
self.session_id)
except:
- logger.info(f"No calibration found for session_id: {self.session_id}, loading most recent calibration")
- self.anipose_camera_calibration_object = CalibrationPipelineOrchestrator().load_most_recent_calibration()
+ logger.info(
+ f"No calibration found for session_id: {self.session_id}, loading most recent "
+ f"calibration")
+ self.anipose_camera_calibration_object = CalibrationPipelineOrchestrator(
+
+ ).load_most_recent_calibration()
dictionary_of_charuco_frame_payloads_on_this_multi_frame = {}
dictionary_of_mediapipe_payloads_on_this_multi_frame = {}
- with self._open_cv_camera_manager.start_capture_session_all_cams() as connected_cameras_dict:
+ with self._open_cv_camera_manager.start_capture_session_all_cams() as \
+ connected_cameras_dict:
self._number_of_cameras = len(connected_cameras_dict)
@@ -167,7 +141,8 @@ class SessionPipelineOrchestrator:
try:
if show_visualizer_gui:
- self._visualizer_gui.setup_and_launch(self._open_cv_camera_manager.available_webcam_ids)
+ self._visualizer_gui.setup_and_launch(
+ self._open_cv_camera_manager.available_webcam_ids)
should_continue = True
while should_continue: # BIG FRAME LOOP STARTS HERE
@@ -177,19 +152,24 @@ class SessionPipelineOrchestrator:
if len(dictionary_of_charuco_frame_payloads_on_this_multi_frame) > 0:
charuco3d_multi_frame_payload = self._reconstruct_3d_charuco(
dictionary_of_charuco_frame_payloads_on_this_multi_frame)
- if show_visualizer_gui and charuco3d_multi_frame_payload is not None:
- self._visualizer_gui.update_charuco_3d_dottos(charuco3d_multi_frame_payload)
+ if show_visualizer_gui and charuco3d_multi_frame_payload is not \
+ None:
+ self._visualizer_gui.update_charuco_3d_dottos(
+ charuco3d_multi_frame_payload)
dictionary_of_charuco_frame_payloads_on_this_multi_frame = {}
if detect_mediapipe:
if len(dictionary_of_mediapipe_payloads_on_this_multi_frame) > 0:
mediapipe3d_multi_frame_payload = self._reconstruct_3d_mediapipe(
dictionary_of_mediapipe_payloads_on_this_multi_frame)
- if show_visualizer_gui and mediapipe3d_multi_frame_payload is not None:
- self._visualizer_gui.update_mediapipe3d_skeleton(mediapipe3d_multi_frame_payload)
+ if show_visualizer_gui and mediapipe3d_multi_frame_payload is not\
+ None:
+ self._visualizer_gui.update_mediapipe3d_skeleton(
+ mediapipe3d_multi_frame_payload)
dictionary_of_mediapipe_payloads_on_this_multi_frame = {}
- timestamp_manager.log_new_timestamp_for_main_loop_perf_coutner_ns(time.perf_counter_ns())
+ timestamp_manager.log_new_timestamp_for_main_loop_perf_coutner_ns(
+ time.perf_counter_ns())
if not self._open_cv_camera_manager.new_multi_frame_ready():
continue
@@ -208,21 +188,25 @@ class SessionPipelineOrchestrator:
image_to_display = this_cam_latest_frame.image.copy()
-
-
if save_video:
create_session_folder(self.session_id)
print(
- f"Recording: {this_open_cv_camera.webcam_id_as_str}, Frame# {this_open_cv_camera.latest_frame_number}")
- # # save this frame straight to the video file (no risk of memory overflow, but can't handle higher numbers of cameras)
- # this_open_cv_camera.video_recorder.save_frame_to_video_file(this_cam_latest_frame)
-
- # can handle large numbers of cameras, but will eventually fill up RAM and cause a crash
- this_open_cv_camera.video_recorder.append_frame_payload_to_list(this_cam_latest_frame)
+ f"Recording: {this_open_cv_camera.webcam_id_as_str}, "
+ f"Frame# {this_open_cv_camera.latest_frame_number}")
+ # # save this frame straight to the video file (no risk of memory
+ # overflow, but can't handle higher numbers of cameras)
+ # this_open_cv_camera.video_recorder.save_frame_to_video_file(
+ # this_cam_latest_frame)
+
+ # can handle large numbers of cameras, but will eventually fill up
+ # RAM and cause a crash
+ this_open_cv_camera.video_recorder.append_frame_payload_to_list(
+ this_cam_latest_frame)
if detect_charuco:
# detect charuco board
- this_charuco_frame_payload = self._charuco_board_detector.detect_charuco_board(
+ this_charuco_frame_payload = \
+ self._charuco_board_detector.detect_charuco_board(
this_cam_latest_frame)
image_to_display = this_charuco_frame_payload.annotated_image
@@ -232,8 +216,9 @@ class SessionPipelineOrchestrator:
if detect_mediapipe:
# detect mediapipe skeleton
- this_mediapipe_frame_payload = self._mediapipe_skeleton_detector.detect_skeleton_in_image(
- raw_frame_payload= this_cam_latest_frame,
+ this_mediapipe_frame_payload = \
+ self._mediapipe_skeleton_detector.detect_skeleton_in_image(
+ raw_frame_payload=this_cam_latest_frame,
annotated_image=image_to_display)
image_to_display = this_mediapipe_frame_payload.annotated_image
@@ -249,7 +234,8 @@ class SessionPipelineOrchestrator:
if show_visualizer_gui:
write_fps_to_image(
image_to_display,
- timestamp_manager.median_frames_per_second_for_webcam(this_webcam_id),
+ timestamp_manager.median_frames_per_second_for_webcam(
+ this_webcam_id),
)
self._visualizer_gui.update_camera_view_image(this_webcam_id,
image_to_display)
@@ -262,17 +248,20 @@ class SessionPipelineOrchestrator:
if show_visualizer_gui:
write_fps_to_image(
image_to_display,
- timestamp_manager.median_frames_per_second_for_webcam(this_webcam_id),
+ timestamp_manager.median_frames_per_second_for_webcam(
+ this_webcam_id),
)
- self._visualizer_gui.update_camera_view_image(this_webcam_id, image_to_display)
+ self._visualizer_gui.update_camera_view_image(this_webcam_id,
+ image_to_display)
# self._visualizer_gui.update_timestamp_plots(timestamp_manager)
if self._visualizer_gui.shut_it_down:
logger.info("GUI closed.")
should_continue = False
- #save frames if 'record' button is pressed
- this_open_cv_camera.record_frames(self._visualizer_gui.record_button_pressed)
+ # save frames if 'record' button is pressed
+ this_open_cv_camera.record_frames(
+ self._visualizer_gui.record_button_pressed)
# exit loop when user presses ESC key
exit_key = cv2.waitKey(1)
@@ -286,7 +275,8 @@ class SessionPipelineOrchestrator:
traceback.print_exc()
finally:
for this_open_cv_camera in connected_cameras_dict.values():
- this_open_cv_camera.video_recorder.save_list_of_frames_to_video_file(this_open_cv_camera.frame_list)
+ this_open_cv_camera.video_recorder.save_list_of_frames_to_video_file(
+ this_open_cv_camera.frame_list)
if show_camera_views_in_windows:
logger.info(f"Destroy window {this_open_cv_camera.webcam_id_as_str}")
@@ -298,15 +288,19 @@ class SessionPipelineOrchestrator:
timestamp_manager.create_diagnostic_plots()
def _reconstruct_3d_charuco(self, dictionary_of_charuco_payloads_on_this_multiframe) -> \
- Union[None, Data3dMultiFramePayload]:
+ Union[None, Data3dMultiFramePayload]:
is_there_any_charuco_data = []
for this_cam_charuco_data in dictionary_of_charuco_payloads_on_this_multiframe.values():
- is_there_any_charuco_data.append(this_cam_charuco_data.charuco_view_data.some_charuco_corners_found)
+ is_there_any_charuco_data.append(
+ this_cam_charuco_data.charuco_view_data.some_charuco_corners_found)
min_cameras_to_reconstruct = 2
- if sum(is_there_any_charuco_data) >= min_cameras_to_reconstruct: # if at least 2 cameras have any data, then we can try to make some 3d dottos
- charuco2d_data_per_cam_dict = self._format_charuco2d_data(dictionary_of_charuco_payloads_on_this_multiframe)
+ if sum(
+ is_there_any_charuco_data) >= min_cameras_to_reconstruct: # if at least 2 cameras
+ # have any data, then we can try to make some 3d dottos
+ charuco2d_data_per_cam_dict = self._format_charuco2d_data(
+ dictionary_of_charuco_payloads_on_this_multiframe)
charuco_3d_data_payload = self._triangulate_2d_data(charuco2d_data_per_cam_dict,
self._charuco_board_detector.number_of_charuco_corners)
@@ -317,7 +311,8 @@ class SessionPipelineOrchestrator:
number_of_tracked_points = self._charuco_board_detector.number_of_charuco_corners
- base_charuco_data_npy_with_nans_for_missing_data_xy = np.zeros((number_of_tracked_points, 2))
+ base_charuco_data_npy_with_nans_for_missing_data_xy = np.zeros(
+ (number_of_tracked_points, 2))
base_charuco_data_npy_with_nans_for_missing_data_xy[:] = np.nan
charuco2d_data_per_cam_dict = {}
@@ -328,7 +323,8 @@ class SessionPipelineOrchestrator:
charuco_ids_in_this_frame_idx = this_cam_data.charuco_view_data.charuco_ids
charuco_corners_in_this_frame_xy = this_cam_data.charuco_view_data.charuco_corners
if charuco_ids_in_this_frame_idx.__class__ != list:
- this_frame_charuco_data_xy[charuco_ids_in_this_frame_idx, :] = charuco_corners_in_this_frame_xy
+ this_frame_charuco_data_xy[charuco_ids_in_this_frame_idx,
+ :] = charuco_corners_in_this_frame_xy
this_webcam_id = this_cam_data.raw_frame_payload.webcam_id
charuco2d_data_per_cam_dict[this_webcam_id] = this_frame_charuco_data_xy
@@ -336,20 +332,25 @@ class SessionPipelineOrchestrator:
return charuco2d_data_per_cam_dict
def _reconstruct_3d_mediapipe(self, dictionary_of_mediapipe_payloads_on_this_multi_frame) -> \
- Union[None, Data3dMultiFramePayload]:
+ Union[None, Data3dMultiFramePayload]:
is_there_any_mediapipe_data = []
for this_cam_medipipe_data in dictionary_of_mediapipe_payloads_on_this_multi_frame.values():
is_there_any_mediapipe_data.append(
this_cam_medipipe_data.pixel_data_numpy_arrays.has_data)
min_cameras_to_reconstruct = 2
- if sum(is_there_any_mediapipe_data) >= min_cameras_to_reconstruct: # if at least 2 cameras have any data, then we can try to make some 3d dottos
+ if sum(
+ is_there_any_mediapipe_data) >= min_cameras_to_reconstruct: # if at least 2 cameras
+ # have any data, then we can try to make some 3d dottos
mediapipe2d_data_per_cam_dict = {}
- for this_webcam_id, this_mediapipe_payload in dictionary_of_mediapipe_payloads_on_this_multi_frame.items():
+ for this_webcam_id, this_mediapipe_payload in \
+ dictionary_of_mediapipe_payloads_on_this_multi_frame.items():
+ self._threshold_2d_data_by_confidence(
+ this_mediapipe_payload.pixel_data_numpy_arrays, .5)
- self._threshold_2d_data_by_confidence(this_mediapipe_payload.pixel_data_numpy_arrays, .5)
-
- mediapipe2d_data_per_cam_dict[this_webcam_id] = this_mediapipe_payload.pixel_data_numpy_arrays.all_data2d_nFrames_nTrackedPts_XY
+ mediapipe2d_data_per_cam_dict[
+ this_webcam_id] = \
+ this_mediapipe_payload.pixel_data_numpy_arrays.all_data2d_nFrames_nTrackedPts_XY
mediapipe_3d_data_payload = self._triangulate_2d_data(mediapipe2d_data_per_cam_dict,
self._mediapipe_skeleton_detector.number_of_tracked_points_total)
@@ -357,14 +358,15 @@ class SessionPipelineOrchestrator:
return mediapipe_3d_data_payload
def _triangulate_2d_data(self, data2d_per_cam_dict: Dict,
- number_of_tracked_points: int) -> Data3dMultiFramePayload:
+ number_of_tracked_points: int) -> Data3dMultiFramePayload:
each_cam2d_data_list = [this_cam_charuco2d_frame_xy for this_cam_charuco2d_frame_xy in
- data2d_per_cam_dict.values()]
+ data2d_per_cam_dict.values()]
data2d_camNum_trackedPointNum_xy = np.asarray(each_cam2d_data_list)
- # THIS IS WHERE THE MAGIC HAPPENS - 2d data from calibrated, synchronized cameras has now become a 3d estimate. Hurray! :`D
+ # THIS IS WHERE THE MAGIC HAPPENS - 2d data from calibrated, synchronized cameras has now
+ # become a 3d estimate. Hurray! :`D
# simple triangulation
data3d_trackedPointNum_xyz = self._anipose_camera_calibration_object.triangulate(
@@ -372,16 +374,24 @@ class SessionPipelineOrchestrator:
progress=False,
undistort=True)
- # # triangulation with ransac (to find the best combo of cameras to minimize reprojection error, I think?
+ # # triangulation with ransac (to find the best combo of cameras to minimize reprojection
+ # error, I think?
# data3d_trackedPointNum_xyz = self._anipose_camera_calibration_object.triangulate_ransac(
# data2d_camNum_trackedPointNum_xy,
# progress=False,
# undistort=True)
- # Reprojection error is a measure of the quality of the reconstruction. It is the distance (error) between the original 2d point and a reprojection of the 3d point back onto the image plane.
- # TODO - use this for filtering data (i.e. if one view has very high reprojection error, re-do the triangulation without that camera's view data)
- # TODO - we are currently using each tracking method's `confidence` values (or whatever they choose to call it) for thresholding, but it's problematic because of the neural_networks' propensity to apply high confidence to bonkers estimates, which leads to SPOOKY GHOST SKELETONS! :O
- data3d_trackedPointNum_reprojectionError = self._anipose_camera_calibration_object.reprojection_error(
+ # Reprojection error is a measure of the quality of the reconstruction. It is the
+ # distance (error) between the original 2d point and a reprojection of the 3d point back
+ # onto the image plane.
+ # TODO - use this for filtering data (i.e. if one view has very high reprojection error,
+ # re-do the triangulation without that camera's view data)
+ # TODO - we are currently using each tracking method's `confidence` values (or whatever
+ # they choose to call it) for thresholding, but it's problematic because of the
+ # neural_networks' propensity to apply high confidence to bonkers estimates, which leads
+ # to SPOOKY GHOST SKELETONS! :O
+ data3d_trackedPointNum_reprojectionError = \
+ self._anipose_camera_calibration_object.reprojection_error(
data3d_trackedPointNum_xyz,
data2d_camNum_trackedPointNum_xy,
mean=True)
@@ -391,21 +401,25 @@ class SessionPipelineOrchestrator:
data3d_trackedPointNum_reprojectionError=data3d_trackedPointNum_reprojectionError, )
def mediapipe_track_skeletons_offline(self):
- self._mediapipe2d_numCams_numFrames_numTrackedPoints_XY = self._mediapipe_skeleton_detector.process_session_folder(
+ self._mediapipe2d_numCams_numFrames_numTrackedPoints_XY = \
+ self._mediapipe_skeleton_detector.process_session_folder(
save_annotated_videos=True)
def reconstruct3d_from_2d_data_offline(self):
number_of_cameras = self._mediapipe2d_numCams_numFrames_numTrackedPoints_XY.shape[0]
number_of_frames = self._mediapipe2d_numCams_numFrames_numTrackedPoints_XY.shape[1]
number_of_tracked_points = self._mediapipe2d_numCams_numFrames_numTrackedPoints_XY.shape[2]
- number_of_spatial_dimensions = self._mediapipe2d_numCams_numFrames_numTrackedPoints_XY.shape[3]
+ number_of_spatial_dimensions = \
+ self._mediapipe2d_numCams_numFrames_numTrackedPoints_XY.shape[3]
if not number_of_spatial_dimensions == 2:
logger.error(
- f"This is supposed to be 2D data but, number_of_spatial_dimensions: {number_of_spatial_dimensions}")
+ f"This is supposed to be 2D data but, number_of_spatial_dimensio"
+ f"ns: {number_of_spatial_dimensions}")
raise Exception
- # reshape data to collapse across 'frames' so it becomes [number_of_cameras, number_of_2d_points(numFrames*numPoints), XY]
+ # reshape data to collapse across 'frames' so it becomes [number_of_cameras,
+ # number_of_2d_points(numFrames*numPoints), XY]
data2d_flat = self._mediapipe2d_numCams_numFrames_numTrackedPoints_XY.reshape(
number_of_cameras,
-1,
@@ -419,36 +433,44 @@ class SessionPipelineOrchestrator:
data3d_flat = self.anipose_camera_calibration_object.triangulate(data2d_flat, progress=True)
- data3d_reprojectionError_flat = self.anipose_camera_calibration_object.reprojection_error(data3d_flat,
- data2d_flat,
- mean=True)
+ data3d_reprojectionError_flat = self.anipose_camera_calibration_object.reprojection_error(
+ data3d_flat,
+ data2d_flat,
+ mean=True)
- data3d_numFrames_numTrackedPoints_XYZ = data3d_flat.reshape(number_of_frames, number_of_tracked_points, 3)
- data3d_numFrames_numTrackedPoints_reprojectionError = data3d_reprojectionError_flat.reshape(number_of_frames,
- number_of_tracked_points)
+ data3d_numFrames_numTrackedPoints_XYZ = data3d_flat.reshape(number_of_frames,
+ number_of_tracked_points, 3)
+ data3d_numFrames_numTrackedPoints_reprojectionError = data3d_reprojectionError_flat.reshape(
+ number_of_frames,
+ number_of_tracked_points)
self._save_mediapipe3d_data_to_npy(data3d_numFrames_numTrackedPoints_XYZ,
data3d_numFrames_numTrackedPoints_reprojectionError)
self._mediapipe3d_full_session_payload = Data3dFullSessionPayload(
data3d_numFrames_numTrackedPoints_XYZ=data3d_numFrames_numTrackedPoints_XYZ,
- data3d_numFrames_numTrackedPoint_reprojectionError=data3d_numFrames_numTrackedPoints_reprojectionError)
+ data3d_numFrames_numTrackedPoint_reprojectionError
+ =data3d_numFrames_numTrackedPoints_reprojectionError)
def _save_mediapipe3d_data_to_npy(self, data3d_numFrames_numTrackedPoints_XYZ: np.ndarray,
- data3d_numFrames_numTrackedPoints_reprojectionError: np.ndarray):
+ data3d_numFrames_numTrackedPoints_reprojectionError: np.ndarray):
output_data_folder = Path(get_session_output_data_folder_path(self._session_id))
# save spatial XYZ data
- self._mediapipe_3dData_save_path = output_data_folder / "mediapipe_3dData_numFrames_numTrackedPoints_spatialXYZ.npy"
+ self._mediapipe_3dData_save_path = output_data_folder / \
+ "mediapipe_3dData_numFrames_numTrackedPoints_spatialXYZ.npy"
logger.info(f"saving: {self._mediapipe_3dData_save_path}")
np.save(str(self._mediapipe_3dData_save_path), data3d_numFrames_numTrackedPoints_XYZ)
# save reprojection error
- self._mediapipe_reprojection_error_save_path = output_data_folder / "mediapipe_3dData_numFrames_numTrackedPoints_reprojectionError.npy"
+ self._mediapipe_reprojection_error_save_path = output_data_folder / \
+ "mediapipe_3dData_numFrames_numTrackedPoints_reprojectionError.npy"
logger.info(f"saving: {self._mediapipe_reprojection_error_save_path}")
- np.save(str(self._mediapipe_reprojection_error_save_path), data3d_numFrames_numTrackedPoints_reprojectionError)
+ np.save(str(self._mediapipe_reprojection_error_save_path),
+ data3d_numFrames_numTrackedPoints_reprojectionError)
- def _threshold_2d_data_by_confidence(self, mediapipe2d_data_payload:Mediapipe2dDataPayload, confidence_threshold:float):
+ def _threshold_2d_data_by_confidence(self, mediapipe2d_data_payload: Mediapipe2dDataPayload,
+ confidence_threshold: float):
pass
@@ -456,27 +478,33 @@ def load_mediapipe3d_skeleton_data(session_id: str = None):
if session_id is None:
session_id = get_most_recent_session_id()
output_data_folder = Path(get_session_output_data_folder_path(session_id))
- mediapipe3d_xyz_file_path = output_data_folder / "mediapipe_3dData_numFrames_numTrackedPoints_spatialXYZ.npy"
+ mediapipe3d_xyz_file_path = output_data_folder / \
+ "mediapipe_3dData_numFrames_numTrackedPoints_spatialXYZ.npy"
logger.info(f"loading: {mediapipe3d_xyz_file_path}")
mediapipe3d_skeleton_nFrames_nTrajectories_xyz = np.load(str(mediapipe3d_xyz_file_path))
- mediapipe_reprojection_error_file_path = output_data_folder / "mediapipe_3dData_numFrames_numTrackedPoints_reprojectionError.npy"
+ mediapipe_reprojection_error_file_path = output_data_folder / \
+ "mediapipe_3dData_numFrames_numTrackedPoints_reprojectionError.npy"
logger.info(f"loading: {mediapipe_reprojection_error_file_path}")
- mediapipe3d_skeleton_nFrames_nTrajectories_reprojectionError = np.load(str(mediapipe_reprojection_error_file_path))
+ mediapipe3d_skeleton_nFrames_nTrajectories_reprojectionError = np.load(
+ str(mediapipe_reprojection_error_file_path))
return Data3dFullSessionPayload(
data3d_numFrames_numTrackedPoints_XYZ=mediapipe3d_skeleton_nFrames_nTrajectories_xyz,
- data3d_numFrames_numTrackedPoint_reprojectionError=mediapipe3d_skeleton_nFrames_nTrajectories_reprojectionError)
+ data3d_numFrames_numTrackedPoint_reprojectionError
+ =mediapipe3d_skeleton_nFrames_nTrajectories_reprojectionError)
def load_mediapipe2d_data(session_id: str = None):
if session_id is None:
session_id = get_most_recent_session_id()
output_data_folder = Path(get_session_output_data_folder_path(session_id))
- mediapipe2d_xy_file_path = output_data_folder / "mediapipe_2dData_numCams_numFrames_numTrackedPoints_pixelXY.npy"
+ mediapipe2d_xy_file_path = output_data_folder / \
+ "mediapipe_2dData_numCams_numFrames_numTrackedPoints_pixelXY.npy"
logger.info(f"loading: {mediapipe2d_xy_file_path}")
mediapipe2d_numCams_numFrames_numTrackedPoints_pixelXY = np.load(mediapipe2d_xy_file_path)
- # TODO - create a dataclass for 2d mediapipe data, including things split up by body, hands, and face (and maybe the raw `mediapipe results` data things if that's not too much data)
+ # TODO - create a dataclass for 2d mediapipe data, including things split up by body, hands,
+ # and face (and maybe the raw `mediapipe results` data things if that's not too much data)
return mediapipe2d_numCams_numFrames_numTrackedPoints_pixelXY
@@ -502,7 +530,7 @@ if __name__ == "__main__":
this_session_orchestrator.reconstruct3d_from_2d_data_offline()
# this_session_orchestrator.visualize_session_data_offline()
-
- qt_gl_laser_skeleton = QtGlLaserSkeletonVisualizer(
- mediapipe_skel_fr_mar_xyz=this_session_orchestrator._mediapipe3d_full_session_payload.data3d_numFrames_numTrackedPoints_XYZ)
- qt_gl_laser_skeleton.start_animation()
+ #
+ # qt_gl_laser_skeleton = QtGlLaserSkeletonVisualizer(
+ # mediapipe_skel_fr_mar_xyz=this_session_orchestrator._mediapipe3d_full_session_payload.data3d_numFrames_numTrackedPoints_XYZ)
+ # qt_gl_laser_skeleton.start_animation()