-
Notifications
You must be signed in to change notification settings - Fork 101
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 9 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,10 @@ 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 | ||||||||||||||||||||||
|
||||||||||||||||||||||
|
@@ -3471,12 +3475,141 @@ def do_action(context: CommandContext, params: dict): | |||||||||||||||||||||
context.openWebsite(rls.url) | ||||||||||||||||||||||
|
||||||||||||||||||||||
|
||||||||||||||||||||||
def copy_to_clipboard(text: str): | ||||||||||||||||||||||
"""Copy a string to the system clipboard. | ||||||||||||||||||||||
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"] | ||||||||||||||||||||||
|
||||||||||||||||||||||
Args: | ||||||||||||||||||||||
text: String to copy to clipboard. | ||||||||||||||||||||||
""" | ||||||||||||||||||||||
clipboard = QtWidgets.QApplication.clipboard() | ||||||||||||||||||||||
clipboard.clear(mode=clipboard.Clipboard) | ||||||||||||||||||||||
clipboard.setText(text, mode=clipboard.Clipboard) | ||||||||||||||||||||||
# 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) | ||||||||||||||||||||||
|
||||||||||||||||||||||
ericleonardis marked this conversation as resolved.
Show resolved
Hide resolved
|
||||||||||||||||||||||
writer.release() | ||||||||||||||||||||||
|
||||||||||||||||||||||
# Create a new Video object for the output video | ||||||||||||||||||||||
new_media_video = MediaVideo( | ||||||||||||||||||||||
filename=params["filename"], grayscale=video.channels == 1, bgr=True | ||||||||||||||||||||||
) | ||||||||||||||||||||||
Comment on lines
+3577
to
+3581
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.
Suggested change
|
||||||||||||||||||||||
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
|
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.