-
Notifications
You must be signed in to change notification settings - Fork 100
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Extract clip as video, slp and pkg.slp #2059
Open
ericleonardis
wants to merge
25
commits into
develop
Choose a base branch
from
eric/extract-clips
base: develop
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from 7 commits
Commits
Show all changes
25 commits
Select commit
Hold shift + click to select a range
c3a8e5b
add extrack clip and labels menu item
ericleonardis dcfa897
add export video clip and labels
ericleonardis 39c17b5
test exportvideoclip for creating video, slp, and pkg
ericleonardis 945d737
simplify dialogue menu by making new custom dialogue
ericleonardis 1907daf
new custom export clip and labels dialogue
ericleonardis c31caa8
test length of lists in labels object
ericleonardis 9f71476
change comments
ericleonardis 117d5a3
reformatted linting with black
ericleonardis 351919e
clean up double
ericleonardis fd1fc67
split clip pkg and clip pkg
ericleonardis 08b40cf
add two menu items for clip video and clip pkg
ericleonardis ab58597
add error for no clip selected; remove imports
ericleonardis 5f6fb07
add test for clip pkg
ericleonardis 4c4ea5d
added edge case testing
ericleonardis c964f2a
throw error for single frame, needs selected range
ericleonardis ace2c85
add error hanlding for slp and package clip writing
ericleonardis ddcb213
skip progress bar in tests
ericleonardis 2dccc28
remove unused import
ericleonardis 4bc5422
fix type in ffmpeg error message
ericleonardis 2d00bb8
node
ericleonardis f5c617f
expanded tests for gui dialogues
ericleonardis e972d3f
test for multiple videos
ericleonardis 39cc496
map frame_to_indedx and find valid_frame_indices for labels
ericleonardis b529dd8
enable/disable based on whether clip is selected
ericleonardis cd866f3
make framerange == (0, video.frames) a valid choice
ericleonardis File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change | ||||||||
---|---|---|---|---|---|---|---|---|---|---|
|
@@ -627,6 +627,9 @@ def openPrereleaseVersion(self): | |||||||||
"""Open the current prerelease version.""" | ||||||||||
self.execute(OpenPrereleaseVersion) | ||||||||||
|
||||||||||
def exportVideoClip(self): | ||||||||||
"""Exports a selected range of video frames and their corresponding labels.""" | ||||||||||
self.execute(ExportVideoClip) | ||||||||||
|
||||||||||
# File Commands | ||||||||||
|
||||||||||
|
@@ -3470,13 +3473,293 @@ def do_action(context: CommandContext, params: dict): | |||||||||
if rls is not None: | ||||||||||
context.openWebsite(rls.url) | ||||||||||
|
||||||||||
class ExportVideoClip(AppCommand): | ||||||||||
@staticmethod | ||||||||||
def do_action(context: CommandContext, params: dict): | ||||||||||
""" | ||||||||||
Extracts a video clip and saves it with pose annotations. | ||||||||||
|
||||||||||
def copy_to_clipboard(text: str): | ||||||||||
"""Copy a string to the system clipboard. | ||||||||||
Args: | ||||||||||
context: Command context, providing state and application access. | ||||||||||
params: Parameters for the action, including file paths and export options. | ||||||||||
""" | ||||||||||
from sleap.io.visuals import save_labeled_video | ||||||||||
from sleap import Labels | ||||||||||
|
||||||||||
Args: | ||||||||||
text: String to copy to clipboard. | ||||||||||
""" | ||||||||||
clipboard = QtWidgets.QApplication.clipboard() | ||||||||||
clipboard.clear(mode=clipboard.Clipboard) | ||||||||||
clipboard.setText(text, mode=clipboard.Clipboard) | ||||||||||
# Extract video and labels from context | ||||||||||
video = context.state["video"] | ||||||||||
labels = context.state["labels"] | ||||||||||
|
||||||||||
# Ensure frame range is set; default to all frames if None | ||||||||||
frame_range = context.state.get("frame_range") | ||||||||||
if frame_range is None: | ||||||||||
frame_range = (0, video.frames) | ||||||||||
|
||||||||||
# Extract only the selected frames into a new Labels object | ||||||||||
pruned_labels = labels.extract( | ||||||||||
inds=range(*frame_range), | ||||||||||
copy=True, # Ensures a deep copy of the extracted labels | ||||||||||
) | ||||||||||
|
||||||||||
# Remap frame indices in pruned_labels to start from 0 | ||||||||||
for labeled_frame in pruned_labels.labeled_frames: | ||||||||||
labeled_frame.frame_idx -= frame_range[0] | ||||||||||
|
||||||||||
# Ensure the pruned labels include the original video reference | ||||||||||
if video not in pruned_labels.videos: | ||||||||||
pruned_labels.add_video(video) | ||||||||||
|
||||||||||
# Conditionally render labels | ||||||||||
render_labels = params["render_labels"] | ||||||||||
|
||||||||||
# Save the video clip with annotations | ||||||||||
# Save the video clip with pose annotations | ||||||||||
save_labeled_video( | ||||||||||
filename=params["filename"], | ||||||||||
labels=context.state["labels"] if render_labels else None, | ||||||||||
video=context.state["video"], | ||||||||||
frames=list(params["frames"]), | ||||||||||
fps=params["fps"], | ||||||||||
color_manager=params["color_manager"], | ||||||||||
background=params["background"], | ||||||||||
show_edges=params["show_edges"] if render_labels else False, | ||||||||||
edge_is_wedge=params["edge_is_wedge"] if render_labels else False, | ||||||||||
marker_size=params["marker_size"] if render_labels else 0, | ||||||||||
scale=params["scale"], | ||||||||||
crop_size_xy=params["crop"], | ||||||||||
gui_progress=True, | ||||||||||
) | ||||||||||
|
||||||||||
# Save the pruned labels | ||||||||||
labels_filename = params["filename"].replace(".mp4", ".slp") | ||||||||||
Comment on lines
+3590
to
+3591
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Use pathlib for path operations
Suggested change
|
||||||||||
pruned_labels.save(labels_filename) | ||||||||||
|
||||||||||
# Open the video file when done, if specified | ||||||||||
if params["open_when_done"]: | ||||||||||
open_file(params["filename"]) | ||||||||||
|
||||||||||
@staticmethod | ||||||||||
def ask(context: CommandContext, params: dict) -> bool: | ||||||||||
""" | ||||||||||
Asks the user for export parameters via a dialog. | ||||||||||
|
||||||||||
Args: | ||||||||||
context: Command context, providing state and application access. | ||||||||||
params: A dictionary to populate with user-defined options. | ||||||||||
|
||||||||||
Returns: | ||||||||||
bool: True if the user confirmed the action, False if canceled. | ||||||||||
""" | ||||||||||
from sleap.gui.dialogs.export_clip import ExportClipDialog | ||||||||||
from sleap.io.videowriter import VideoWriter | ||||||||||
from qtpy import QtWidgets | ||||||||||
|
||||||||||
# Show the export dialog to the user | ||||||||||
dialog = ExportClipDialog() | ||||||||||
|
||||||||||
# Set default FPS from the current video | ||||||||||
dialog.form_widget.set_form_data( | ||||||||||
dict(fps=getattr(context.state["video"], "fps", 30)) | ||||||||||
) | ||||||||||
|
||||||||||
export_options = dialog.get_results() | ||||||||||
|
||||||||||
if export_options is None: # User canceled the dialog | ||||||||||
return False | ||||||||||
|
||||||||||
# **Add "Render Labels" Option Manually** | ||||||||||
# Since the dialog does not have an "Render Labels" checkbox, add it here. | ||||||||||
# Prompt the user with a simple Yes/No dialog for "Render Labels" | ||||||||||
render_labels_dialog = QtWidgets.QMessageBox() | ||||||||||
render_labels_dialog.setWindowTitle("Render Labels") | ||||||||||
render_labels_dialog.setText("Do you want to include pose annotations in the video?") | ||||||||||
render_labels_dialog.setStandardButtons(QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No) | ||||||||||
render_labels_dialog.setDefaultButton(QtWidgets.QMessageBox.Yes) | ||||||||||
render_labels = render_labels_dialog.exec_() == QtWidgets.QMessageBox.Yes | ||||||||||
|
||||||||||
# Determine default output filename | ||||||||||
default_out_filename = context.state["filename"] + ".avi" | ||||||||||
if VideoWriter.can_use_ffmpeg(): | ||||||||||
default_out_filename = context.state["filename"] + ".mp4" | ||||||||||
|
||||||||||
# Prompt the user to select an output file | ||||||||||
filename, _ = QtWidgets.QFileDialog.getSaveFileName( | ||||||||||
None, | ||||||||||
"Save Clip As...", | ||||||||||
default_out_filename, | ||||||||||
"Video (*.avi *.mp4)", | ||||||||||
) | ||||||||||
|
||||||||||
if not filename: # User canceled file selection | ||||||||||
return False | ||||||||||
|
||||||||||
# Populate parameters with user-selected options | ||||||||||
params["filename"] = filename | ||||||||||
params["fps"] = export_options["fps"] | ||||||||||
params["scale"] = export_options["scale"] | ||||||||||
params["open_when_done"] = export_options["open_when_done"] | ||||||||||
params["background"] = export_options["background"] | ||||||||||
params["render_labels"] = render_labels # Add render_labels option | ||||||||||
|
||||||||||
# Handle crop size | ||||||||||
params["crop"] = None | ||||||||||
w = int(context.state["video"].width * params["scale"]) | ||||||||||
h = int(context.state["video"].height * params["scale"]) | ||||||||||
if export_options["crop"] == "Half": | ||||||||||
params["crop"] = (w // 2, h // 2) | ||||||||||
elif export_options["crop"] == "Quarter": | ||||||||||
params["crop"] = (w // 4, h // 4) | ||||||||||
|
||||||||||
# Use GUI visuals if selected | ||||||||||
if export_options["use_gui_visuals"]: | ||||||||||
params["color_manager"] = context.app.color_manager | ||||||||||
else: | ||||||||||
params["color_manager"] = None | ||||||||||
|
||||||||||
# Access frame range | ||||||||||
if context.state.get("has_frame_range"): | ||||||||||
params["frames"] = range(*context.state["frame_range"]) | ||||||||||
else: | ||||||||||
params["frames"] = range(context.state["video"].frames) | ||||||||||
|
||||||||||
params["show_edges"] = context.state.get("show edges", default=True) | ||||||||||
params["edge_is_wedge"] = ( | ||||||||||
context.state.get("edge style", default="").lower() == "wedge" | ||||||||||
) | ||||||||||
params["marker_size"] = context.state.get("marker size", default=4) | ||||||||||
|
||||||||||
return True | ||||||||||
|
||||||||||
ericleonardis marked this conversation as resolved.
Show resolved
Hide resolved
|
||||||||||
class ExportVideoClip(AppCommand): | ||||||||||
@staticmethod | ||||||||||
def do_action(context: CommandContext, params: dict): | ||||||||||
from sleap.io.visuals import save_labeled_video | ||||||||||
from sleap.io.video import MediaVideo, Video | ||||||||||
import cv2 | ||||||||||
import numpy as np | ||||||||||
|
||||||||||
# Extract video and labels from context | ||||||||||
video = context.state["video"] | ||||||||||
labels = context.state["labels"] | ||||||||||
|
||||||||||
# Ensure frame range is set; default to all frames if None | ||||||||||
frame_range = context.state.get("frame_range") | ||||||||||
if frame_range is None: | ||||||||||
frame_range = (0, video.frames) | ||||||||||
|
||||||||||
# Extract only the selected frames into a new Labels object | ||||||||||
pruned_labels = labels.extract( | ||||||||||
inds=range(*frame_range), | ||||||||||
copy=True, # Ensures a deep copy of the extracted labels | ||||||||||
) | ||||||||||
|
||||||||||
# Remap frame indices in pruned_labels to start from 0 | ||||||||||
for labeled_frame in pruned_labels.labeled_frames: | ||||||||||
labeled_frame.frame_idx -= frame_range[0] | ||||||||||
|
||||||||||
# Save the video | ||||||||||
fourcc = cv2.VideoWriter_fourcc(*"mp4v") | ||||||||||
height, width = video.height, video.width | ||||||||||
is_color = video.channels == 3 | ||||||||||
writer = cv2.VideoWriter(params["filename"], fourcc, params["fps"], (width, height), is_color) | ||||||||||
|
||||||||||
for frame_idx in params["frames"]: | ||||||||||
frame = video.get_frame(frame_idx) | ||||||||||
|
||||||||||
# Ensure frame format is valid for OpenCV | ||||||||||
if frame.ndim == 2: # Grayscale frames | ||||||||||
frame = cv2.cvtColor(frame, cv2.COLOR_GRAY2BGR) | ||||||||||
|
||||||||||
if frame.shape[:2] != (height, width): | ||||||||||
raise ValueError(f"Frame size {frame.shape[:2]} does not match expected {height, width}") | ||||||||||
|
||||||||||
writer.write(frame) | ||||||||||
|
||||||||||
writer.release() | ||||||||||
|
||||||||||
# Create a new Video object for the output video | ||||||||||
new_media_video = MediaVideo(filename=params["filename"], grayscale=video.channels == 1, bgr=True) | ||||||||||
new_video = Video(backend=new_media_video) | ||||||||||
|
||||||||||
# Step 1: Update all labeled frames to point to the new video | ||||||||||
for labeled_frame in pruned_labels.labeled_frames: | ||||||||||
if labeled_frame.video.filename == video.filename: | ||||||||||
labeled_frame.video = new_video | ||||||||||
|
||||||||||
# Step 2: Safely replace the old video with the new video | ||||||||||
pruned_labels.videos = [ | ||||||||||
v for v in pruned_labels.videos if v.filename != video.filename | ||||||||||
] | ||||||||||
pruned_labels.add_video(new_video) | ||||||||||
|
||||||||||
# Step 3: Rebuild the cache to ensure consistency | ||||||||||
pruned_labels.update_cache() | ||||||||||
|
||||||||||
# Save the pruned labels as .slp | ||||||||||
labels_filename = params["filename"].replace(".mp4", ".slp") | ||||||||||
pruned_labels.save(labels_filename) | ||||||||||
|
||||||||||
# Save the pruned labels with embedded images as .pkg.slp | ||||||||||
pkg_filename = params["filename"].replace(".mp4", ".pkg.slp") | ||||||||||
pruned_labels.save(pkg_filename, with_images=True) | ||||||||||
ericleonardis marked this conversation as resolved.
Show resolved
Hide resolved
|
||||||||||
|
||||||||||
# Open the video file when done, if specified | ||||||||||
if params["open_when_done"]: | ||||||||||
open_file(params["filename"]) | ||||||||||
|
||||||||||
@staticmethod | ||||||||||
def ask(context: CommandContext, params: dict) -> bool: | ||||||||||
""" | ||||||||||
Asks the user for export parameters via a custom dialog. | ||||||||||
|
||||||||||
Args: | ||||||||||
context: Command context, providing state and application access. | ||||||||||
params: A dictionary to populate with user-defined options. | ||||||||||
|
||||||||||
Returns: | ||||||||||
bool: True if the user confirmed the action, False if canceled. | ||||||||||
""" | ||||||||||
from sleap.gui.dialogs.export_clip import ExportClipAndLabelsDialog | ||||||||||
from qtpy import QtWidgets | ||||||||||
|
||||||||||
# Extract FPS from video metadata (fallback to 30 if unavailable) | ||||||||||
video_fps = getattr(context.state["video"], "fps", 30) | ||||||||||
|
||||||||||
# Initialize and show the export dialog | ||||||||||
dialog = ExportClipAndLabelsDialog(video_fps=video_fps) | ||||||||||
if dialog.exec_() != QtWidgets.QDialog.Accepted: | ||||||||||
return False # User canceled | ||||||||||
|
||||||||||
# Get user input from dialog | ||||||||||
export_options = dialog.get_results() | ||||||||||
|
||||||||||
# Prompt user to select output file | ||||||||||
filename, _ = QtWidgets.QFileDialog.getSaveFileName( | ||||||||||
None, "Save Clip As...", "", "Video (*.avi *.mp4)" | ||||||||||
) | ||||||||||
if not filename: | ||||||||||
return False # User canceled file selection | ||||||||||
|
||||||||||
# Populate export parameters | ||||||||||
params["filename"] = filename | ||||||||||
params["fps"] = export_options["fps"] | ||||||||||
params["open_when_done"] = export_options["open_when_done"] | ||||||||||
|
||||||||||
|
||||||||||
# Access frame range | ||||||||||
if context.state.get("has_frame_range"): | ||||||||||
params["frames"] = range(*context.state["frame_range"]) | ||||||||||
else: | ||||||||||
params["frames"] = range(context.state["video"].frames) | ||||||||||
|
||||||||||
return True | ||||||||||
|
||||||||||
def copy_to_clipboard(text: str): | ||||||||||
"""Copy a string to the system clipboard. | ||||||||||
|
||||||||||
Args: | ||||||||||
text: String to copy to clipboard. | ||||||||||
""" | ||||||||||
clipboard = QtWidgets.QApplication.clipboard() | ||||||||||
clipboard.clear(mode=clipboard.Clipboard) | ||||||||||
clipboard.setText(text, mode=clipboard.Clipboard) | ||||||||||
ericleonardis marked this conversation as resolved.
Show resolved
Hide resolved
ericleonardis marked this conversation as resolved.
Show resolved
Hide resolved
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
When
inds
is either alist
orrange
, then we just callLabels.get
for each item in thelist
orrange
(int
in our case).This means that we try to grab the item from the
Labels.labels: List[LabeledFrame]
at the index we provided - which is not the same as grabbing the item at the frame index.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
sleap/sleap/io/dataset.py
Lines 779 to 798 in 1eff33d
sleap/sleap/io/dataset.py
Lines 636 to 674 in 1eff33d
sleap/sleap/io/dataset.py
Lines 768 to 769 in 1eff33d
sleap/sleap/io/dataset.py
Lines 738 to 739 in 1eff33d
sleap/sleap/io/dataset.py
Lines 552 to 555 in 1eff33d
sleap/sleap/io/dataset.py
Line 416 in 1eff33d
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Ok, I think I have addressed this suggestion by creating a frame_to_index mapping and then feeding in valid frame indices on line 3666-3677 in command.py.
`
Map frame indices to the actual labeled frame objects
`
This should now be robust to multiple videos and sparsely labelled videos.