I am giving you a script. kindly modify the script so that I can use in Google colab and select Google drive folder. you may use any widget or anything but I want to select videos cropping area like android device video editors. here is the script= import tkinter as tk
from tkinter import filedialog, messagebox, ttk
import cv2
import ffmpeg
from PIL import Image, ImageTk
import os
def select_area(event):
global start_x, start_y
start_x, start_y = event.x, event.y
print(f"Start area selected at ({start_x}, {start_y})")
def crop_area(event):
global end_x, end_y, rect_id
end_x, end_y = event.x, event.y
if rect_id:
canvas.delete(rect_id)
rect_id = canvas.create_rectangle(start_x, start_y, end_x, end_y, outline='red')
print(f"Crop area updated to ({end_x}, {end_y})")
def load_frames():
global frame, img_tk, input_files, current_file_index
while True:
files = filedialog.askopenfilenames(filetypes=[("Video files", ".mp4;.avi;.mov;.mkv")])
if not files:
break
input_files.extend(files)
if not input_files:
return
current_file_index = 0
load_next_frame()
instructions = tk.Label(root, text="Instructions:\n1. Load videos.\n2. Select crop area by clicking and dragging.\n3. Press Enter to confirm selection and move to the next video.\n4. Use 'Previous Video' and 'Next Video' buttons to navigate.\n5. Click 'Clear Selection' to reset the crop area.")
instructions.pack()
root.mainloop()
Assistant
To modify the given script for use in Google Colab and to include the ability to select a cropping area like video editors on mobile devices, we will need to make several changes. Since Google Colab does not support GUI frameworks like Tkinter for graphical user interactions, we can use alternative libraries and widgets available in Colab.
Below is a modified version of your script that allows users to select a folder from their Google Drive and manually input crop areas for videos using forms and sliders in the Colab notebook interface.
First, we need to mount Google Drive and then use forms to input crop boundaries. Note that using widgets for interactive video cropping is limited in the Colab environment without a direct GUI.
Here's an example modification:
python
# Ensure these packages are installed
!pip install opencv-python-headless ffmpeg-python
from google.colab import drive
from google.colab import files
import os
import cv2
import ffmpeg
# Mount Google Drive
drive.mount('/content/drive')
drive_folder = '/content/drive/My Drive/Videos/' # Specify your folder path
def crop_videos(files_list, crop_areas):
try:
for i, input_file in enumerate(files_list):
output_file = f"{os.path.splitext(input_file)[0]}_CROPPED.mp4"
start_x, start_y, end_x, end_y = crop_areas[i]
# Calculate width and height for cropping
width = end_x - start_x
height = end_y - start_y
if width <= 0 or height <= 0:
print(f"Invalid crop dimensions for {input_file}")
continue
print(f"Cropping {input_file} with dimensions: ({start_x}, {start_y}, {end_x}, {end_y})")
try:
ffmpeg.input(input_file).crop(x=start_x, y=start_y, width=width, height=height).hflip().output(output_file).run()
print(f"Video {input_file} cropped and flipped successfully!")
except ffmpeg.Error as e:
print(f"FFmpeg error: {e}")
except Exception as e:
print(f"Unexpected error: {e}")
except Exception as e:
print(f"Error: {e}")
# List video files in the specified folder
files_list = [os.path.join(drive_folder, f) for f in os.listdir(drive_folder) if f.endswith(('.mp4', '.avi', '.mov', '.mkv'))]
# For simplicity, let's define crop areas directly for each video.
# In a GUI, these would be selected interactively.
crop_areas = [
# Example: [(start_x1, start_y1, end_x1, end_y1), ...]
(100, 100, 400, 400), # For first video
(120, 120, 360, 360), # For second video
# Add more tuples for each video in files_list
]
# Ensure crop_areas corresponds to files_list
if len(crop_areas) != len(files_list):
print("The number of crop areas must match the number of video files.")
# Process videos
crop_videos(files_list, crop_areas)
User
is it complete script? also improve google drive folder selection interface
Assistant
Here's a complete version of the Colab script with an improved interface for Google Drive folder selection. We'll use the google.colab.drive to mount the drive and ipywidgets for folder selection. You'll need to provide the folder path by browsing your drive after mounting it.
python
User
the script should show one preview frame to confirm my cropping areas accurately
Assistant
To provide a preview of one frame from each video for cropping area confirmation in Google Colab, you can use ipywidgets along with OpenCV to display the frame. Here's an improved script that includes a preview feature:
python
User
i am getting these errors NameError Traceback (most recent call last)
in <cell line: 46>()
44 files_dropdown.options = files_list
45
---> 46 files_list = list_videos(drive_folder)
47
48 # Dropdown to select video file
NameError: name 'list_videos' is not defined
Selected folder: /content/drive/My Drive/DROPMMS
NameError Traceback (most recent call last)
/usr/local/lib/python3.10/dist-packages/ipywidgets/widgets/widget.py in _handle_msg(self, msg)
754 if 'buffer_paths' in data:
755 _put_buffers(state, data['buffer_paths'], msg['buffers'])
--> 756 self.set_state(state)
757
758 # Handle a state request.
14 frames
in refresh_files_list()
42 global files_list
43 files_list = [os.path.join(drive_folder, f) for f in os.listdir(drive_folder) if f.endswith(('.mp4', '.avi', '.mov', '.mkv'))]
---> 44 files_dropdown.options = files_list
45
46 files_list = list_videos(drive_folder)
NameError: name 'files_dropdown' is not defined
Assistant
It looks like there were some issues with the definition and initialization of variables. The missing function list_videos and the order of operations, including initializing lists and widgets, were not correctly defined.
Let's simplify and correct these parts to avoid the NameError. Here’s a revised script that should work correctly:
python
User
also make sure that I can browse and select any subfolders of any depth of Google drive..
Assistant
To enable browsing and selecting any subfolder at any depth within your Google Drive using Google Colab and ipywidgets, we need to dynamically refresh the folder paths in the dropdowns recursively. Here's how to accomplish this:
python
User
modifiy the script so that after entering values preview come after clicking preview button.
Assistant
To modify the script such that the video frame preview is displayed after clicking a "Preview" button, we'll need to add the button and link its click event to the preview function. Here’s how you can adjust the script:
python
User
also make sure that output video should save in the same location of input video after cropping. the new output video's name should input video's name+cropped suffix
Assistant
To ensure the output video is saved in the same directory as the input video with a name suffix _cropped, we'll modify the output filename construction in the script. Here’s the complete revised script:
python
User
i am not getting sounds of videos after cropping.please fix it. also make preview screen smaller irrespective of video resolution (asume that I am using Google colab in mobile phone)
Assistant
To ensure that the audio stream is preserved while cropping videos with FFmpeg, you can specify the acodec parameter to copy the audio along with the video when generating the output file. Additionally, to accommodate viewing the preview on mobile devices, we can adjust its display size using Matplotlib.
Here's the revised script that addresses both issues:
python
User
after running script, I am getting these errors= File "", line 127
output_file, vcodec='libx264', acodec='aac', map='0:v', map='0:a').run()
^
SyntaxError: keyword argument repeated: map
Also no need options to being able to resize preview window. just make it little smaller if you can. (Why I am getting errors each time, make script perfectly, don't waste too much time making one script. give more attention during creating codes)
Assistant
I apologize for the oversight. Let's fix the repeated keyword argument issue and streamline the script for a smaller, fixed preview size. Here's the revised version:
python
User
still not getting video sounds in output videos. why same thing happening each time? fix these please
Assistant
I apologize for the continued issues. Let's ensure we preserve the audio track correctly while cropping the videos. Here's how we can resolve the audio issue:
Ensure Audio is Explicitly Copied: Use FFmpeg options to ensure that the audio track is preserved, not just assumed to copy by default.
Focus Using Correct FFmpeg Options: Use ffmpeg.filter() to apply the crop without disturbing the audio.
Let's fine-tune the script to achieve this correctly:
python
User
now I am getting these errors...Error Traceback (most recent call last)
in crop_videos()
128 video_stream = streams.video.filter('crop', x=start_x, y=start_y, width=width, height=height)
--> 129 ffmpeg.output(video_stream, streams.audio, output_file, vcodec='libx264', acodec='aac', strict='experimental').run()
130 print(f"Cropped and saved as: {output_file}")
2 frames
Error: ffmpeg error (see stderr output for detail)
During handling of the above exception, another exception occurred:
AttributeError Traceback (most recent call last)
in crop_videos()
130 print(f"Cropped and saved as: {output_file}")
131 except ffmpeg.Error as e:
--> 132 print(f"FFmpeg error: {e.stderr.decode()}")
133 except Exception as e:
134 print(f"Unexpected error: {e}")
AttributeError: 'NoneType' object has no attribute 'decode'
Assistant
I'm sorry to hear you're facing issues. The error you're experiencing typically arises when ffmpeg encounters an error during execution, but the handling of the error message isn't accurate. Let's address the issues by adjusting the error handling and ensuring that the ffmpeg commands are executed correctly. I'll also add some safeguards to ensure better error inspection.
Here is the revised version of the script with improved error handling:
python
User
you may re encode audio also for if it etter
Assistant
Certainly! Re-encoding the audio to a common format like AAC can sometimes help resolve compatibility issues. We can update the FFmpeg commands to ensure both the video and audio are re-encoded, which should address the issue effectively. Here's the revised script:
python
User
i am getting these FFmpeg error: No error details available
FFmpeg error: No error details available
Assistant
When the ffmpeg command fails to produce error details, it's important to ensure that we're using the right approach to capture any potential issues. Here are some steps to help troubleshoot and resolve this problem:
Ensure FFmpeg and Input Validity: Double-check that the ffmpeg installation is correct and that the input files are valid and accessible.
Verbose Logging: Enable more verbose logging to help capture detailed error output.
Here's an updated script with improved logging and error capturing:
python
User
i am getting these output with errors=Starting crop...
File conversion failed
The error message indicates that FFmpeg is encountering an issue with the crop filter arguments, specifically that height is not being recognized as it should. This typically happens if the arguments to the crop filter aren't formatted correctly. Let's make sure everything is set up right for FFmpeg to properly receive these parameters.
Here's the revised script ensuring correct FFmpeg argument usage:
python
User
remember , if I put my slider sometimes at zero it means I don't want to crop videos from that side
Assistant
Understood. If setting the slider to zero indicates that you don't want to crop from a particular side, the script should handle that gracefully by keeping the selection unchanged for those edges.
Here's the updated script making sure that the crop dimensions are set correctly when sliders are at zero:
The error you're encountering indicates an issue with the crop filter arguments, suggesting that the computed width or height for the crop is larger than what is available in the video or is negative. This usually happens when the crop area is incorrectly calculated, either exceeding the original video dimensions or having zero or negative size.
To resolve this, we should adjust the crop logic to be more defensive in checking for valid crop regions. Additionally, we need to handle the edge case where sliders are set to the maximum dimensions, implying no cropping should happen. Let's fix the code accordingly:
The error message indicates that the calculated crop dimensions (width and height) exceed the actual dimensions of the video or are non-positive. There are a few steps you can take to ensure that FFmpeg receives valid and feasible crop dimensions:
Ensure Valid Crop Dimensions: Calculate crop dimensions such that they do not exceed the video size and are non-zero.
Dynamic Adjustment: Adjust slider values if the calculated crop dimensions are invalid.
Here's the updated code with additional checks to ensure valid crop dimensions:
python
User
remember , my google drive folder may contain each videos with different resolutions
Assistant
Thank you for mentioning that. Let's ensure the script dynamically adapts to each video's specific resolution. The approach will be to load each video individually, and set the slider ranges based on that video's dimensions, before allowing the user to preview or crop.
Here's an enhanced script that dynamically sets slider limits based on the active video's resolution:
python
User
okay it's working. now can you make start and end x, y etc like 0 to 100 in range each?
Assistant
Certainly! To adjust the sliders so that they range from 0 to 100 (representing percentages of the video dimensions), we'll modify the sliders' range and calculate the crop coordinates based on these percentages. This allows for a more intuitive cropping setup.
Here's how you can achieve that:
python
User
also try to give a feedback at output so that I can get idea about how much time will require
Assistant
To provide feedback on the estimated time remaining during the processing of each video, we can display a progress bar along with estimated time feedback. Although FFmpeg itself does not provide direct timing feedback during processing, we can approximate the progress based on the video's duration and the current time.
Here's how you can enhance the script to display a progress bar and provide estimated remaining time:
python
User
progress bar not supporting properly so remove feedback portion from script
Assistant
If the progress bar and related feedback aren't required or aren't functioning as expected, it's simple to remove those elements. Below is the script without the progress feedback components, focusing on the main functionality of cropping videos based on percentage sliders:
python
User
okay I am saving this script. I want another version of this script where I can select crop percentage of each of the videos instead of just one video. I want the script should give me button for selecting percentage of cropping videos one by one. once I Mark all videos then the script should start cropping process based on my input. can you do that?
Assistant
Certainly! Let's modify the script so you can manually set the crop percentages for each video before starting the crop process. We'll implement navigation through the videos with a button for setting crop percentages individually. Once all settings are complete, a button will allow you to begin the cropping process for all videos in sequence.
Here's how you can achieve this:
python
User
Drive already mounted at /content/drive; to attempt to forcibly remount, call drive.mount("/content/drive", force_remount=True).
Select Folder:
The error you're experiencing indicates that the files_list is empty, meaning no video files were found in the selected folder. This is likely happening because the directory you selected doesn't contain files with the specified extensions. Let's make sure that all components are working correctly:
Ensure Correct Folder Selection: Make sure your Google Drive folder actually contains video files with the extensions .mp4, .avi, .mov, or .mkv.
Add Error Handling: Modify the script to handle the case where no video files are found to prevent the index error.
Debugging Output: Verify the directories and file paths being accessed.
Here's the updated version of the script with better error handling and debugging outputs:
python
User
i want to navigate through each folder and subfolders of Google drive to select folder containing videos like my previous script, why you already changed that?
Assistant
Let's modify the script to allow you to navigate through folders and subfolders in your Google Drive. We will restore that functionality so you can choose the exact folder that contains your videos. I will make sure that you can select the folder and set the cropping percentages for each video individually.
Here is the updated script:
python
User
getting this out put No video files available to preview.
Assistant
The message "No video files available to preview" indicates that the script didn't find any video files in the selected directory. Here are some steps to troubleshoot and resolve this issue:
Verify Files are Present: Ensure that the selected Google Drive folder contains video files with the extensions .mp4, .avi, .mov, or .mkv.
Path Check: Check for any typos or errors in the path or when selecting directories.
Enhance Debugging: Add extra logging to verify file detection processes.
If your folder structure and video file formats are fine, there might have been an issue during directory listing or file extension filtering. Here's an updated version of the script with additional logging to help identify why files might not be detected:
python
User
it shows this error even before I selecting folder through navigating
Assistant
To ensure that the script runs smoothly and allows folder navigation to select the correct directory, let's refine the initial setup to handle situations where no folder is selected or no videos are found. We'll ensure the script waits for folder selection before proceeding with attempts to list video files.
Here's how to set up the script correctly:
python
User
i should get preview with marking after selecting area
Assistant
Certainly! After selecting the crop area using sliders, you should immediately see a marked preview of the video. Let's set it up so that after you adjust the crop area sliders, the preview is automatically updated with the selected area.
Ensure that your video files are stored in the specified Google Drive folder.
Modify drive_folder to point to the correct path in your Google Drive.
Adjust the crop_areas list to define the crop dimensions for each video. The length of this list must match files_list.
Note: Interactive cropping as you might in a GUI app is not feasible directly in Colab due to its server-side execution nature. Such tasks typically require a client-side UI environment.
# Install necessary packages
!pip install opencv-python-headless ffmpeg-python
import os
import cv2
import ffmpeg
from google.colab import drive
import ipywidgets as widgets
from IPython.display import display
# Function to crop and flip videos
def crop_videos(files_list, crop_areas):
try:
for i, input_file in enumerate(files_list):
output_file = f"{os.path.splitext(input_file)[0]}_CROPPED.mp4"
start_x, start_y, end_x, end_y = crop_areas[i]
# Calculate width and height for cropping
width = end_x - start_x
height = end_y - start_y
if width <= 0 or height <= 0:
print(f"Invalid crop dimensions for {input_file}")
continue
print(f"Cropping {input_file} with dimensions: ({start_x}, {start_y}, {end_x}, {end_y})")
try:
ffmpeg.input(input_file).crop(x=start_x, y=start_y, width=width, height=height).hflip().output(output_file).run()
print(f"Video {input_file} cropped and flipped successfully!")
except ffmpeg.Error as e:
print(f"FFmpeg error: {e}")
except Exception as e:
print(f"Unexpected error: {e}")
except Exception as e:
print(f"Error: {e}")
# Mount Google Drive
drive.mount('/content/drive')
# Function to browse the Google Drive directory structure
def browse_drive(folder='/content/drive/My Drive'):
items = os.listdir(folder)
subfolders = [item for item in items if os.path.isdir(os.path.join(folder, item))]
return subfolders
# Dropdown widget to select folder
folder_dropdown = widgets.Dropdown(
options=browse_drive(),
description='Folder:',
layout=widgets.Layout(width='50%')
)
display(folder_dropdown)
# Update the folder path based on selection
def update_folder_path(change):
global drive_folder
selected_subfolder = change.new
drive_folder = os.path.join('/content/drive/My Drive', selected_subfolder)
print(f'Selected folder: {drive_folder}')
folder_dropdown.observe(update_folder_path, names='value')
# After folder selection, list video files
def list_videos(folder_path):
video_files = [os.path.join(folder_path, f) for f in os.listdir(folder_path) if f.endswith(('.mp4', '.avi', '.mov', '.mkv'))]
return video_files
# After setting drive_folder, you must manually update this list:
files_list = list_videos(drive_folder)
# Define crop areas for corresponding videos in files_list (inputs should be user-defined)
crop_areas = [
# Example: [(start_x, start_y, end_x, end_y), ...]
(100, 100, 400, 400), # Example for first video
# Add additional tuples for each video in files_list
]
# Check if crop_areas length matches files_list and process
if len(crop_areas) != len(files_list):
print("Ensure the number of specified crop areas matches the number of video files.")
# Process videos
crop_videos(files_list, crop_areas)
Key Changes:
Google Drive: The script mounts Google Drive and allows for browsing using dropdowns to select the folder containing videos.
Interactive Widgets: Utilizes ipywidgets to create a dropdown for folder selection, offering a more interactive experience in Colab.
Note on Crop Areas: Users should manually define crop areas in the crop_areas list corresponding to each video. It should be adapted interactively if needed, though this script uses predefined values due to the limitation of GUI-interactive cropping in Colab.
Instructions:
Run the script in a Colab notebook.
Mount your Google Drive.
Use the dropdown to navigate and select the correct folder containing videos.
Manually set crop_areas to define appropriate cropping for each video.
Ensure the crop_areas list matches the files_list in length.
Run the process to crop and flip the videos.
Adjust this script to match your specific needs for video cropping and file handling.
# Install necessary packages
!pip install opencv-python-headless ffmpeg-python
import os
import cv2
import ffmpeg
from google.colab import drive
import ipywidgets as widgets
from IPython.display import display, clear_output
import matplotlib.pyplot as plt
# Mount Google Drive
drive.mount('/content/drive')
# Function to browse directories in Google Drive
def browse_drive(folder='/content/drive/My Drive'):
items = os.listdir(folder)
subfolders = [item for item in items if os.path.isdir(os.path.join(folder, item))]
return subfolders
# Dropdown widget for folder selection
folder_dropdown = widgets.Dropdown(
options=browse_drive(),
description='Folder:',
layout=widgets.Layout(width='50%')
)
display(folder_dropdown)
# Update folder path based on selection
drive_folder = '/content/drive/My Drive'
def update_folder_path(change):
global drive_folder
selected_subfolder = change.new
drive_folder = os.path.join(drive_folder, selected_subfolder)
print(f'Selected folder: {drive_folder}')
refresh_files_list()
folder_dropdown.observe(update_folder_path, names='value')
# Refresh video files list based on current folder selection
def refresh_files_list():
global files_list
files_list = [os.path.join(drive_folder, f) for f in os.listdir(drive_folder) if f.endswith(('.mp4', '.avi', '.mov', '.mkv'))]
files_dropdown.options = files_list
files_list = list_videos(drive_folder)
# Dropdown to select video file
files_dropdown = widgets.Dropdown(
options=files_list,
description='Video:',
layout=widgets.Layout(width='100%')
)
display(files_dropdown)
# Image display placeholder
image_widget = widgets.Output()
# Slider for selecting crop areas
x_start_slider = widgets.IntSlider(value=0, min=0, max=640, step=1, description="Start X:")
y_start_slider = widgets.IntSlider(value=0, min=0, max=480, step=1, description="Start Y:")
x_end_slider = widgets.IntSlider(value=640, min=0, max=640, step=1, description="End X:")
y_end_slider = widgets.IntSlider(value=480, min=0, max=480, step=1, description="End Y:")
def show_preview(*args):
clear_output(wait=True)
display(folder_dropdown, files_dropdown, image_widget, x_start_slider, y_start_slider, x_end_slider, y_end_slider)
selected_file = files_dropdown.value
if not selected_file:
print("No video selected.")
return
cap = cv2.VideoCapture(selected_file)
ret, frame = cap.read()
cap.release()
if not ret:
print("Error reading video frame.")
return
frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
fig, ax = plt.subplots()
ax.imshow(frame_rgb)
ax.set_title('Select crop area')
crop_area = [
(x_start_slider.value, y_start_slider.value),
(x_end_slider.value, y_end_slider.value)
]
rect = plt.Rectangle(crop_area[0], crop_area[1][0]-crop_area[0][0], crop_area[1][1]-crop_area[0][1],
linewidth=1, edgecolor='r', facecolor='none')
ax.add_patch(rect)
plt.show()
# Update crop slider maximum values to match actual video dimensions
def update_sliders(*args):
selected_file = files_dropdown.value
if not selected_file:
return
cap = cv2.VideoCapture(selected_file)
ret, frame = cap.read()
cap.release()
if not ret:
return
height, width = frame.shape[:2]
x_start_slider.max = x_end_slider.max = width
y_start_slider.max = y_end_slider.max = height
files_dropdown.observe(show_preview, names='value')
files_dropdown.observe(update_sliders, names='value')
x_start_slider.observe(show_preview, names='value')
y_start_slider.observe(show_preview, names='value')
x_end_slider.observe(show_preview, names='value')
y_end_slider.observe(show_preview, names='value')
display(image_widget, x_start_slider, y_start_slider, x_end_slider, y_end_slider)
# Function to crop videos
def crop_videos(crop_areas):
print("Starting crop...")
for idx, input_file in enumerate(files_list):
output_file = f"{os.path.splitext(input_file)[0]}_CROPPED.mp4"
start_x, start_y, end_x, end_y = crop_areas[idx]
width = end_x - start_x
height = end_y - start_y
if width <= 0 or height <= 0:
print(f"Invalid crop dimensions for {input_file}")
continue
try:
ffmpeg.input(input_file).crop(x=start_x, y=start_y, width=width, height=height).hflip().output(output_file).run()
print(f"Cropped {input_file} successfully!")
except ffmpeg.Error as e:
print(f"FFmpeg error: {e}")
except Exception as e:
print(f"Unexpected error: {e}")
# Button to start cropping process
crop_button = widgets.Button(description='Start Cropping')
def on_crop_button_clicked(b):
crop_areas = [(x_start_slider.value, y_start_slider.value, x_end_slider.value, y_end_slider.value)]
crop_videos(crop_areas)
crop_button.on_click(on_crop_button_clicked)
display(crop_button)
Steps and Features:
Google Drive: The script mounts and lets you browse folders from Google Drive.
Preview Frame: Before execution, it shows a preview frame where you can adjust crop area via sliders.
Dynamic Sliders: The sliders are updated based on the dimensions of the video, ensuring accurate cropping selection.
Widgets: Uses interactive widgets for file selection, defining crop areas, and displaying preview.
Usage:
Execute each cell sequentially in Google Colab.
Select a folder using the provided dropdown.
Choose a video to preview a single frame.
Adjust sliders to select the cropping area. Preview updates dynamically.
Press the "Start Cropping" button to crop videos based on set parameters.
Remember, interactive element rendering relies on a proper Colab notebook session, and video processing is subject to server-side execution constraints. Adjust your crop areas manually for each video sequentially.
# Install necessary packages
!pip install opencv-python-headless ffmpeg-python
import os
import cv2
import ffmpeg
from google.colab import drive
import ipywidgets as widgets
from IPython.display import display, clear_output
import matplotlib.pyplot as plt
# Mount Google Drive
drive.mount('/content/drive')
# Function to browse directories in Google Drive
def browse_drive(folder='/content/drive/My Drive'):
items = os.listdir(folder)
subfolders = [item for item in items if os.path.isdir(os.path.join(folder, item))]
return subfolders
# Initialize drive folder
drive_folder = '/content/drive/My Drive'
# Dropdown widget for folder selection
folder_dropdown = widgets.Dropdown(
options=browse_drive(),
description='Folder:',
layout=widgets.Layout(width='50%')
)
display(folder_dropdown)
# Function to refresh video files list based on current folder selection
def refresh_files_list():
global drive_folder, files_list, files_dropdown
files_list = [os.path.join(drive_folder, f) for f in os.listdir(drive_folder) if f.endswith(('.mp4', '.avi', '.mov', '.mkv'))]
files_dropdown.options = files_list
# Function to update drive folder path
def update_folder_path(change):
global drive_folder
selected_subfolder = change.new
drive_folder = os.path.join('/content/drive/My Drive', selected_subfolder)
print(f'Selected folder: {drive_folder}')
refresh_files_list()
folder_dropdown.observe(update_folder_path, names='value')
# Dropdown to select video file
files_dropdown = widgets.Dropdown(
options=[],
description='Video:',
layout=widgets.Layout(width='100%')
)
display(files_dropdown)
# Image display placeholder
image_widget = widgets.Output()
# Sliders for selecting crop areas
x_start_slider = widgets.IntSlider(value=0, min=0, max=640, step=1, description="Start X:")
y_start_slider = widgets.IntSlider(value=0, min=0, max=480, step=1, description="Start Y:")
x_end_slider = widgets.IntSlider(value=640, min=0, max=640, step=1, description="End X:")
y_end_slider = widgets.IntSlider(value=480, min=0, max=480, step=1, description="End Y:")
# Show video frame preview
def show_preview(*args):
clear_output(wait=True)
display(folder_dropdown, files_dropdown, image_widget, x_start_slider, y_start_slider, x_end_slider, y_end_slider, crop_button)
selected_file = files_dropdown.value
if not selected_file:
print("No video selected.")
return
cap = cv2.VideoCapture(selected_file)
ret, frame = cap.read()
cap.release()
if not ret:
print("Error reading video frame.")
return
height, width = frame.shape[:2]
x_start_slider.max = x_end_slider.max = width
y_start_slider.max = y_end_slider.max = height
frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
fig, ax = plt.subplots()
ax.imshow(frame_rgb)
ax.set_title('Select crop area')
crop_area = [
(x_start_slider.value, y_start_slider.value),
(x_end_slider.value, y_end_slider.value)
]
rect = plt.Rectangle(crop_area[0], crop_area[1][0]-crop_area[0][0], crop_area[1][1]-crop_area[0][1],
linewidth=1, edgecolor='r', facecolor='none')
ax.add_patch(rect)
plt.show()
files_dropdown.observe(show_preview, names='value')
x_start_slider.observe(show_preview, names='value')
y_start_slider.observe(show_preview, names='value')
x_end_slider.observe(show_preview, names='value')
y_end_slider.observe(show_preview, names='value')
display(image_widget, x_start_slider, y_start_slider, x_end_slider, y_end_slider)
# Function to crop videos
def crop_videos(crop_areas):
print("Starting crop...")
for idx, input_file in enumerate(files_list):
output_file = f"{os.path.splitext(input_file)[0]}_CROPPED.mp4"
start_x, start_y, end_x, end_y = crop_areas[idx]
width = end_x - start_x
height = end_y - start_y
if width <= 0 or height <= 0:
print(f"Invalid crop dimensions for {input_file}")
continue
try:
ffmpeg.input(input_file).crop(x=start_x, y=start_y, width=width, height=height).hflip().output(output_file).run()
print(f"Cropped {input_file} successfully!")
except ffmpeg.Error as e:
print(f"FFmpeg error: {e}")
except Exception as e:
print(f"Unexpected error: {e}")
# Button to start cropping process
crop_button = widgets.Button(description='Start Cropping')
def on_crop_button_clicked(b):
crop_areas = [(x_start_slider.value, y_start_slider.value, x_end_slider.value, y_end_slider.value)]
crop_videos(crop_areas)
crop_button.on_click(on_crop_button_clicked)
display(crop_button)
Key fixes and notes:
Function Definitions: Ensure all functions (refresh_files_list) and variables are defined before they are called.
Dynamic List Updates: Update files_list and files_dropdown when a new folder is selected.
Slider Adjustment: Automatically adjust slider ranges according to video frame dimensions on preview.
Sequential Display: Proper ordering of widget displays ensures smooth interaction in Colab.
To use this script, make sure you execute each part in sequence in a Colab notebook, paying attention to any Google Drive permissions. The sliders allow you to choose the area for cropping interactively, and the selected area is previewed on the frame displayed.
# Install necessary packages
!pip install opencv-python-headless ffmpeg-python
import os
import cv2
import ffmpeg
from google.colab import drive
import ipywidgets as widgets
from IPython.display import display, clear_output
import matplotlib.pyplot as plt
# Mount Google Drive
drive.mount('/content/drive')
# Function to browse directories in Google Drive
def browse_subfolders(base_folder='/content/drive/My Drive'):
"""Returns a list of subfolder paths."""
folder_list = []
for dirname, _, _ in os.walk(base_folder):
folder_list.append(dirname)
return folder_list
# Prepare folder navigation
folder_dropdown = widgets.Dropdown(
options=browse_subfolders(),
description='Select Folder:',
layout=widgets.Layout(width='100%')
)
display(folder_dropdown)
drive_folder = '/content/drive/My Drive'
# Callback to update drive folder path
def update_folder_path(change):
global drive_folder
drive_folder = change.new
print(f'Selected folder: {drive_folder}')
refresh_files_list()
folder_dropdown.observe(update_folder_path, names='value')
# Function to refresh video files list based on current folder selection
files_list = []
files_dropdown = widgets.Dropdown(
options=files_list,
description='Select Video:',
layout=widgets.Layout(width='100%')
)
display(files_dropdown)
def refresh_files_list():
global files_list
files_list = [os.path.join(drive_folder, f) for f in os.listdir(drive_folder) if f.lower().endswith(('.mp4', '.avi', '.mov', '.mkv'))]
files_dropdown.options = files_list or ["No video files found"]
# Display video frame preview and adjust sliders
image_widget = widgets.Output()
x_start_slider = widgets.IntSlider(value=0, min=0, max=640, step=1, description="Start X:")
y_start_slider = widgets.IntSlider(value=0, min=0, max=480, step=1, description="Start Y:")
x_end_slider = widgets.IntSlider(value=640, min=0, max=640, step=1, description="End X:")
y_end_slider = widgets.IntSlider(value=480, min=0, max=480, step=1, description="End Y:")
def show_preview(*args):
clear_output(wait=True)
display(folder_dropdown, files_dropdown, image_widget, x_start_slider, y_start_slider, x_end_slider, y_end_slider, crop_button)
selected_file = files_dropdown.value
if not selected_file or selected_file == "No video files found":
print("No video selected or found.")
return
cap = cv2.VideoCapture(selected_file)
ret, frame = cap.read()
cap.release()
if not ret:
print("Error reading video frame.")
return
height, width = frame.shape[:2]
x_start_slider.max = x_end_slider.max = width
y_start_slider.max = y_end_slider.max = height
frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
fig, ax = plt.subplots()
ax.imshow(frame_rgb)
ax.set_title('Select crop area')
crop_area = [
(x_start_slider.value, y_start_slider.value),
(x_end_slider.value, y_end_slider.value)
]
rect = plt.Rectangle(crop_area[0], crop_area[1][0]-crop_area[0][0], crop_area[1][1]-crop_area[0][1],
linewidth=1, edgecolor='r', facecolor='none')
ax.add_patch(rect)
plt.show()
files_dropdown.observe(show_preview, names='value')
x_start_slider.observe(show_preview, names='value')
y_start_slider.observe(show_preview, names='value')
x_end_slider.observe(show_preview, names='value')
y_end_slider.observe(show_preview, names='value')
display(image_widget, x_start_slider, y_start_slider, x_end_slider, y_end_slider)
# Define the function to crop videos
def crop_videos(crop_areas):
print("Starting crop...")
for idx, input_file in enumerate(files_list):
output_file = f"{os.path.splitext(input_file)[0]}_CROPPED.mp4"
start_x, start_y, end_x, end_y = crop_areas[idx]
width = end_x - start_x
height = end_y - start_y
if width <= 0 or height <= 0:
print(f"Invalid crop dimensions for {input_file}")
continue
try:
ffmpeg.input(input_file).crop(x=start_x, y=start_y, width=width, height=height).hflip().output(output_file).run()
print(f"Cropped {input_file} successfully!")
except ffmpeg.Error as e:
print(f"FFmpeg error: {e}")
except Exception as e:
print(f"Unexpected error: {e}")
# Button to start cropping process
crop_button = widgets.Button(description='Start Cropping')
def on_crop_button_clicked(b):
crop_areas = [(x_start_slider.value, y_start_slider.value, x_end_slider.value, y_end_slider.value)]
crop_videos(crop_areas)
crop_button.on_click(on_crop_button_clicked)
display(crop_button)
Key Changes and Features:
Recursive Folder Browsing: Uses os.walk to populate the dropdown with all subfolders at any depth.
Dynamic Dropdown Updates: Updates video file options dynamically when a folder selection changes.
Interactive Sliders and Preview: Provides live updates to the preview based on slider actions, allowing precise crop area adjustment.
User Guidance: Prints messages and adjusts widgets based on user actions to aid navigation and selection.
How to Use:
Execute the script in a Colab notebook.
Mount Google Drive and choose a folder with the dropdown. You can navigate to any depth.
Choose a video from the files dropdown; the frame will update for crop area selection.
Adjust crop area using sliders displayed beneath the video preview.
Press "Start Cropping" to crop and save videos using the defined selections.
This solution allows you to navigate through the entire folder structure in your Google Drive to choose desired folders and videos for processing.
# Install necessary packages
!pip install opencv-python-headless ffmpeg-python -q
import os
import cv2
import ffmpeg
from google.colab import drive
import ipywidgets as widgets
from IPython.display import display, clear_output
import matplotlib.pyplot as plt
# Mount Google Drive
drive.mount('/content/drive')
# Function to browse directories in Google Drive
def browse_subfolders(base_folder='/content/drive/My Drive'):
"""Returns a list of subfolder paths."""
folder_list = []
for dirname, _, _ in os.walk(base_folder):
folder_list.append(dirname)
return folder_list
# Folder navigation setup
folder_dropdown = widgets.Dropdown(
options=browse_subfolders(),
description='Select Folder:',
layout=widgets.Layout(width='100%')
)
display(folder_dropdown)
drive_folder = '/content/drive/My Drive'
# Callback to update drive folder path
def update_folder_path(change):
global drive_folder
drive_folder = change.new
print(f'Selected folder: {drive_folder}')
refresh_files_list()
folder_dropdown.observe(update_folder_path, names='value')
# Function to refresh video files list based on current folder selection
files_list = []
files_dropdown = widgets.Dropdown(
options=files_list,
description='Select Video:',
layout=widgets.Layout(width='100%')
)
display(files_dropdown)
def refresh_files_list():
global files_list
files_list = [os.path.join(drive_folder, f) for f in os.listdir(drive_folder) if f.lower().endswith(('.mp4', '.avi', '.mov', '.mkv'))]
files_dropdown.options = files_list or ["No video files found"]
# Image display and control widgets
image_widget = widgets.Output()
x_start_slider = widgets.IntSlider(value=0, min=0, max=640, step=1, description="Start X:")
y_start_slider = widgets.IntSlider(value=0, min=0, max=480, step=1, description="Start Y:")
x_end_slider = widgets.IntSlider(value=640, min=0, max=640, step=1, description="End X:")
y_end_slider = widgets.IntSlider(value=480, min=0, max=480, step=1, description="End Y:")
# Show video frame preview
def show_preview(*args):
clear_output(wait=True)
display(folder_dropdown, files_dropdown, preview_button, image_widget, x_start_slider, y_start_slider, x_end_slider, y_end_slider, crop_button)
selected_file = files_dropdown.value
if not selected_file or selected_file == "No video files found":
print("No video selected or found.")
return
cap = cv2.VideoCapture(selected_file)
ret, frame = cap.read()
cap.release()
if not ret:
print("Error reading video frame.")
return
height, width = frame.shape[:2]
x_start_slider.max = x_end_slider.max = width
y_start_slider.max = y_end_slider.max = height
frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
fig, ax = plt.subplots()
ax.imshow(frame_rgb)
ax.set_title('Select crop area')
crop_area = [
(x_start_slider.value, y_start_slider.value),
(x_end_slider.value, y_end_slider.value)
]
rect = plt.Rectangle(crop_area[0], crop_area[1][0]-crop_area[0][0], crop_area[1][1]-crop_area[0][1],
linewidth=1, edgecolor='r', facecolor='none')
ax.add_patch(rect)
plt.show()
# Button to trigger preview
preview_button = widgets.Button(description='Preview')
preview_button.on_click(show_preview)
# Display widgets
display(preview_button, image_widget, x_start_slider, y_start_slider, x_end_slider, y_end_slider)
# Define the function to crop videos
def crop_videos(crop_areas):
print("Starting crop...")
for idx, input_file in enumerate(files_list):
output_file = f"{os.path.splitext(input_file)[0]}_CROPPED.mp4"
start_x, start_y, end_x, end_y = crop_areas[idx]
width = end_x - start_x
height = end_y - start_y
if width <= 0 or height <= 0:
print(f"Invalid crop dimensions for {input_file}")
continue
try:
ffmpeg.input(input_file).crop(x=start_x, y=start_y, width=width, height=height).hflip().output(output_file).run()
print(f"Cropped {input_file} successfully!")
except ffmpeg.Error as e:
print(f"FFmpeg error: {e}")
except Exception as e:
print(f"Unexpected error: {e}")
# Button to start cropping process
crop_button = widgets.Button(description='Start Cropping')
def on_crop_button_clicked(b):
crop_areas = [(x_start_slider.value, y_start_slider.value, x_end_slider.value, y_end_slider.value)]
crop_videos(crop_areas)
crop_button.on_click(on_crop_button_clicked)
display(crop_button)
Key Changes:
Introduction of a Preview Button: The preview_button is introduced to trigger the frame preview, requiring user interaction for the preview display.
Manual Interaction Flow: The preview only updates when the "Preview" button is clicked, not automatically when sliders are adjusted.
How to Use:
Run the script in a Colab notebook.
Choose the folder with videos using dropdown menus.
Select a video file from the dropdown.
Use the sliders to set cropping values.
Click the "Preview" button to display the frame and the selected crop area.
Adjust the sliders as needed and re-click "Preview" to see changes.
Click "Start Cropping" to apply the crop settings to the selected video(s).
This workflow incorporates manual interaction via widgets, which fits well with Google Colab’s notebook interface constraints.
# Install necessary packages
!pip install opencv-python-headless ffmpeg-python -q
import os
import cv2
import ffmpeg
from google.colab import drive
import ipywidgets as widgets
from IPython.display import display, clear_output
import matplotlib.pyplot as plt
# Mount Google Drive
drive.mount('/content/drive')
# Function to browse directories in Google Drive
def browse_subfolders(base_folder='/content/drive/My Drive'):
"""Returns a list of subfolder paths."""
folder_list = []
for dirname, _, _ in os.walk(base_folder):
folder_list.append(dirname)
return folder_list
# Folder navigation setup
folder_dropdown = widgets.Dropdown(
options=browse_subfolders(),
description='Select Folder:',
layout=widgets.Layout(width='100%')
)
display(folder_dropdown)
drive_folder = '/content/drive/My Drive'
# Callback to update drive folder path
def update_folder_path(change):
global drive_folder
drive_folder = change.new
print(f'Selected folder: {drive_folder}')
refresh_files_list()
folder_dropdown.observe(update_folder_path, names='value')
# Function to refresh video files list based on current folder selection
files_list = []
files_dropdown = widgets.Dropdown(
options=files_list,
description='Select Video:',
layout=widgets.Layout(width='100%')
)
display(files_dropdown)
def refresh_files_list():
global files_list
files_list = [os.path.join(drive_folder, f) for f in os.listdir(drive_folder) if f.lower().endswith(('.mp4', '.avi', '.mov', '.mkv'))]
files_dropdown.options = files_list or ["No video files found"]
# Image display and control widgets
image_widget = widgets.Output()
x_start_slider = widgets.IntSlider(value=0, min=0, max=640, step=1, description="Start X:")
y_start_slider = widgets.IntSlider(value=0, min=0, max=480, step=1, description="Start Y:")
x_end_slider = widgets.IntSlider(value=640, min=0, max=640, step=1, description="End X:")
y_end_slider = widgets.IntSlider(value=480, min=0, max=480, step=1, description="End Y:")
def update_sliders(width, height):
x_start_slider.max = x_end_slider.max = width
y_start_slider.max = y_end_slider.max = height
# Show video frame preview
def show_preview(*args):
clear_output(wait=True)
display(folder_dropdown, files_dropdown, preview_button, image_widget, x_start_slider, y_start_slider, x_end_slider, y_end_slider, crop_button)
selected_file = files_dropdown.value
if not selected_file or selected_file == "No video files found":
print("No video selected or found.")
return
cap = cv2.VideoCapture(selected_file)
ret, frame = cap.read()
cap.release()
if not ret:
print("Error reading video frame.")
return
height, width = frame.shape[:2]
update_sliders(width, height)
frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
fig, ax = plt.subplots()
ax.imshow(frame_rgb)
ax.set_title('Select crop area')
crop_area = [
(x_start_slider.value, y_start_slider.value),
(x_end_slider.value, y_end_slider.value)
]
rect = plt.Rectangle(crop_area[0], crop_area[1][0] - crop_area[0][0], crop_area[1][1] - crop_area[0][1],
linewidth=1, edgecolor='r', facecolor='none')
ax.add_patch(rect)
plt.show()
# Button to trigger preview
preview_button = widgets.Button(description='Preview')
preview_button.on_click(show_preview)
# Display widgets
display(preview_button, image_widget, x_start_slider, y_start_slider, x_end_slider, y_end_slider)
# Define the function to crop videos
def crop_videos():
print("Starting crop...")
for input_file in files_list:
# Construct output file path with "_cropped" suffix
file_dir, file_name = os.path.split(input_file)
file_base, file_ext = os.path.splitext(file_name)
output_file = os.path.join(file_dir, f"{file_base}_cropped{file_ext}")
start_x, start_y, end_x, end_y = x_start_slider.value, y_start_slider.value, x_end_slider.value, y_end_slider.value
width = end_x - start_x
height = end_y - start_y
if width <= 0 or height <= 0:
print(f"Invalid crop dimensions for {input_file}")
continue
try:
ffmpeg.input(input_file).crop(x=start_x, y=start_y, width=width, height=height).hflip().output(output_file).run()
print(f"Cropped and saved as: {output_file}")
except ffmpeg.Error as e:
print(f"FFmpeg error: {e}")
except Exception as e:
print(f"Unexpected error: {e}")
# Button to start cropping process
crop_button = widgets.Button(description='Start Cropping')
crop_button.on_click(lambda b: crop_videos())
display(crop_button)
Key Features:
Output Location: Cropped videos are saved in the same directory as the input videos.
Naming Convention: Adds _cropped suffix to the original filename.
Preview Button: Displays the video frame preview on clicking "Preview" after adjusting the sliders.
Widgets for Interaction: Sliders for specifying the crop areas with dynamic updates.
How to Use:
Run the script in a Colab notebook.
Mount your Google Drive and select a folder with video files via the dropdown.
Choose a video and adjust the crop area using the sliders.
Click "Preview" to visualize the selection on a frame of the video.
Once satisfied, click "Start Cropping" to process the video.
The cropped video is saved with _cropped appended to its name in the same location as the original video.
# Install necessary packages
!pip install opencv-python-headless ffmpeg-python -q
import os
import cv2
import ffmpeg
from google.colab import drive
import ipywidgets as widgets
from IPython.display import display, clear_output
import matplotlib.pyplot as plt
# Mount Google Drive
drive.mount('/content/drive')
# Function to browse directories in Google Drive
def browse_subfolders(base_folder='/content/drive/My Drive'):
"""Returns a list of subfolder paths."""
folder_list = []
for dirname, _, _ in os.walk(base_folder):
folder_list.append(dirname)
return folder_list
# Folder navigation setup
folder_dropdown = widgets.Dropdown(
options=browse_subfolders(),
description='Select Folder:',
layout=widgets.Layout(width='100%')
)
display(folder_dropdown)
drive_folder = '/content/drive/My Drive'
# Callback to update drive folder path
def update_folder_path(change):
global drive_folder
drive_folder = change.new
print(f'Selected folder: {drive_folder}')
refresh_files_list()
folder_dropdown.observe(update_folder_path, names='value')
# Function to refresh video files list based on current folder selection
files_list = []
files_dropdown = widgets.Dropdown(
options=files_list,
description='Select Video:',
layout=widgets.Layout(width='100%')
)
display(files_dropdown)
def refresh_files_list():
global files_list
files_list = [os.path.join(drive_folder, f) for f in os.listdir(drive_folder) if f.lower().endswith(('.mp4', '.avi', '.mov', '.mkv'))]
files_dropdown.options = files_list or ["No video files found"]
# Image display and control widgets
image_widget = widgets.Output()
x_start_slider = widgets.IntSlider(value=0, min=0, max=640, step=1, description="Start X:")
y_start_slider = widgets.IntSlider(value=0, min=0, max=480, step=1, description="Start Y:")
x_end_slider = widgets.IntSlider(value=640, min=0, max=640, step=1, description="End X:")
y_end_slider = widgets.IntSlider(value=480, min=0, max=480, step=1, description="End Y:")
def update_sliders(width, height):
x_start_slider.max = x_end_slider.max = width
y_start_slider.max = y_end_slider.max = height
# Show video frame preview
def show_preview(*args):
clear_output(wait=True)
display(folder_dropdown, files_dropdown, preview_button, image_widget, x_start_slider, y_start_slider, x_end_slider, y_end_slider, crop_button)
selected_file = files_dropdown.value
if not selected_file or selected_file == "No video files found":
print("No video selected or found.")
return
cap = cv2.VideoCapture(selected_file)
ret, frame = cap.read()
cap.release()
if not ret:
print("Error reading video frame.")
return
height, width = frame.shape[:2]
update_sliders(width, height)
frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
fig, ax = plt.subplots(figsize=(6, 4)) # Set a smaller figure size
ax.imshow(frame_rgb)
ax.set_title('Select crop area')
crop_area = [
(x_start_slider.value, y_start_slider.value),
(x_end_slider.value, y_end_slider.value)
]
rect = plt.Rectangle(crop_area[0], crop_area[1][0] - crop_area[0][0], crop_area[1][1] - crop_area[0][1],
linewidth=1, edgecolor='r', facecolor='none')
ax.add_patch(rect)
plt.show()
# Button to trigger preview
preview_button = widgets.Button(description='Preview')
preview_button.on_click(show_preview)
# Display widgets
display(preview_button, image_widget, x_start_slider, y_start_slider, x_end_slider, y_end_slider)
# Define the function to crop videos
def crop_videos():
print("Starting crop...")
for input_file in files_list:
# Construct output file path with "_cropped" suffix
file_dir, file_name = os.path.split(input_file)
file_base, file_ext = os.path.splitext(file_name)
output_file = os.path.join(file_dir, f"{file_base}_cropped{file_ext}")
start_x, start_y, end_x, end_y = x_start_slider.value, y_start_slider.value, x_end_slider.value, y_end_slider.value
width = end_x - start_x
height = end_y - start_y
if width <= 0 or height <= 0:
print(f"Invalid crop dimensions for {input_file}")
continue
try:
ffmpeg.input(input_file).crop(x=start_x, y=start_y, width=width, height=height).output(
output_file, vcodec='libx264', acodec='aac', map='0:v', map='0:a').run()
print(f"Cropped and saved as: {output_file}")
except ffmpeg.Error as e:
print(f"FFmpeg error: {e}")
except Exception as e:
print(f"Unexpected error: {e}")
# Button to start cropping process
crop_button = widgets.Button(description='Start Cropping')
crop_button.on_click(lambda b: crop_videos())
display(crop_button)
Changes Made:
Audio Preservation: Ensured audio is copied using FFmpeg options – by including acodec='aac', map='0:v', map='0:a', we preserve both video and audio tracks.
Preview Size: Set a smaller size (figsize=(6, 4)) for the preview window to make it more suitable for viewing on mobile devices.
How to Use:
Run this script in a Google Colab notebook.
Mount your Google Drive and select the folder with your video files using the dropdown.
Select a video, adjust the crop area using sliders, and click "Preview" to see the crop area.
If satisfied, click "Start Cropping". The cropped videos will be saved with _cropped in the same directory as the input videos.
These modifications make the process more suitable for a streamlined experience on mobile, with audio intact in the outputs.
# Install necessary packages
!pip install opencv-python-headless ffmpeg-python -q
import os
import cv2
import ffmpeg
from google.colab import drive
import ipywidgets as widgets
from IPython.display import display, clear_output
import matplotlib.pyplot as plt
# Mount Google Drive
drive.mount('/content/drive')
# Function to browse directories in Google Drive
def browse_subfolders(base_folder='/content/drive/My Drive'):
"""Returns a list of subfolder paths."""
folder_list = []
for dirname, _, _ in os.walk(base_folder):
folder_list.append(dirname)
return folder_list
# Folder navigation setup
folder_dropdown = widgets.Dropdown(
options=browse_subfolders(),
description='Select Folder:',
layout=widgets.Layout(width='100%')
)
display(folder_dropdown)
drive_folder = '/content/drive/My Drive'
# Callback to update drive folder path
def update_folder_path(change):
global drive_folder
drive_folder = change.new
print(f'Selected folder: {drive_folder}')
refresh_files_list()
folder_dropdown.observe(update_folder_path, names='value')
# Function to refresh video files list based on current folder selection
files_list = []
files_dropdown = widgets.Dropdown(
options=files_list,
description='Select Video:',
layout=widgets.Layout(width='100%')
)
display(files_dropdown)
def refresh_files_list():
global files_list
files_list = [os.path.join(drive_folder, f) for f in os.listdir(drive_folder) if f.lower().endswith(('.mp4', '.avi', '.mov', '.mkv'))]
files_dropdown.options = files_list or ["No video files found"]
# Image display and control widgets
image_widget = widgets.Output()
x_start_slider = widgets.IntSlider(value=0, min=0, max=640, step=1, description="Start X:")
y_start_slider = widgets.IntSlider(value=0, min=0, max=480, step=1, description="Start Y:")
x_end_slider = widgets.IntSlider(value=640, min=0, max=640, step=1, description="End X:")
y_end_slider = widgets.IntSlider(value=480, min=0, max=480, step=1, description="End Y:")
def update_sliders(width, height):
x_start_slider.max = x_end_slider.max = width
y_start_slider.max = y_end_slider.max = height
# Show video frame preview
def show_preview(*args):
clear_output(wait=True)
display(folder_dropdown, files_dropdown, preview_button, image_widget, x_start_slider, y_start_slider, x_end_slider, y_end_slider, crop_button)
selected_file = files_dropdown.value
if not selected_file or selected_file == "No video files found":
print("No video selected or found.")
return
cap = cv2.VideoCapture(selected_file)
ret, frame = cap.read()
cap.release()
if not ret:
print("Error reading video frame.")
return
height, width = frame.shape[:2]
update_sliders(width, height)
frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
fig, ax = plt.subplots(figsize=(4, 3)) # Smaller size for mobile viewing
ax.imshow(frame_rgb)
ax.set_title('Select crop area')
crop_area = [
(x_start_slider.value, y_start_slider.value),
(x_end_slider.value, y_end_slider.value)
]
rect = plt.Rectangle(crop_area[0], crop_area[1][0] - crop_area[0][0], crop_area[1][1] - crop_area[0][1],
linewidth=1, edgecolor='r', facecolor='none')
ax.add_patch(rect)
plt.show()
# Button to trigger preview
preview_button = widgets.Button(description='Preview')
preview_button.on_click(show_preview)
# Display widgets
display(preview_button, image_widget, x_start_slider, y_start_slider, x_end_slider, y_end_slider)
# Define the function to crop videos
def crop_videos():
print("Starting crop...")
for input_file in files_list:
# Construct output file path with "_cropped" suffix
file_dir, file_name = os.path.split(input_file)
file_base, file_ext = os.path.splitext(file_name)
output_file = os.path.join(file_dir, f"{file_base}_cropped{file_ext}")
start_x, start_y, end_x, end_y = x_start_slider.value, y_start_slider.value, x_end_slider.value, y_end_slider.value
width = end_x - start_x
height = end_y - start_y
if width <= 0 or height <= 0:
print(f"Invalid crop dimensions for {input_file}")
continue
try:
# Copy both video and audio tracks
ffmpeg.input(input_file).crop(x=start_x, y=start_y, width=width, height=height).output(
output_file, vcodec='libx264', acodec='aac').run()
print(f"Cropped and saved as: {output_file}")
except ffmpeg.Error as e:
print(f"FFmpeg error: {e}")
except Exception as e:
print(f"Unexpected error: {e}")
# Button to start cropping process
crop_button = widgets.Button(description='Start Cropping')
crop_button.on_click(lambda b: crop_videos())
display(crop_button)
Key Adjustments:
Ensured there is no duplicate keyword by using acodec='aac' to copy the audio codec.
Set a smaller fixed preview size (figsize=(4, 3)) suitable for mobile viewing.
Simplified FFmpeg command to ensure audio is preserved without duplicated keywords.
Usage:
Run the script in a Google Colab notebook.
Mount your Google Drive and select the desired folder.
Choose a video file, adjust the crop area using sliders, and click "Preview".
Verify the crop selection visually and adjust sliders if necessary.
Click "Start Cropping" to save cropped videos in the same location with _cropped appended to filenames.
These improvements should provide a seamless experience, integrating video and audio with clear direction on visual adjustments. If further modifications are needed, feel free to ask!
# Install necessary packages
!pip install opencv-python-headless ffmpeg-python -q
import os
import cv2
import ffmpeg
from google.colab import drive
import ipywidgets as widgets
from IPython.display import display, clear_output
import matplotlib.pyplot as plt
# Mount Google Drive
drive.mount('/content/drive')
# Function to browse directories in Google Drive
def browse_subfolders(base_folder='/content/drive/My Drive'):
"""Returns a list of subfolder paths."""
folder_list = []
for dirname, _, _ in os.walk(base_folder):
folder_list.append(dirname)
return folder_list
# Folder navigation setup
folder_dropdown = widgets.Dropdown(
options=browse_subfolders(),
description='Select Folder:',
layout=widgets.Layout(width='100%')
)
display(folder_dropdown)
drive_folder = '/content/drive/My Drive'
# Callback to update drive folder path
def update_folder_path(change):
global drive_folder
drive_folder = change.new
print(f'Selected folder: {drive_folder}')
refresh_files_list()
folder_dropdown.observe(update_folder_path, names='value')
# Function to refresh video files list based on current folder selection
files_list = []
files_dropdown = widgets.Dropdown(
options=files_list,
description='Select Video:',
layout=widgets.Layout(width='100%')
)
display(files_dropdown)
def refresh_files_list():
global files_list
files_list = [os.path.join(drive_folder, f) for f in os.listdir(drive_folder) if f.lower().endswith(('.mp4', '.avi', '.mov', '.mkv'))]
files_dropdown.options = files_list or ["No video files found"]
# Image display and control widgets
image_widget = widgets.Output()
x_start_slider = widgets.IntSlider(value=0, min=0, max=640, step=1, description="Start X:")
y_start_slider = widgets.IntSlider(value=0, min=0, max=480, step=1, description="Start Y:")
x_end_slider = widgets.IntSlider(value=640, min=0, max=640, step=1, description="End X:")
y_end_slider = widgets.IntSlider(value=480, min=0, max=480, step=1, description="End Y:")
def update_sliders(width, height):
x_start_slider.max = x_end_slider.max = width
y_start_slider.max = y_end_slider.max = height
# Show video frame preview
def show_preview(*args):
clear_output(wait=True)
display(folder_dropdown, files_dropdown, preview_button, image_widget, x_start_slider, y_start_slider, x_end_slider, y_end_slider, crop_button)
selected_file = files_dropdown.value
if not selected_file or selected_file == "No video files found":
print("No video selected or found.")
return
cap = cv2.VideoCapture(selected_file)
ret, frame = cap.read()
cap.release()
if not ret:
print("Error reading video frame.")
return
height, width = frame.shape[:2]
update_sliders(width, height)
frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
fig, ax = plt.subplots(figsize=(4, 3)) # Smaller size for mobile viewing
ax.imshow(frame_rgb)
ax.set_title('Select crop area')
crop_area = [
(x_start_slider.value, y_start_slider.value),
(x_end_slider.value, y_end_slider.value)
]
rect = plt.Rectangle(crop_area[0], crop_area[1][0] - crop_area[0][0], crop_area[1][1] - crop_area[0][1],
linewidth=1, edgecolor='r', facecolor='none')
ax.add_patch(rect)
plt.show()
# Button to trigger preview
preview_button = widgets.Button(description='Preview')
preview_button.on_click(show_preview)
# Display widgets
display(preview_button, image_widget, x_start_slider, y_start_slider, x_end_slider, y_end_slider)
# Define the function to crop videos
def crop_videos():
print("Starting crop...")
for input_file in files_list:
# Construct output file path with "_cropped" suffix
file_dir, file_name = os.path.split(input_file)
file_base, file_ext = os.path.splitext(file_name)
output_file = os.path.join(file_dir, f"{file_base}_cropped{file_ext}")
start_x, start_y, end_x, end_y = x_start_slider.value, y_start_slider.value, x_end_slider.value, y_end_slider.value
width = end_x - start_x
height = end_y - start_y
if width <= 0 or height <= 0:
print(f"Invalid crop dimensions for {input_file}")
continue
try:
# Use FFmpeg filters and explicitly copy audio
streams = ffmpeg.input(input_file)
video_stream = streams.video.filter('crop', x=start_x, y=start_y, width=width, height=height)
ffmpeg.output(video_stream, streams.audio, output_file, vcodec='libx264', acodec='aac', strict='experimental').run()
print(f"Cropped and saved as: {output_file}")
except ffmpeg.Error as e:
print(f"FFmpeg error: {e.stderr.decode()}")
except Exception as e:
print(f"Unexpected error: {e}")
# Button to start cropping process
crop_button = widgets.Button(description='Start Cropping')
crop_button.on_click(lambda b: crop_videos())
display(crop_button)
Key Adjustments:
Audio Handling: Explicitly copying both video and audio using ffmpeg.output(video_stream, streams.audio, ...).
FFmpeg Filter: Applied the crop as a filter while ensuring the audio is linked and processed correctly.
Preview Size: Consistent small preview for mobile viewing (figsize=(4, 3)).
With these changes, the script will preserve audio while cropping, ensuring the resulting video retains its sound. Again, make sure you're running each cell in order after the Google Drive is mounted correctly.
# Install necessary packages
!pip install opencv-python-headless ffmpeg-python -q
import os
import cv2
import ffmpeg
from google.colab import drive
import ipywidgets as widgets
from IPython.display import display, clear_output
import matplotlib.pyplot as plt
# Mount Google Drive
drive.mount('/content/drive')
# Function to browse directories in Google Drive
def browse_subfolders(base_folder='/content/drive/My Drive'):
"""Returns a list of subfolder paths."""
folder_list = []
for dirname, _, _ in os.walk(base_folder):
folder_list.append(dirname)
return folder_list
# Folder navigation setup
folder_dropdown = widgets.Dropdown(
options=browse_subfolders(),
description='Select Folder:',
layout=widgets.Layout(width='100%')
)
display(folder_dropdown)
drive_folder = '/content/drive/My Drive'
# Callback to update drive folder path
def update_folder_path(change):
global drive_folder
drive_folder = change.new
print(f'Selected folder: {drive_folder}')
refresh_files_list()
folder_dropdown.observe(update_folder_path, names='value')
# Function to refresh video files list based on current folder selection
files_list = []
files_dropdown = widgets.Dropdown(
options=files_list,
description='Select Video:',
layout=widgets.Layout(width='100%')
)
display(files_dropdown)
def refresh_files_list():
global files_list
files_list = [os.path.join(drive_folder, f) for f in os.listdir(drive_folder) if f.lower().endswith(('.mp4', '.avi', '.mov', '.mkv'))]
files_dropdown.options = files_list or ["No video files found"]
# Image display and control widgets
image_widget = widgets.Output()
x_start_slider = widgets.IntSlider(value=0, min=0, max=640, step=1, description="Start X:")
y_start_slider = widgets.IntSlider(value=0, min=0, max=480, step=1, description="Start Y:")
x_end_slider = widgets.IntSlider(value=640, min=0, max=640, step=1, description="End X:")
y_end_slider = widgets.IntSlider(value=480, min=0, max=480, step=1, description="End Y:")
def update_sliders(width, height):
x_start_slider.max = x_end_slider.max = width
y_start_slider.max = y_end_slider.max = height
# Show video frame preview
def show_preview(*args):
clear_output(wait=True)
display(folder_dropdown, files_dropdown, preview_button, image_widget, x_start_slider, y_start_slider, x_end_slider, y_end_slider, crop_button)
selected_file = files_dropdown.value
if not selected_file or selected_file == "No video files found":
print("No video selected or found.")
return
cap = cv2.VideoCapture(selected_file)
ret, frame = cap.read()
cap.release()
if not ret:
print("Error reading video frame.")
return
height, width = frame.shape[:2]
update_sliders(width, height)
frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
fig, ax = plt.subplots(figsize=(4, 3)) # Smaller size for mobile viewing
ax.imshow(frame_rgb)
ax.set_title('Select crop area')
crop_area = [
(x_start_slider.value, y_start_slider.value),
(x_end_slider.value, y_end_slider.value)
]
rect = plt.Rectangle(crop_area[0], crop_area[1][0] - crop_area[0][0], crop_area[1][1] - crop_area[0][1],
linewidth=1, edgecolor='r', facecolor='none')
ax.add_patch(rect)
plt.show()
# Button to trigger preview
preview_button = widgets.Button(description='Preview')
preview_button.on_click(show_preview)
# Display widgets
display(preview_button, image_widget, x_start_slider, y_start_slider, x_end_slider, y_end_slider)
# Define the function to crop videos
def crop_videos():
print("Starting crop...")
for input_file in files_list:
# Construct output file path with "_cropped" suffix
file_dir, file_name = os.path.split(input_file)
file_base, file_ext = os.path.splitext(file_name)
output_file = os.path.join(file_dir, f"{file_base}_cropped{file_ext}")
start_x, start_y, end_x, end_y = x_start_slider.value, y_start_slider.value, x_end_slider.value, y_end_slider.value
width = end_x - start_x
height = end_y - start_y
if width <= 0 or height <= 0:
print(f"Invalid crop dimensions for {input_file}")
continue
try:
# Use FFmpeg filters and explicitly copy audio
streams = ffmpeg.input(input_file)
video_stream = streams.video.filter('crop', x=start_x, y=start_y, width=width, height=height)
ffmpeg.output(video_stream, streams.audio, output_file, vcodec='libx264', acodec='aac', strict='experimental').run()
print(f"Cropped and saved as: {output_file}")
except ffmpeg.Error as e:
error_message = e.stderr.decode('utf8') if e.stderr else 'No error details available'
print(f"FFmpeg error: {error_message}")
except Exception as e:
print(f"Unexpected error: {str(e)}")
# Button to start cropping process
crop_button = widgets.Button(description='Start Cropping')
crop_button.on_click(lambda b: crop_videos())
display(crop_button)
Key Adjustments:
Error Handling: Improved handling by checking for stderr presence and using it safely if available to avoid attribute errors.
Consistent ffmpeg Application: Ensures that both video and audio streams are processed correctly through ffmpeg with appropriate filtering and output options.
This should correctly crop the video and preserve both video and audio, including improved error handling to better inform you of any issues encountered during processing. Make sure to review any ffmpeg errors that may appear to verify they're specific to the environment or inputs.
# Install necessary packages
!pip install opencv-python-headless ffmpeg-python -q
import os
import cv2
import ffmpeg
from google.colab import drive
import ipywidgets as widgets
from IPython.display import display, clear_output
import matplotlib.pyplot as plt
# Mount Google Drive
drive.mount('/content/drive')
# Function to browse directories in Google Drive
def browse_subfolders(base_folder='/content/drive/My Drive'):
"""Returns a list of subfolder paths."""
folder_list = []
for dirname, _, _ in os.walk(base_folder):
folder_list.append(dirname)
return folder_list
# Folder navigation setup
folder_dropdown = widgets.Dropdown(
options=browse_subfolders(),
description='Select Folder:',
layout=widgets.Layout(width='100%')
)
display(folder_dropdown)
drive_folder = '/content/drive/My Drive'
# Callback to update drive folder path
def update_folder_path(change):
global drive_folder
drive_folder = change.new
print(f'Selected folder: {drive_folder}')
refresh_files_list()
folder_dropdown.observe(update_folder_path, names='value')
# Function to refresh video files list based on current folder selection
files_list = []
files_dropdown = widgets.Dropdown(
options=files_list,
description='Select Video:',
layout=widgets.Layout(width='100%')
)
display(files_dropdown)
def refresh_files_list():
global files_list
files_list = [os.path.join(drive_folder, f) for f in os.listdir(drive_folder) if f.lower().endswith(('.mp4', '.avi', '.mov', '.mkv'))]
files_dropdown.options = files_list or ["No video files found"]
# Image display and control widgets
image_widget = widgets.Output()
x_start_slider = widgets.IntSlider(value=0, min=0, max=640, step=1, description="Start X:")
y_start_slider = widgets.IntSlider(value=0, min=0, max=480, step=1, description="Start Y:")
x_end_slider = widgets.IntSlider(value=640, min=0, max=640, step=1, description="End X:")
y_end_slider = widgets.IntSlider(value=480, min=0, max=480, step=1, description="End Y:")
def update_sliders(width, height):
x_start_slider.max = x_end_slider.max = width
y_start_slider.max = y_end_slider.max = height
# Show video frame preview
def show_preview(*args):
clear_output(wait=True)
display(folder_dropdown, files_dropdown, preview_button, image_widget, x_start_slider, y_start_slider, x_end_slider, y_end_slider, crop_button)
selected_file = files_dropdown.value
if not selected_file or selected_file == "No video files found":
print("No video selected or found.")
return
cap = cv2.VideoCapture(selected_file)
ret, frame = cap.read()
cap.release()
if not ret:
print("Error reading video frame.")
return
height, width = frame.shape[:2]
update_sliders(width, height)
frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
fig, ax = plt.subplots(figsize=(4, 3)) # Smaller size for mobile viewing
ax.imshow(frame_rgb)
ax.set_title('Select crop area')
crop_area = [
(x_start_slider.value, y_start_slider.value),
(x_end_slider.value, y_end_slider.value)
]
rect = plt.Rectangle(crop_area[0], crop_area[1][0] - crop_area[0][0], crop_area[1][1] - crop_area[0][1],
linewidth=1, edgecolor='r', facecolor='none')
ax.add_patch(rect)
plt.show()
# Button to trigger preview
preview_button = widgets.Button(description='Preview')
preview_button.on_click(show_preview)
# Display widgets
display(preview_button, image_widget, x_start_slider, y_start_slider, x_end_slider, y_end_slider)
# Define the function to crop videos
def crop_videos():
print("Starting crop...")
for input_file in files_list:
# Construct output file path with "_cropped" suffix
file_dir, file_name = os.path.split(input_file)
file_base, file_ext = os.path.splitext(file_name)
output_file = os.path.join(file_dir, f"{file_base}_cropped{file_ext}")
start_x, start_y, end_x, end_y = x_start_slider.value, y_start_slider.value, x_end_slider.value, y_end_slider.value
width = end_x - start_x
height = end_y - start_y
if width <= 0 or height <= 0:
print(f"Invalid crop dimensions for {input_file}")
continue
try:
# Re-encode both video and audio
streams = ffmpeg.input(input_file)
video_stream = streams.video.filter('crop', x=start_x, y=start_y, width=width, height=height)
ffmpeg.output(video_stream, streams.audio, output_file, vcodec='libx264', acodec='aac', audio_bitrate='192k').run()
print(f"Cropped and saved as: {output_file}")
except ffmpeg.Error as e:
error_message = e.stderr.decode('utf8') if e.stderr else 'No error details available'
print(f"FFmpeg error: {error_message}")
except Exception as e:
print(f"Unexpected error: {str(e)}")
# Button to start cropping process
crop_button = widgets.Button(description='Start Cropping')
crop_button.on_click(lambda b: crop_videos())
display(crop_button)
Changes and Considerations:
Re-encoded Audio: The script explicitly specifies acodec='aac' and sets an audio_bitrate to ensure the audio is properly encoded.
Streamlined Error Handling: Safeguards are in place to decode and display errors meaningfully.
Preview Size: Consistent smaller frame size (figsize=(4, 3)) for easier viewing on mobile devices.
This should rectify the issue of missing audio in the output while ensuring re-encoded audio is included. Make sure to test with compatible and diverse input formats to verify comprehensive functionality across different files.
# Install necessary packages
!pip install opencv-python-headless ffmpeg-python -q
import os
import cv2
import ffmpeg
from google.colab import drive
import ipywidgets as widgets
from IPython.display import display, clear_output
import matplotlib.pyplot as plt
# Mount Google Drive
drive.mount('/content/drive')
# Function to browse directories in Google Drive
def browse_subfolders(base_folder='/content/drive/My Drive'):
"""Returns a list of subfolder paths."""
folder_list = []
for dirname, _, _ in os.walk(base_folder):
folder_list.append(dirname)
return folder_list
# Folder navigation setup
folder_dropdown = widgets.Dropdown(
options=browse_subfolders(),
description='Select Folder:',
layout=widgets.Layout(width='100%')
)
display(folder_dropdown)
drive_folder = '/content/drive/My Drive'
# Callback to update drive folder path
def update_folder_path(change):
global drive_folder
drive_folder = change.new
print(f'Selected folder: {drive_folder}')
refresh_files_list()
folder_dropdown.observe(update_folder_path, names='value')
# Function to refresh video files list based on current folder selection
files_list = []
files_dropdown = widgets.Dropdown(
options=files_list,
description='Select Video:',
layout=widgets.Layout(width='100%')
)
display(files_dropdown)
def refresh_files_list():
global files_list
files_list = [os.path.join(drive_folder, f) for f in os.listdir(drive_folder) if f.lower().endswith(('.mp4', '.avi', '.mov', '.mkv'))]
files_dropdown.options = files_list or ["No video files found"]
# Image display and control widgets
image_widget = widgets.Output()
x_start_slider = widgets.IntSlider(value=0, min=0, max=640, step=1, description="Start X:")
y_start_slider = widgets.IntSlider(value=0, min=0, max=480, step=1, description="Start Y:")
x_end_slider = widgets.IntSlider(value=640, min=0, max=640, step=1, description="End X:")
y_end_slider = widgets.IntSlider(value=480, min=0, max=480, step=1, description="End Y:")
def update_sliders(width, height):
x_start_slider.max = x_end_slider.max = width
y_start_slider.max = y_end_slider.max = height
# Show video frame preview
def show_preview(*args):
clear_output(wait=True)
display(folder_dropdown, files_dropdown, preview_button, image_widget, x_start_slider, y_start_slider, x_end_slider, y_end_slider, crop_button)
selected_file = files_dropdown.value
if not selected_file or selected_file == "No video files found":
print("No video selected or found.")
return
cap = cv2.VideoCapture(selected_file)
ret, frame = cap.read()
cap.release()
if not ret:
print("Error reading video frame.")
return
height, width = frame.shape[:2]
update_sliders(width, height)
frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
fig, ax = plt.subplots(figsize=(4, 3)) # Smaller size for mobile viewing
ax.imshow(frame_rgb)
ax.set_title('Select crop area')
crop_area = [
(x_start_slider.value, y_start_slider.value),
(x_end_slider.value, y_end_slider.value)
]
rect = plt.Rectangle(crop_area[0], crop_area[1][0] - crop_area[0][0], crop_area[1][1] - crop_area[0][1],
linewidth=1, edgecolor='r', facecolor='none')
ax.add_patch(rect)
plt.show()
# Button to trigger preview
preview_button = widgets.Button(description='Preview')
preview_button.on_click(show_preview)
# Display widgets
display(preview_button, image_widget, x_start_slider, y_start_slider, x_end_slider, y_end_slider)
# Define the function to crop videos
def crop_videos():
print("Starting crop...")
for input_file in files_list:
# Construct output file path with "_cropped" suffix
file_dir, file_name = os.path.split(input_file)
file_base, file_ext = os.path.splitext(file_name)
output_file = os.path.join(file_dir, f"{file_base}_cropped{file_ext}")
start_x, start_y, end_x, end_y = x_start_slider.value, y_start_slider.value, x_end_slider.value, y_end_slider.value
width = end_x - start_x
height = end_y - start_y
if width <= 0 or height <= 0:
print(f"Invalid crop dimensions for {input_file}")
continue
try:
# Use FFmpeg with verbose logging for detailed output
streams = ffmpeg.input(input_file)
video_stream = streams.video.filter('crop', x=start_x, y=start_y, width=width, height=height)
(
ffmpeg
.output(video_stream, streams.audio, output_file, vcodec='libx264', acodec='aac', audio_bitrate='192k')
.run(overwrite_output=True, capture_stdout=True, capture_stderr=True)
)
print(f"Cropped and saved as: {output_file}")
except ffmpeg.Error as e:
print("File conversion failed")
print(e.stdout.decode('utf8'))
print(e.stderr.decode('utf8'))
except Exception as e:
print(f"Unexpected error: {str(e)}")
# Button to start cropping process
crop_button = widgets.Button(description='Start Cropping')
crop_button.on_click(lambda b: crop_videos())
display(crop_button)
Key Adjustments:
FFmpeg Verbosity: Outputs both stdout and stderr from FFmpeg to capture any detailed messages that may help diagnose the problem.
Error Capture: Displays detailed error messages directly for enhanced troubleshooting.
Overwrite Protection: Added overwrite_output=True to handle existing output files seamlessly.
By reviewing the captured stdout and stderr after attempting to run FFmpeg, you'll gain clarity on the underlying issues, if any remain.
# Install necessary packages
!pip install opencv-python-headless ffmpeg-python -q
import os
import cv2
import ffmpeg
from google.colab import drive
import ipywidgets as widgets
from IPython.display import display, clear_output
import matplotlib.pyplot as plt
# Mount Google Drive
drive.mount('/content/drive')
# Function to browse directories in Google Drive
def browse_subfolders(base_folder='/content/drive/My Drive'):
"""Returns a list of subfolder paths."""
folder_list = []
for dirname, _, _ in os.walk(base_folder):
folder_list.append(dirname)
return folder_list
# Folder navigation setup
folder_dropdown = widgets.Dropdown(
options=browse_subfolders(),
description='Select Folder:',
layout=widgets.Layout(width='100%')
)
display(folder_dropdown)
drive_folder = '/content/drive/My Drive'
# Callback to update drive folder path
def update_folder_path(change):
global drive_folder
drive_folder = change.new
print(f'Selected folder: {drive_folder}')
refresh_files_list()
folder_dropdown.observe(update_folder_path, names='value')
# Function to refresh video files list based on current folder selection
files_list = []
files_dropdown = widgets.Dropdown(
options=files_list,
description='Select Video:',
layout=widgets.Layout(width='100%')
)
display(files_dropdown)
def refresh_files_list():
global files_list
files_list = [os.path.join(drive_folder, f) for f in os.listdir(drive_folder) if f.lower().endswith(('.mp4', '.avi', '.mov', '.mkv'))]
files_dropdown.options = files_list or ["No video files found"]
# Image display and control widgets
image_widget = widgets.Output()
x_start_slider = widgets.IntSlider(value=0, min=0, max=640, step=1, description="Start X:")
y_start_slider = widgets.IntSlider(value=0, min=0, max=480, step=1, description="Start Y:")
x_end_slider = widgets.IntSlider(value=640, min=0, max=640, step=1, description="End X:")
y_end_slider = widgets.IntSlider(value=480, min=0, max=480, step=1, description="End Y:")
def update_sliders(width, height):
x_start_slider.max = x_end_slider.max = width
y_start_slider.max = y_end_slider.max = height
# Show video frame preview
def show_preview(*args):
clear_output(wait=True)
display(folder_dropdown, files_dropdown, preview_button, image_widget, x_start_slider, y_start_slider, x_end_slider, y_end_slider, crop_button)
selected_file = files_dropdown.value
if not selected_file or selected_file == "No video files found":
print("No video selected or found.")
return
cap = cv2.VideoCapture(selected_file)
ret, frame = cap.read()
cap.release()
if not ret:
print("Error reading video frame.")
return
height, width = frame.shape[:2]
update_sliders(width, height)
frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
fig, ax = plt.subplots(figsize=(4, 3)) # Smaller size for mobile viewing
ax.imshow(frame_rgb)
ax.set_title('Select crop area')
crop_area = [
(x_start_slider.value, y_start_slider.value),
(x_end_slider.value, y_end_slider.value)
]
rect = plt.Rectangle(crop_area[0], crop_area[1][0] - crop_area[0][0], crop_area[1][1] - crop_area[0][1],
linewidth=1, edgecolor='r', facecolor='none')
ax.add_patch(rect)
plt.show()
# Button to trigger preview
preview_button = widgets.Button(description='Preview')
preview_button.on_click(show_preview)
# Display widgets
display(preview_button, image_widget, x_start_slider, y_start_slider, x_end_slider, y_end_slider)
# Define the function to crop videos
def crop_videos():
print("Starting crop...")
for input_file in files_list:
# Construct output file path with "_cropped" suffix
file_dir, file_name = os.path.split(input_file)
file_base, file_ext = os.path.splitext(file_name)
output_file = os.path.join(file_dir, f"{file_base}_cropped{file_ext}")
start_x, start_y = x_start_slider.value, y_start_slider.value
width = x_end_slider.value - x_start_slider.value
height = y_end_slider.value - y_start_slider.value
if width <= 0 or height <= 0:
print(f"Invalid crop dimensions for {input_file}")
continue
try:
# Use FFmpeg with verbose logging for detailed output
streams = ffmpeg.input(input_file)
video_stream = streams.video.filter('crop', x=start_x, y=start_y, out_w=width, out_h=height)
(
ffmpeg
.output(video_stream, streams.audio, output_file, vcodec='libx264', acodec='aac', audio_bitrate='192k')
.run(overwrite_output=True, capture_stdout=True, capture_stderr=True)
)
print(f"Cropped and saved as: {output_file}")
except ffmpeg.Error as e:
print("File conversion failed")
print(e.stdout.decode('utf8'))
print(e.stderr.decode('utf8'))
except Exception as e:
print(f"Unexpected error: {str(e)}")
# Button to start cropping process
crop_button = widgets.Button(description='Start Cropping')
crop_button.on_click(lambda b: crop_videos())
display(crop_button)
Key Corrections:
FFmpeg Filter Arguments: Correctly specifying the crop filter arguments as out_w (output width) and out_h (output height) rather than width and height resolves the issue.
Error Reporting: Improved capturing and reporting of both standard output and error output for diagnostic purposes.
Variable Calculations: Ensures width and height are computed correctly based on slider positions, avoiding negative or zero dimensions.
Try running this code and observe the logs for any further insights into potential issues.
# Install necessary packages
!pip install opencv-python-headless ffmpeg-python -q
import os
import cv2
import ffmpeg
from google.colab import drive
import ipywidgets as widgets
from IPython.display import display, clear_output
import matplotlib.pyplot as plt
# Mount Google Drive
drive.mount('/content/drive')
# Function to browse directories in Google Drive
def browse_subfolders(base_folder='/content/drive/My Drive'):
"""Returns a list of subfolder paths."""
folder_list = []
for dirname, _, _ in os.walk(base_folder):
folder_list.append(dirname)
return folder_list
# Folder navigation setup
folder_dropdown = widgets.Dropdown(
options=browse_subfolders(),
description='Select Folder:',
layout=widgets.Layout(width='100%')
)
display(folder_dropdown)
drive_folder = '/content/drive/My Drive'
# Callback to update drive folder path
def update_folder_path(change):
global drive_folder
drive_folder = change.new
print(f'Selected folder: {drive_folder}')
refresh_files_list()
folder_dropdown.observe(update_folder_path, names='value')
# Function to refresh video files list based on current folder selection
files_list = []
files_dropdown = widgets.Dropdown(
options=files_list,
description='Select Video:',
layout=widgets.Layout(width='100%')
)
display(files_dropdown)
def refresh_files_list():
global files_list
files_list = [os.path.join(drive_folder, f) for f in os.listdir(drive_folder) if f.lower().endswith(('.mp4', '.avi', '.mov', '.mkv'))]
files_dropdown.options = files_list or ["No video files found"]
# Image display and control widgets
image_widget = widgets.Output()
x_start_slider = widgets.IntSlider(value=0, min=0, max=640, step=1, description="Start X:")
y_start_slider = widgets.IntSlider(value=0, min=0, max=480, step=1, description="Start Y:")
x_end_slider = widgets.IntSlider(value=640, min=0, max=640, step=1, description="End X:")
y_end_slider = widgets.IntSlider(value=480, min=0, max=480, step=1, description="End Y:")
def update_sliders(width, height):
x_start_slider.max = x_end_slider.max = width
y_start_slider.max = y_end_slider.max = height
x_end_slider.value = width
y_end_slider.value = height
# Show video frame preview
def show_preview(*args):
clear_output(wait=True)
display(folder_dropdown, files_dropdown, preview_button, image_widget, x_start_slider, y_start_slider, x_end_slider, y_end_slider, crop_button)
selected_file = files_dropdown.value
if not selected_file or selected_file == "No video files found":
print("No video selected or found.")
return
cap = cv2.VideoCapture(selected_file)
ret, frame = cap.read()
cap.release()
if not ret:
print("Error reading video frame.")
return
height, width = frame.shape[:2]
update_sliders(width, height)
frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
fig, ax = plt.subplots(figsize=(4, 3)) # Smaller size for mobile viewing
ax.imshow(frame_rgb)
ax.set_title('Select crop area')
crop_area = [
(x_start_slider.value, y_start_slider.value),
(x_end_slider.value, y_end_slider.value)
]
rect = plt.Rectangle(crop_area[0], crop_area[1][0] - crop_area[0][0], crop_area[1][1] - crop_area[0][1],
linewidth=1, edgecolor='r', facecolor='none')
ax.add_patch(rect)
plt.show()
# Button to trigger preview
preview_button = widgets.Button(description='Preview')
preview_button.on_click(show_preview)
# Display widgets
display(preview_button, image_widget, x_start_slider, y_start_slider, x_end_slider, y_end_slider)
# Define the function to crop videos
def crop_videos():
print("Starting crop...")
for input_file in files_list:
# Construct output file path with "_cropped" suffix
file_dir, file_name = os.path.split(input_file)
file_base, file_ext = os.path.splitext(file_name)
output_file = os.path.join(file_dir, f"{file_base}_cropped{file_ext}")
start_x, start_y = x_start_slider.value, y_start_slider.value
end_x, end_y = x_end_slider.value, y_end_slider.value
width = end_x - start_x
height = end_y - start_y
if width <= 0 or height <= 0:
print(f"Invalid crop dimensions for {input_file}")
continue
try:
# Use FFmpeg with verbose logging for detailed output
streams = ffmpeg.input(input_file)
video_stream = streams.video.filter('crop', x=start_x, y=start_y, out_w=width, out_h=height)
(
ffmpeg
.output(video_stream, streams.audio, output_file, vcodec='libx264', acodec='aac', audio_bitrate='192k')
.run(overwrite_output=True, capture_stdout=True, capture_stderr=True)
)
print(f"Cropped and saved as: {output_file}")
except ffmpeg.Error as e:
print("File conversion failed")
print(e.stdout.decode('utf8'))
print(e.stderr.decode('utf8'))
except Exception as e:
print(f"Unexpected error: {str(e)}")
# Button to start cropping process
crop_button = widgets.Button(description='Start Cropping')
crop_button.on_click(lambda b: crop_videos())
display(crop_button)
Changes Made:
Flexible Sliders: Set x_end_slider.value and y_end_slider.value to match the video dimensions by default, ensuring no cropping occurs if sliders start at their max values.
Crop Logic: Calculate width and height dynamically to support no cropping enforcement when sliders remain unadjusted.
With this setup, if sliders are positioned at zero, it means no cropping will happen from that side, effectively ensuring the frame remains as intended when full size is required.
# Install necessary packages
!pip install opencv-python-headless ffmpeg-python -q
import os
import cv2
import ffmpeg
from google.colab import drive
import ipywidgets as widgets
from IPython.display import display, clear_output
import matplotlib.pyplot as plt
# Mount Google Drive
drive.mount('/content/drive')
# Function to browse directories in Google Drive
def browse_subfolders(base_folder='/content/drive/My Drive'):
"""Returns a list of subfolder paths."""
folder_list = []
for dirname, _, _ in os.walk(base_folder):
folder_list.append(dirname)
return folder_list
# Folder navigation setup
folder_dropdown = widgets.Dropdown(
options=browse_subfolders(),
description='Select Folder:',
layout=widgets.Layout(width='100%')
)
display(folder_dropdown)
drive_folder = '/content/drive/My Drive'
# Callback to update drive folder path
def update_folder_path(change):
global drive_folder
drive_folder = change.new
print(f'Selected folder: {drive_folder}')
refresh_files_list()
folder_dropdown.observe(update_folder_path, names='value')
# Function to refresh video files list based on current folder selection
files_list = []
files_dropdown = widgets.Dropdown(
options=files_list,
description='Select Video:',
layout=widgets.Layout(width='100%')
)
display(files_dropdown)
def refresh_files_list():
global files_list
files_list = [os.path.join(drive_folder, f) for f in os.listdir(drive_folder) if f.lower().endswith(('.mp4', '.avi', '.mov', '.mkv'))]
files_dropdown.options = files_list or ["No video files found"]
# Image display and control widgets
image_widget = widgets.Output()
x_start_slider = widgets.IntSlider(value=0, min=0, max=640, step=1, description="Start X:")
y_start_slider = widgets.IntSlider(value=0, min=0, max=480, step=1, description="Start Y:")
x_end_slider = widgets.IntSlider(value=640, min=0, max=640, step=1, description="End X:")
y_end_slider = widgets.IntSlider(value=480, min=0, max=480, step=1, description="End Y:")
def update_sliders(width, height):
x_start_slider.max = x_end_slider.max = width
y_start_slider.max = y_end_slider.max = height
x_end_slider.value = width
y_end_slider.value = height
# Show video frame preview
def show_preview(*args):
clear_output(wait=True)
display(folder_dropdown, files_dropdown, preview_button, image_widget, x_start_slider, y_start_slider, x_end_slider, y_end_slider, crop_button)
selected_file = files_dropdown.value
if not selected_file or selected_file == "No video files found":
print("No video selected or found.")
return
cap = cv2.VideoCapture(selected_file)
ret, frame = cap.read()
cap.release()
if not ret:
print("Error reading video frame.")
return
height, width = frame.shape[:2]
update_sliders(width, height)
frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
fig, ax = plt.subplots(figsize=(4, 3)) # Smaller size for mobile viewing
ax.imshow(frame_rgb)
ax.set_title('Select crop area')
crop_area = [
(x_start_slider.value, y_start_slider.value),
(x_end_slider.value, y_end_slider.value)
]
rect = plt.Rectangle(crop_area[0], crop_area[1][0] - crop_area[0][0], crop_area[1][1] - crop_area[0][1],
linewidth=1, edgecolor='r', facecolor='none')
ax.add_patch(rect)
plt.show()
# Button to trigger preview
preview_button = widgets.Button(description='Preview')
preview_button.on_click(show_preview)
# Display widgets
display(preview_button, image_widget, x_start_slider, y_start_slider, x_end_slider, y_end_slider)
# Define the function to crop videos
def crop_videos():
print("Starting crop...")
for input_file in files_list:
# Construct output file path with "_cropped" suffix
file_dir, file_name = os.path.split(input_file)
file_base, file_ext = os.path.splitext(file_name)
output_file = os.path.join(file_dir, f"{file_base}_cropped{file_ext}")
start_x, start_y = x_start_slider.value, y_start_slider.value
end_x, end_y = x_end_slider.value, y_end_slider.value
# Calculate width and height, ensuring they are valid within video dimensions
width = max(1, end_x - start_x)
height = max(1, end_y - start_y)
# Ensure that cropped dimensions respect available video dimensions
if end_x > x_start_slider.max or end_y > y_start_slider.max:
print(f"Crop dimensions exceed video size for {input_file}")
continue
try:
# Use FFmpeg with verbose logging for detailed output
streams = ffmpeg.input(input_file)
video_stream = streams.video.filter('crop', x=start_x, y=start_y, out_w=width, out_h=height)
(
ffmpeg
.output(video_stream, streams.audio, output_file, vcodec='libx264', acodec='aac', audio_bitrate='192k')
.run(overwrite_output=True, capture_stdout=True, capture_stderr=True)
)
print(f"Cropped and saved as: {output_file}")
except ffmpeg.Error as e:
print("File conversion failed")
print(e.stdout.decode('utf8'))
print(e.stderr.decode('utf8'))
except Exception as e:
print(f"Unexpected error: {str(e)}")
# Button to start cropping process
crop_button = widgets.Button(description='Start Cropping')
crop_button.on_click(lambda b: crop_videos())
display(crop_button)
Key Adjustments:
Validation: Added checks to ensure that the crop dimensions do not exceed the video dimensions and are also positive.
Width & Height Calculation: Use max(1, ...) to ensure that width and height are always positive, preventing FFmpeg from failing due to invalid dimensions.
With these modifications, the script should handle situations where sliders are at their extremes properly, respecting the video boundaries. This should prevent invalid crop dimensions, ensuring the operation proceeds as expected.
# Install necessary packages
!pip install opencv-python-headless ffmpeg-python -q
import os
import cv2
import ffmpeg
from google.colab import drive
import ipywidgets as widgets
from IPython.display import display, clear_output
import matplotlib.pyplot as plt
# Mount Google Drive
drive.mount('/content/drive')
# Function to browse directories in Google Drive
def browse_subfolders(base_folder='/content/drive/My Drive'):
"""Returns a list of subfolder paths."""
folder_list = []
for dirname, _, _ in os.walk(base_folder):
folder_list.append(dirname)
return folder_list
# Folder navigation setup
folder_dropdown = widgets.Dropdown(
options=browse_subfolders(),
description='Select Folder:',
layout=widgets.Layout(width='100%')
)
display(folder_dropdown)
drive_folder = '/content/drive/My Drive'
# Callback to update drive folder path
def update_folder_path(change):
global drive_folder
drive_folder = change.new
print(f'Selected folder: {drive_folder}')
refresh_files_list()
folder_dropdown.observe(update_folder_path, names='value')
# Function to refresh video files list based on current folder selection
files_list = []
files_dropdown = widgets.Dropdown(
options=files_list,
description='Select Video:',
layout=widgets.Layout(width='100%')
)
display(files_dropdown)
def refresh_files_list():
global files_list
files_list = [os.path.join(drive_folder, f) for f in os.listdir(drive_folder) if f.lower().endswith(('.mp4', '.avi', '.mov', '.mkv'))]
files_dropdown.options = files_list or ["No video files found"]
# Image display and control widgets
image_widget = widgets.Output()
x_start_slider = widgets.IntSlider(value=0, min=0, layout=widgets.Layout(width='50%'), description="Start X:")
y_start_slider = widgets.IntSlider(value=0, min=0, layout=widgets.Layout(width='50%'), description="Start Y:")
x_end_slider = widgets.IntSlider(value=640, min=0, layout=widgets.Layout(width='50%'), description="End X:")
y_end_slider = widgets.IntSlider(value=480, min=0, layout=widgets.Layout(width='50%'), description="End Y:")
def update_sliders(width, height):
x_start_slider.max = width
x_end_slider.max = width
y_start_slider.max = height
y_end_slider.max = height
x_end_slider.value = width
y_end_slider.value = height
# Show video frame preview
def show_preview(*args):
clear_output(wait=True)
display(folder_dropdown, files_dropdown, preview_button, image_widget, x_start_slider, y_start_slider, x_end_slider, y_end_slider, crop_button)
selected_file = files_dropdown.value
if not selected_file or selected_file == "No video files found":
print("No video selected or found.")
return
cap = cv2.VideoCapture(selected_file)
ret, frame = cap.read()
cap.release()
if not ret:
print("Error reading video frame.")
return
height, width = frame.shape[:2]
update_sliders(width, height)
frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
fig, ax = plt.subplots(figsize=(4, 3)) # Smaller size for mobile viewing
ax.imshow(frame_rgb)
ax.set_title('Select crop area')
crop_area = [
(x_start_slider.value, y_start_slider.value),
(x_end_slider.value, y_end_slider.value)
]
rect = plt.Rectangle(crop_area[0], crop_area[1][0] - crop_area[0][0], crop_area[1][1] - crop_area[0][1],
linewidth=1, edgecolor='r', facecolor='none')
ax.add_patch(rect)
plt.show()
# Button to trigger preview
preview_button = widgets.Button(description='Preview')
preview_button.on_click(show_preview)
# Display widgets
display(preview_button, image_widget, x_start_slider, y_start_slider, x_end_slider, y_end_slider)
# Define the function to crop videos
def crop_videos():
print("Starting crop...")
for input_file in files_list:
# Construct output file path with "_cropped" suffix
file_dir, file_name = os.path.split(input_file)
file_base, file_ext = os.path.splitext(file_name)
output_file = os.path.join(file_dir, f"{file_base}_cropped{file_ext}")
start_x, start_y = x_start_slider.value, y_start_slider.value
end_x, end_y = x_end_slider.value, y_end_slider.value
# Calculate width and height, ensuring they stay within video bounds
width = min(end_x, x_start_slider.max) - start_x
height = min(end_y, y_start_slider.max) - start_y
if width <= 0 or height <= 0:
print(f"Invalid or too large crop dimensions for {input_file}")
continue
try:
# Use FFmpeg with verbose logging for detailed output
streams = ffmpeg.input(input_file)
video_stream = streams.video.filter('crop', x=start_x, y=start_y, out_w=width, out_h=height)
(
ffmpeg
.output(video_stream, streams.audio, output_file, vcodec='libx264', acodec='aac', audio_bitrate='192k')
.run(overwrite_output=True, capture_stdout=True, capture_stderr=True)
)
print(f"Cropped and saved as: {output_file}")
except ffmpeg.Error as e:
print("File conversion failed")
print(e.stdout.decode('utf8'))
print(e.stderr.decode('utf8'))
except Exception as e:
print(f"Unexpected error: {str(e)}")
# Button to start cropping process
crop_button = widgets.Button(description='Start Cropping')
crop_button.on_click(lambda b: crop_videos())
display(crop_button)
Key Improvements:
Dynamic Adjustment: Adjust the crop width and height using min() to ensure they do not exceed the video dimensions.
Validation: Include further checks to avoid ending dimensions beyond video boundaries or resulting in non-positive sizes.
These modifications ensure that only valid crop dimensions are passed to FFmpeg, preventing the previous error from occurring.
# Install necessary packages
!pip install opencv-python-headless ffmpeg-python -q
import os
import cv2
import ffmpeg
from google.colab import drive
import ipywidgets as widgets
from IPython.display import display, clear_output
import matplotlib.pyplot as plt
# Mount Google Drive
drive.mount('/content/drive')
# Function to browse directories in Google Drive
def browse_subfolders(base_folder='/content/drive/My Drive'):
"""Returns a list of subfolder paths."""
folder_list = []
for dirname, _, _ in os.walk(base_folder):
folder_list.append(dirname)
return folder_list
# Folder navigation setup
folder_dropdown = widgets.Dropdown(
options=browse_subfolders(),
description='Select Folder:',
layout=widgets.Layout(width='100%')
)
display(folder_dropdown)
drive_folder = '/content/drive/My Drive'
def update_folder_path(change):
global drive_folder
drive_folder = change.new
print(f'Selected folder: {drive_folder}')
refresh_files_list()
folder_dropdown.observe(update_folder_path, names='value')
files_list = []
files_dropdown = widgets.Dropdown(
options=files_list,
description='Select Video:',
layout=widgets.Layout(width='100%')
)
display(files_dropdown)
def refresh_files_list():
global files_list
files_list = [os.path.join(drive_folder, f) for f in os.listdir(drive_folder) if f.lower().endswith(('.mp4', '.avi', '.mov', '.mkv'))]
files_dropdown.options = files_list or ["No video files found"]
image_widget = widgets.Output()
x_start_slider = widgets.IntSlider(value=0, min=0, layout=widgets.Layout(width='50%'), description="Start X:")
y_start_slider = widgets.IntSlider(value=0, min=0, layout=widgets.Layout(width='50%'), description="Start Y:")
x_end_slider = widgets.IntSlider(value=1, min=0, layout=widgets.Layout(width='50%'), description="End X:")
y_end_slider = widgets.IntSlider(value=1, min=0, layout=widgets.Layout(width='50%'), description="End Y:")
def set_slider_max_values(video_path):
cap = cv2.VideoCapture(video_path)
ret, frame = cap.read()
cap.release()
if not ret:
print("Error reading video frame.")
return
height, width = frame.shape[:2]
# Update slider max values and defaults
x_start_slider.max = x_end_slider.max = width
y_start_slider.max = y_end_slider.max = height
x_end_slider.value = width
y_end_slider.value = height
return width, height
def show_preview(*args):
clear_output(wait=True)
selected_file = files_dropdown.value
if not selected_file or selected_file == "No video files found":
print("No video selected or found.")
return
width, height = set_slider_max_values(selected_file)
clear_output(wait=True)
display(folder_dropdown, files_dropdown, preview_button, crop_button, image_widget, x_start_slider, y_start_slider, x_end_slider, y_end_slider)
cap = cv2.VideoCapture(selected_file)
ret, frame = cap.read()
cap.release()
if ret:
frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
fig, ax = plt.subplots(figsize=(4, 3))
ax.imshow(frame_rgb)
ax.set_title('Select crop area')
crop_area = [
(x_start_slider.value, y_start_slider.value),
(x_end_slider.value, y_end_slider.value)
]
rect = plt.Rectangle(crop_area[0], crop_area[1][0] - crop_area[0][0], crop_area[1][1] - crop_area[0][1],
linewidth=1, edgecolor='r', facecolor='none')
ax.add_patch(rect)
plt.show()
preview_button = widgets.Button(description='Preview')
preview_button.on_click(show_preview)
def crop_videos():
print("Starting crop...")
for input_file in files_list:
file_dir, file_name = os.path.split(input_file)
file_base, file_ext = os.path.splitext(file_name)
output_file = os.path.join(file_dir, f"{file_base}_cropped{file_ext}")
width, height = set_slider_max_values(input_file)
start_x, start_y = x_start_slider.value, y_start_slider.value
end_x, end_y = x_end_slider.value, y_end_slider.value
crop_width = min(end_x, width) - start_x
crop_height = min(end_y, height) - start_y
if crop_width <= 0 or crop_height <= 0:
print(f"Invalid crop dimensions for {input_file}")
continue
try:
streams = ffmpeg.input(input_file)
video_stream = streams.video.filter('crop', x=start_x, y=start_y, out_w=crop_width, out_h=crop_height)
(
ffmpeg
.output(video_stream, streams.audio, output_file, vcodec='libx264', acodec='aac', audio_bitrate='192k')
.run(overwrite_output=True, capture_stdout=True, capture_stderr=True)
)
print(f"Cropped and saved as: {output_file}")
except ffmpeg.Error as e:
print("File conversion failed")
print(e.stdout.decode('utf8'))
print(e.stderr.decode('utf8'))
except Exception as e:
print(f"Unexpected error: {str(e)}")
crop_button = widgets.Button(description='Start Cropping')
crop_button.on_click(lambda b: crop_videos())
display(preview_button, crop_button, image_widget, x_start_slider, y_start_slider, x_end_slider, y_end_slider)
Key Features:
Dynamic Slider Adjustment: Sliders automatically adjust based on the resolution of the selected video, thus accommodating different resolutions.
Validation: The script will gracefully notify if invalid cropping parameters are requested.
Workflow: The script provides a smooth process for selecting and processing multiple videos with varying resolutions from your Google Drive.
This setup should handle different input resolutions correctly while adhering to cropping constraints.
# Install necessary packages
!pip install opencv-python-headless ffmpeg-python -q
import os
import cv2
import ffmpeg
from google.colab import drive
import ipywidgets as widgets
from IPython.display import display, clear_output
import matplotlib.pyplot as plt
# Mount Google Drive
drive.mount('/content/drive')
# Function to browse directories in Google Drive
def browse_subfolders(base_folder='/content/drive/My Drive'):
"""Returns a list of subfolder paths."""
folder_list = []
for dirname, _, _ in os.walk(base_folder):
folder_list.append(dirname)
return folder_list
# Folder navigation setup
folder_dropdown = widgets.Dropdown(
options=browse_subfolders(),
description='Select Folder:',
layout=widgets.Layout(width='100%')
)
display(folder_dropdown)
drive_folder = '/content/drive/My Drive'
def update_folder_path(change):
global drive_folder
drive_folder = change.new
print(f'Selected folder: {drive_folder}')
refresh_files_list()
folder_dropdown.observe(update_folder_path, names='value')
files_list = []
files_dropdown = widgets.Dropdown(
options=files_list,
description='Select Video:',
layout=widgets.Layout(width='100%')
)
display(files_dropdown)
def refresh_files_list():
global files_list
files_list = [os.path.join(drive_folder, f) for f in os.listdir(drive_folder) if f.lower().endswith(('.mp4', '.avi', '.mov', '.mkv'))]
files_dropdown.options = files_list or ["No video files found"]
image_widget = widgets.Output()
x_start_slider = widgets.IntSlider(value=0, min=0, max=100, layout=widgets.Layout(width='50%'), description="Start X (%)")
y_start_slider = widgets.IntSlider(value=0, min=0, max=100, layout=widgets.Layout(width='50%'), description="Start Y (%)")
x_end_slider = widgets.IntSlider(value=100, min=0, max=100, layout=widgets.Layout(width='50%'), description="End X (%)")
y_end_slider = widgets.IntSlider(value=100, min=0, max=100, layout=widgets.Layout(width='50%'), description="End Y (%)")
def set_slider_max_values(video_path):
cap = cv2.VideoCapture(video_path)
ret, frame = cap.read()
cap.release()
if not ret:
print("Error reading video frame.")
return
height, width = frame.shape[:2]
return width, height
def show_preview(*args):
clear_output(wait=True)
selected_file = files_dropdown.value
if not selected_file or selected_file == "No video files found":
print("No video selected or found.")
return
width, height = set_slider_max_values(selected_file)
clear_output(wait=True)
display(folder_dropdown, files_dropdown, preview_button, crop_button, image_widget, x_start_slider, y_start_slider, x_end_slider, y_end_slider)
cap = cv2.VideoCapture(selected_file)
ret, frame = cap.read()
cap.release()
if ret:
frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
fig, ax = plt.subplots(figsize=(4, 3))
ax.imshow(frame_rgb)
ax.set_title('Select crop area')
start_x = int(x_start_slider.value / 100 * width)
start_y = int(y_start_slider.value / 100 * height)
end_x = int(x_end_slider.value / 100 * width)
end_y = int(y_end_slider.value / 100 * height)
crop_area = [(start_x, start_y), (end_x, end_y)]
rect = plt.Rectangle(crop_area[0], crop_area[1][0] - crop_area[0][0], crop_area[1][1] - crop_area[0][1],
linewidth=1, edgecolor='r', facecolor='none')
ax.add_patch(rect)
plt.show()
preview_button = widgets.Button(description='Preview')
preview_button.on_click(show_preview)
def crop_videos():
print("Starting crop...")
for input_file in files_list:
file_dir, file_name = os.path.split(input_file)
file_base, file_ext = os.path.splitext(file_name)
output_file = os.path.join(file_dir, f"{file_base}_cropped{file_ext}")
width, height = set_slider_max_values(input_file)
start_x = int(x_start_slider.value / 100 * width)
start_y = int(y_start_slider.value / 100 * height)
end_x = int(x_end_slider.value / 100 * width)
end_y = int(y_end_slider.value / 100 * height)
crop_width = end_x - start_x
crop_height = end_y - start_y
if crop_width <= 0 or crop_height <= 0:
print(f"Invalid crop dimensions for {input_file}")
continue
try:
streams = ffmpeg.input(input_file)
video_stream = streams.video.filter('crop', x=start_x, y=start_y, out_w=crop_width, out_h=crop_height)
(
ffmpeg
.output(video_stream, streams.audio, output_file, vcodec='libx264', acodec='aac', audio_bitrate='192k')
.run(overwrite_output=True, capture_stdout=True, capture_stderr=True)
)
print(f"Cropped and saved as: {output_file}")
except ffmpeg.Error as e:
print("File conversion failed")
print(e.stdout.decode('utf8'))
print(e.stderr.decode('utf8'))
except Exception as e:
print(f"Unexpected error: {str(e)}")
crop_button = widgets.Button(description='Start Cropping')
crop_button.on_click(lambda b: crop_videos())
display(preview_button, crop_button, image_widget, x_start_slider, y_start_slider, x_end_slider, y_end_slider)
Key Adjustments:
Percentage-Based Sliders: The sliders for start and end points have a range from 0 to 100, representing percentages of the video dimensions.
Width and Height Calculations: Crop coordinates are calculated based on the percentages set by the sliders, allowing flexible and intuitive adjustments across videos of different resolutions.
These adjustments should meet your requirements, providing an easier way to specify crop areas using percentages.
# Install necessary packages
!pip install opencv-python-headless ffmpeg-python tqdm -q
import os
import cv2
import ffmpeg
from google.colab import drive
import ipywidgets as widgets
from IPython.display import display, clear_output
import matplotlib.pyplot as plt
from tqdm import tqdm
import time
# Mount Google Drive
drive.mount('/content/drive')
# Function to browse directories in Google Drive
def browse_subfolders(base_folder='/content/drive/My Drive'):
"""Returns a list of subfolder paths."""
folder_list = []
for dirname, _, _ in os.walk(base_folder):
folder_list.append(dirname)
return folder_list
# Folder navigation setup
folder_dropdown = widgets.Dropdown(
options=browse_subfolders(),
description='Select Folder:',
layout=widgets.Layout(width='100%')
)
display(folder_dropdown)
drive_folder = '/content/drive/My Drive'
def update_folder_path(change):
global drive_folder
drive_folder = change.new
print(f'Selected folder: {drive_folder}')
refresh_files_list()
folder_dropdown.observe(update_folder_path, names='value')
files_list = []
files_dropdown = widgets.Dropdown(
options=files_list,
description='Select Video:',
layout=widgets.Layout(width='100%')
)
display(files_dropdown)
def refresh_files_list():
global files_list
files_list = [os.path.join(drive_folder, f) for f in os.listdir(drive_folder) if f.lower().endswith(('.mp4', '.avi', '.mov', '.mkv'))]
files_dropdown.options = files_list or ["No video files found"]
image_widget = widgets.Output()
x_start_slider = widgets.IntSlider(value=0, min=0, max=100, layout=widgets.Layout(width='50%'), description="Start X (%)")
y_start_slider = widgets.IntSlider(value=0, min=0, max=100, layout=widgets.Layout(width='50%'), description="Start Y (%)")
x_end_slider = widgets.IntSlider(value=100, min=0, max=100, layout=widgets.Layout(width='50%'), description="End X (%)")
y_end_slider = widgets.IntSlider(value=100, min=0, max=100, layout=widgets.Layout(width='50%'), description="End Y (%)")
def set_slider_max_values(video_path):
cap = cv2.VideoCapture(video_path)
ret, frame = cap.read()
cap.release()
if not ret:
print("Error reading video frame.")
return
height, width = frame.shape[:2]
return width, height
def get_video_duration(video_path):
try:
probe = ffmpeg.probe(video_path)
duration = float(probe['format']['duration'])
return duration
except:
print("Error retrieving video duration.")
return None
def show_preview(*args):
clear_output(wait=True)
selected_file = files_dropdown.value
if not selected_file or selected_file == "No video files found":
print("No video selected or found.")
return
width, height = set_slider_max_values(selected_file)
clear_output(wait=True)
display(folder_dropdown, files_dropdown, preview_button, crop_button, image_widget, x_start_slider, y_start_slider, x_end_slider, y_end_slider)
cap = cv2.VideoCapture(selected_file)
ret, frame = cap.read()
cap.release()
if ret:
frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
fig, ax = plt.subplots(figsize=(4, 3))
ax.imshow(frame_rgb)
ax.set_title('Select crop area')
start_x = int(x_start_slider.value / 100 * width)
start_y = int(y_start_slider.value / 100 * height)
end_x = int(x_end_slider.value / 100 * width)
end_y = int(y_end_slider.value / 100 * height)
crop_area = [(start_x, start_y), (end_x, end_y)]
rect = plt.Rectangle(crop_area[0], crop_area[1][0] - crop_area[0][0], crop_area[1][1] - crop_area[0][1],
linewidth=1, edgecolor='r', facecolor='none')
ax.add_patch(rect)
plt.show()
preview_button = widgets.Button(description='Preview')
preview_button.on_click(show_preview)
def crop_videos():
print("Starting crop...")
for input_file in files_list:
file_dir, file_name = os.path.split(input_file)
file_base, file_ext = os.path.splitext(file_name)
output_file = os.path.join(file_dir, f"{file_base}_cropped{file_ext}")
width, height = set_slider_max_values(input_file)
start_x = int(x_start_slider.value / 100 * width)
start_y = int(y_start_slider.value / 100 * height)
end_x = int(x_end_slider.value / 100 * width)
end_y = int(y_end_slider.value / 100 * height)
crop_width = end_x - start_x
crop_height = end_y - start_y
if crop_width <= 0 or crop_height <= 0:
print(f"Invalid crop dimensions for {input_file}")
continue
duration = get_video_duration(input_file)
progress_bar = tqdm(total=duration, desc=f'Processing {file_name}', unit='s')
try:
def update_progress(mode, blsize, tells):
progress_bar.update(1)
streams = ffmpeg.input(input_file)
video_stream = streams.video.filter('crop', x=start_x, y=start_y, out_w=crop_width, out_h=crop_height)
process = (
ffmpeg
.output(video_stream, streams.audio, output_file, vcodec='libx264', acodec='aac', audio_bitrate='192k')
.global_args('-progress', 'pipe:1')
.run_async(pipe_stdout=True, pipe_stderr=True)
)
start_time = time.time()
while process.poll() is None:
line = process.stdout.readline()
if line:
tqdm.write(line.decode('utf8').strip())
time.sleep(0.1)
process.wait()
end_time = time.time()
elapsed_time = end_time - start_time
progress_bar.close()
print(f"Cropped and saved as: {output_file} (Time taken: {elapsed_time:.2f} seconds)")
except ffmpeg.Error as e:
progress_bar.close()
print("File conversion failed")
print(e.stdout.decode('utf8'))
print(e.stderr.decode('utf8'))
except Exception as e:
progress_bar.close()
print(f"Unexpected error: {str(e)}")
crop_button = widgets.Button(description='Start Cropping')
crop_button.on_click(lambda b: crop_videos())
display(preview_button, crop_button, image_widget, x_start_slider, y_start_slider, x_end_slider, y_end_slider)
Key Features:
Progress Indicator: Uses the tqdm library to provide a visual progress bar while processing.
Time Estimation: Calculates and displays the elapsed time once the processing of each video is done.
Percentage-Based Cropping: Sliders continue to represent crop areas in terms of percentages, from 0 to 100.
This setup will allow you to intuitively set crop areas and track the progress of video processing.
# Install necessary packages
!pip install opencv-python-headless ffmpeg-python -q
import os
import cv2
import ffmpeg
from google.colab import drive
import ipywidgets as widgets
from IPython.display import display, clear_output
import matplotlib.pyplot as plt
# Mount Google Drive
drive.mount('/content/drive')
# Function to browse directories in Google Drive
def browse_subfolders(base_folder='/content/drive/My Drive'):
"""Returns a list of subfolder paths."""
folder_list = []
for dirname, _, _ in os.walk(base_folder):
folder_list.append(dirname)
return folder_list
# Folder navigation setup
folder_dropdown = widgets.Dropdown(
options=browse_subfolders(),
description='Select Folder:',
layout=widgets.Layout(width='100%')
)
display(folder_dropdown)
drive_folder = '/content/drive/My Drive'
def update_folder_path(change):
global drive_folder
drive_folder = change.new
print(f'Selected folder: {drive_folder}')
refresh_files_list()
folder_dropdown.observe(update_folder_path, names='value')
files_list = []
files_dropdown = widgets.Dropdown(
options=files_list,
description='Select Video:',
layout=widgets.Layout(width='100%')
)
display(files_dropdown)
def refresh_files_list():
global files_list
files_list = [os.path.join(drive_folder, f) for f in os.listdir(drive_folder) if f.lower().endswith(('.mp4', '.avi', '.mov', '.mkv'))]
files_dropdown.options = files_list or ["No video files found"]
image_widget = widgets.Output()
x_start_slider = widgets.IntSlider(value=0, min=0, max=100, layout=widgets.Layout(width='50%'), description="Start X (%)")
y_start_slider = widgets.IntSlider(value=0, min=0, max=100, layout=widgets.Layout(width='50%'), description="Start Y (%)")
x_end_slider = widgets.IntSlider(value=100, min=0, max=100, layout=widgets.Layout(width='50%'), description="End X (%)")
y_end_slider = widgets.IntSlider(value=100, min=0, max=100, layout=widgets.Layout(width='50%'), description="End Y (%)")
def set_slider_max_values(video_path):
cap = cv2.VideoCapture(video_path)
ret, frame = cap.read()
cap.release()
if not ret:
print("Error reading video frame.")
return
height, width = frame.shape[:2]
return width, height
def show_preview(*args):
clear_output(wait=True)
selected_file = files_dropdown.value
if not selected_file or selected_file == "No video files found":
print("No video selected or found.")
return
width, height = set_slider_max_values(selected_file)
clear_output(wait=True)
display(folder_dropdown, files_dropdown, preview_button, crop_button, image_widget, x_start_slider, y_start_slider, x_end_slider, y_end_slider)
cap = cv2.VideoCapture(selected_file)
ret, frame = cap.read()
cap.release()
if ret:
frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
fig, ax = plt.subplots(figsize=(4, 3))
ax.imshow(frame_rgb)
ax.set_title('Select crop area')
start_x = int(x_start_slider.value / 100 * width)
start_y = int(y_start_slider.value / 100 * height)
end_x = int(x_end_slider.value / 100 * width)
end_y = int(y_end_slider.value / 100 * height)
crop_area = [(start_x, start_y), (end_x, end_y)]
rect = plt.Rectangle(crop_area[0], crop_area[1][0] - crop_area[0][0], crop_area[1][1] - crop_area[0][1],
linewidth=1, edgecolor='r', facecolor='none')
ax.add_patch(rect)
plt.show()
preview_button = widgets.Button(description='Preview')
preview_button.on_click(show_preview)
def crop_videos():
print("Starting crop...")
for input_file in files_list:
file_dir, file_name = os.path.split(input_file)
file_base, file_ext = os.path.splitext(file_name)
output_file = os.path.join(file_dir, f"{file_base}_cropped{file_ext}")
width, height = set_slider_max_values(input_file)
start_x = int(x_start_slider.value / 100 * width)
start_y = int(y_start_slider.value / 100 * height)
end_x = int(x_end_slider.value / 100 * width)
end_y = int(y_end_slider.value / 100 * height)
crop_width = end_x - start_x
crop_height = end_y - start_y
if crop_width <= 0 or crop_height <= 0:
print(f"Invalid crop dimensions for {input_file}")
continue
try:
streams = ffmpeg.input(input_file)
video_stream = streams.video.filter('crop', x=start_x, y=start_y, out_w=crop_width, out_h=crop_height)
(
ffmpeg
.output(video_stream, streams.audio, output_file, vcodec='libx264', acodec='aac', audio_bitrate='192k')
.run(overwrite_output=True)
)
print(f"Cropped and saved as: {output_file}")
except ffmpeg.Error as e:
print("File conversion failed")
print(e.stdout.decode('utf8'))
print(e.stderr.decode('utf8'))
except Exception as e:
print(f"Unexpected error: {str(e)}")
crop_button = widgets.Button(description='Start Cropping')
crop_button.on_click(lambda b: crop_videos())
display(preview_button, crop_button, image_widget, x_start_slider, y_start_slider, x_end_slider, y_end_slider)
Key Features:
Smooth Operation: Removed progress and time feedback components for simpler operation.
Percentage-Based Cropping: Continued percentage-based sliders for ease of use across different video resolutions.
This version of the script will efficiently handle your cropping tasks without the added complexity of progress tracking. Feel free to run and test the script!
Individual Crop Settings: Use the sliders to set crop percentages for each video individually.
Sequential Navigation: Buttons to set crop parameters and navigate through each video.
Batch Processing: After setting cropping parameters, initiate the cropping process for all videos at once.
This workflow allows you to customize the cropping area for each video before processing them in one go. Display and navigation are designed to help keep track of settings for multiple videos.
# Install necessary packages
!pip install opencv-python-headless ffmpeg-python -q
import os
import cv2
import ffmpeg
from google.colab import drive
import ipywidgets as widgets
from IPython.display import display, clear_output
import matplotlib.pyplot as plt
# Mount Google Drive
drive.mount('/content/drive')
# Function to browse directories in Google Drive
def browse_subfolders(base_folder='/content/drive/My Drive'):
"""Returns a list of subfolder paths."""
folder_list = []
for dirname, _, _ in os.walk(base_folder):
folder_list.append(dirname)
return folder_list
drive_folder = '/content/drive/My Drive'
folder_dropdown = widgets.Dropdown(
options=browse_subfolders(),
description='Select Folder:',
layout=widgets.Layout(width='100%')
)
display(folder_dropdown)
def update_folder_path(change):
global drive_folder
drive_folder = change.new
print(f'Selected folder: {drive_folder}')
refresh_files_list()
folder_dropdown.observe(update_folder_path, names='value')
files_list = []
files_dropdown = widgets.Dropdown(
options=files_list,
description='Select Video:',
layout=widgets.Layout(width='100%')
)
display(files_dropdown)
current_file_index = 0
crop_settings = {}
def refresh_files_list():
global files_list, current_file_index, crop_settings
files_list = [os.path.join(drive_folder, f) for f in os.listdir(drive_folder) if f.lower().endswith(('.mp4', '.avi', '.mov', '.mkv'))]
if not files_list:
print("No video files found in the selected folder.")
else:
print(f"Found {len(files_list)} video files.")
files_dropdown.options = files_list or ["No video files found"]
current_file_index = 0
crop_settings = {file: (0, 0, 100, 100) for file in files_list}
refresh_files_list()
x_start_slider = widgets.IntSlider(value=0, min=0, max=100, layout=widgets.Layout(width='50%'), description="Start X (%)")
y_start_slider = widgets.IntSlider(value=0, min=0, max=100, layout=widgets.Layout(width='50%'), description="Start Y (%)")
x_end_slider = widgets.IntSlider(value=100, min=0, max=100, layout=widgets.Layout(width='50%'), description="End X (%)")
y_end_slider = widgets.IntSlider(value=100, min=0, max=100, layout=widgets.Layout(width='50%'), description="End Y (%)")
image_widget = widgets.Output()
def update_sliders_for_current_file():
if files_list: # Check if the list is not empty
current_file = files_list[current_file_index]
start_x, start_y, end_x, end_y = crop_settings[current_file]
x_start_slider.value = start_x
y_start_slider.value = start_y
x_end_slider.value = end_x
y_end_slider.value = end_y
else:
print("No video files available to set sliders.")
def set_slider_max_values(video_path):
cap = cv2.VideoCapture(video_path)
ret, frame = cap.read()
cap.release()
if not ret:
print("Error reading video frame.")
return None, None # Return None to indicate failure
height, width = frame.shape[:2]
return width, height
def show_preview():
clear_output(wait=True)
if not files_list:
print("No video files available to preview.")
return
display(folder_dropdown, files_dropdown, image_widget, x_start_slider, y_start_slider, x_end_slider, y_end_slider, set_button, next_button, crop_all_button)
current_file = files_list[current_file_index]
cap = cv2.VideoCapture(current_file)
ret, frame = cap.read()
cap.release()
width, height = frame.shape[1], frame.shape[0]
if ret:
frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
fig, ax = plt.subplots(figsize=(4, 3))
ax.imshow(frame_rgb)
ax.set_title(f'Crop area for: {os.path.basename(current_file)}')
start_x = int(x_start_slider.value / 100 * width)
start_y = int(y_start_slider.value / 100 * height)
end_x = int(x_end_slider.value / 100 * width)
end_y = int(y_end_slider.value / 100 * height)
crop_area = [(start_x, start_y), (end_x, end_y)]
rect = plt.Rectangle(crop_area[0], crop_area[1][0] - crop_area[0][0], crop_area[1][1] - crop_area[0][1],
linewidth=1, edgecolor='r', facecolor='none')
ax.add_patch(rect)
plt.show()
def set_crop_for_current_file():
if files_list: # Check if there are videos to set
current_file = files_list[current_file_index]
crop_settings[current_file] = (x_start_slider.value, y_start_slider.value, x_end_slider.value, y_end_slider.value)
print(f"Set crop for {os.path.basename(current_file)}: {crop_settings[current_file]}")
def next_video(*args):
global current_file_index
if current_file_index < len(files_list) - 1:
current_file_index += 1
update_sliders_for_current_file()
show_preview()
def crop_videos():
if not files_list:
print("No videos to crop.")
return
print("Starting crop...")
for input_file in files_list:
file_dir, file_name = os.path.split(input_file)
file_base, file_ext = os.path.splitext(file_name)
output_file = os.path.join(file_dir, f"{file_base}_cropped{file_ext}")
crop_info = crop_settings[input_file]
start_x_percent, start_y_percent, end_x_percent, end_y_percent = crop_info
width, height = set_slider_max_values(input_file)
if width is None or height is None:
print(f"Skipping {input_file} due to read error.")
continue
start_x = int(start_x_percent / 100 * width)
start_y = int(start_y_percent / 100 * height)
end_x = int(end_x_percent / 100 * width)
end_y = int(end_y_percent / 100 * height)
crop_width = end_x - start_x
crop_height = end_y - start_y
if crop_width <= 0 or crop_height <= 0:
print(f"Invalid crop dimensions for {input_file}")
continue
try:
streams = ffmpeg.input(input_file)
video_stream = streams.video.filter('crop', x=start_x, y=start_y, out_w=crop_width, out_h=crop_height)
(
ffmpeg
.output(video_stream, streams.audio, output_file, vcodec='libx264', acodec='aac', audio_bitrate='192k')
.run(overwrite_output=True)
)
print(f"Cropped and saved as: {output_file}")
except ffmpeg.Error as e:
print("File conversion failed")
print(e.stdout.decode('utf8'))
print(e.stderr.decode('utf8'))
except Exception as e:
print(f"Unexpected error: {str(e)}")
set_button = widgets.Button(description="Set Crop for Current Video")
set_button.on_click(lambda b: set_crop_for_current_file())
next_button = widgets.Button(description="Next Video")
next_button.on_click(lambda b: next_video())
crop_all_button = widgets.Button(description="Start Cropping All Videos")
crop_all_button.on_click(lambda b: crop_videos())
update_sliders_for_current_file()
show_preview()
Explanation:
Error Handling: Added checks to handle empty files_list, preventing index errors and allowing for more meaningful error messages.
Initialization: Sets up a default crop setting for each video when the file list is initialized.
User Feedback: Provides feedback if no videos are found or a specific operation cannot proceed, guiding the user appropriately.
Make sure your chosen Google Drive folder contains video files with the specified formats for this code to work properly.
# Install necessary packages
!pip install opencv-python-headless ffmpeg-python -q
import os
import cv2
import ffmpeg
from google.colab import drive
import ipywidgets as widgets
from IPython.display import display, clear_output
import matplotlib.pyplot as plt
# Mount Google Drive
drive.mount('/content/drive')
# Function to browse directories in Google Drive
def browse_subfolders(base_folder='/content/drive/My Drive'):
"""Returns a list of subfolder paths."""
folder_list = [base_folder]
for dirname, _, _ in os.walk(base_folder):
folder_list.append(dirname)
return folder_list
# Dropdown to select folder
drive_folder = '/content/drive/My Drive'
folder_dropdown = widgets.Dropdown(
options=browse_subfolders(drive_folder),
description='Select Folder:',
layout=widgets.Layout(width='100%')
)
display(folder_dropdown)
def update_folder_path(change):
global drive_folder
drive_folder = change.new
print(f'Selected folder: {drive_folder}')
refresh_files_list()
folder_dropdown.observe(update_folder_path, names='value')
files_list = []
files_dropdown = widgets.Dropdown(
options=files_list,
description='Select Video:',
layout=widgets.Layout(width='100%')
)
current_file_index = 0
crop_settings = {}
def refresh_files_list():
global files_list, current_file_index, crop_settings
files_list = [os.path.join(drive_folder, f) for f in os.listdir(drive_folder) if f.lower().endswith(('.mp4', '.avi', '.mov', '.mkv'))]
if not files_list:
print("No video files found in the selected folder.")
else:
print(f"Found {len(files_list)} video files.")
files_dropdown.options = files_list or ["No video files found"]
current_file_index = 0
crop_settings = {file: (0, 0, 100, 100) for file in files_list}
refresh_files_list()
x_start_slider = widgets.IntSlider(value=0, min=0, max=100, layout=widgets.Layout(width='50%'), description="Start X (%)")
y_start_slider = widgets.IntSlider(value=0, min=0, max=100, layout=widgets.Layout(width='50%'), description="Start Y (%)")
x_end_slider = widgets.IntSlider(value=100, min=0, max=100, layout=widgets.Layout(width='50%'), description="End X (%)")
y_end_slider = widgets.IntSlider(value=100, min=0, max=100, layout=widgets.Layout(width='50%'), description="End Y (%)")
image_widget = widgets.Output()
def update_sliders_for_current_file():
if files_list: # Check if the list is not empty
current_file = files_list[current_file_index]
start_x, start_y, end_x, end_y = crop_settings[current_file]
x_start_slider.value = start_x
y_start_slider.value = start_y
x_end_slider.value = end_x
y_end_slider.value = end_y
else:
print("No video files available to set sliders.")
def set_slider_max_values(video_path):
cap = cv2.VideoCapture(video_path)
ret, frame = cap.read()
cap.release()
if not ret:
print("Error reading video frame.")
return None, None # Return None to indicate failure
height, width = frame.shape[:2]
return width, height
def show_preview():
clear_output(wait=True)
if not files_list:
print("No video files available to preview.")
return
display(folder_dropdown, x_start_slider, y_start_slider, x_end_slider, y_end_slider, set_button, next_button, crop_all_button)
current_file = files_list[current_file_index]
cap = cv2.VideoCapture(current_file)
ret, frame = cap.read()
cap.release()
width, height = frame.shape[1], frame.shape[0]
if ret:
frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
fig, ax = plt.subplots(figsize=(4, 3))
ax.imshow(frame_rgb)
ax.set_title(f'Crop area for: {os.path.basename(current_file)}')
start_x = int(x_start_slider.value / 100 * width)
start_y = int(y_start_slider.value / 100 * height)
end_x = int(x_end_slider.value / 100 * width)
end_y = int(y_end_slider.value / 100 * height)
crop_area = [(start_x, start_y), (end_x, end_y)]
rect = plt.Rectangle(crop_area[0], crop_area[1][0] - crop_area[0][0], crop_area[1][1] - crop_area[0][1],
linewidth=1, edgecolor='r', facecolor='none')
ax.add_patch(rect)
plt.show()
def set_crop_for_current_file():
if files_list: # Check if there are videos to set
current_file = files_list[current_file_index]
crop_settings[current_file] = (x_start_slider.value, y_start_slider.value, x_end_slider.value, y_end_slider.value)
print(f"Set crop for {os.path.basename(current_file)}: {crop_settings[current_file]}")
def next_video(*args):
global current_file_index
if current_file_index < len(files_list) - 1:
current_file_index += 1
update_sliders_for_current_file()
show_preview()
def crop_videos():
if not files_list:
print("No videos to crop.")
return
print("Starting crop...")
for input_file in files_list:
file_dir, file_name = os.path.split(input_file)
file_base, file_ext = os.path.splitext(file_name)
output_file = os.path.join(file_dir, f"{file_base}_cropped{file_ext}")
crop_info = crop_settings[input_file]
start_x_percent, start_y_percent, end_x_percent, end_y_percent = crop_info
width, height = set_slider_max_values(input_file)
if width is None or height is None:
print(f"Skipping {input_file} due to read error.")
continue
start_x = int(start_x_percent / 100 * width)
start_y = int(start_y_percent / 100 * height)
end_x = int(end_x_percent / 100 * width)
end_y = int(end_y_percent / 100 * height)
crop_width = end_x - start_x
crop_height = end_y - start_y
if crop_width <= 0 or crop_height <= 0:
print(f"Invalid crop dimensions for {input_file}")
continue
try:
streams = ffmpeg.input(input_file)
video_stream = streams.video.filter('crop', x=start_x, y=start_y, out_w=crop_width, out_h=crop_height)
(
ffmpeg
.output(video_stream, streams.audio, output_file, vcodec='libx264', acodec='aac', audio_bitrate='192k')
.run(overwrite_output=True)
)
print(f"Cropped and saved as: {output_file}")
except ffmpeg.Error as e:
print("File conversion failed")
print(e.stdout.decode('utf8'))
print(e.stderr.decode('utf8'))
except Exception as e:
print(f"Unexpected error: {str(e)}")
set_button = widgets.Button(description="Set Crop for Current Video")
set_button.on_click(lambda b: set_crop_for_current_file())
next_button = widgets.Button(description="Next Video")
next_button.on_click(lambda b: next_video())
crop_all_button = widgets.Button(description="Start Cropping All Videos")
crop_all_button.on_click(lambda b: crop_videos())
update_sliders_for_current_file()
show_preview()
Key Features:
Folder Navigation: Allows you to navigate through all folders and subfolders in your Google Drive to find the folder with videos.
Set Crop for Each Video: Navigate through videos to set crop percentages individually.
Batch Processing: Start the crop process for all videos after they've been configured.
You can iterate through each video, adjusting crop settings one by one, before proceeding to batch-process them.
# Install necessary packages
!pip install opencv-python-headless ffmpeg-python -q
import os
import cv2
import ffmpeg
from google.colab import drive
import ipywidgets as widgets
from IPython.display import display, clear_output
import matplotlib.pyplot as plt
# Mount Google Drive
drive.mount('/content/drive')
# Function to browse directories in Google Drive
def browse_subfolders(base_folder='/content/drive/My Drive'):
"""Returns a list of subfolder paths."""
folder_list = [base_folder]
for dirname, _, _ in os.walk(base_folder):
folder_list.append(dirname)
return folder_list
# Dropdown for folder selection
drive_folder = '/content/drive/My Drive'
folder_dropdown = widgets.Dropdown(
options=browse_subfolders(drive_folder),
description='Select Folder:',
layout=widgets.Layout(width='100%')
)
display(folder_dropdown)
def update_folder_path(change):
global drive_folder
drive_folder = change.new
print(f'Selected folder: {drive_folder}')
refresh_files_list()
folder_dropdown.observe(update_folder_path, names='value')
files_list = []
files_dropdown = widgets.Dropdown(
options=files_list,
description='Select Video:',
layout=widgets.Layout(width='100%')
)
current_file_index = 0
crop_settings = {}
def refresh_files_list():
global files_list, current_file_index, crop_settings
try:
files_list = [os.path.join(drive_folder, f) for f in os.listdir(drive_folder) if f.lower().endswith(('.mp4', '.avi', '.mov', '.mkv'))]
print(f"Debug: Found {len(files_list)} video files in {drive_folder}.")
except Exception as e:
print(f"Error accessing folder: {e}")
files_list = []
if not files_list:
print("No video files found in the selected folder.")
else:
print(f"Found {len(files_list)} video files.")
files_dropdown.options = files_list or ["No video files found"]
current_file_index = 0
crop_settings = {file: (0, 0, 100, 100) for file in files_list}
refresh_files_list()
x_start_slider = widgets.IntSlider(value=0, min=0, max=100, layout=widgets.Layout(width='50%'), description="Start X (%)")
y_start_slider = widgets.IntSlider(value=0, min=0, max=100, layout=widgets.Layout(width='50%'), description="Start Y (%)")
x_end_slider = widgets.IntSlider(value=100, min=0, max=100, layout=widgets.Layout(width='50%'), description="End X (%)")
y_end_slider = widgets.IntSlider(value=100, min=0, max=100, layout=widgets.Layout(width='50%'), description="End Y (%)")
image_widget = widgets.Output()
def update_sliders_for_current_file():
if files_list: # Check if the list is not empty
current_file = files_list[current_file_index]
start_x, start_y, end_x, end_y = crop_settings[current_file]
x_start_slider.value = start_x
y_start_slider.value = start_y
x_end_slider.value = end_x
y_end_slider.value = end_y
else:
print("No video files available to set sliders.")
def set_slider_max_values(video_path):
cap = cv2.VideoCapture(video_path)
ret, frame = cap.read()
cap.release()
if not ret:
print("Error reading video frame.")
return None, None # Return None to indicate failure
height, width = frame.shape[:2]
return width, height
def show_preview():
clear_output(wait=True)
if not files_list:
print("No video files available to preview.")
return
display(folder_dropdown, x_start_slider, y_start_slider, x_end_slider, y_end_slider, set_button, next_button, crop_all_button)
current_file = files_list[current_file_index]
cap = cv2.VideoCapture(current_file)
ret, frame = cap.read()
cap.release()
if not ret:
print(f"Error reading video: {current_file}")
return
width, height = frame.shape[1], frame.shape[0]
frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
fig, ax = plt.subplots(figsize=(4, 3))
ax.imshow(frame_rgb)
ax.set_title(f'Crop area for: {os.path.basename(current_file)}')
start_x = int(x_start_slider.value / 100 * width)
start_y = int(y_start_slider.value / 100 * height)
end_x = int(x_end_slider.value / 100 * width)
end_y = int(y_end_slider.value / 100 * height)
crop_area = [(start_x, start_y), (end_x, end_y)]
rect = plt.Rectangle(crop_area[0], crop_area[1][0] - crop_area[0][0], crop_area[1][1] - crop_area[0][1],
linewidth=1, edgecolor='r', facecolor='none')
ax.add_patch(rect)
plt.show()
def set_crop_for_current_file():
if files_list: # Check if there are videos to set
current_file = files_list[current_file_index]
crop_settings[current_file] = (x_start_slider.value, y_start_slider.value, x_end_slider.value, y_end_slider.value)
print(f"Set crop for {os.path.basename(current_file)}: {crop_settings[current_file]}")
def next_video(*args):
global current_file_index
if current_file_index < len(files_list) - 1:
current_file_index += 1
update_sliders_for_current_file()
show_preview()
def crop_videos():
if not files_list:
print("No videos to crop.")
return
print("Starting crop...")
for input_file in files_list:
file_dir, file_name = os.path.split(input_file)
file_base, file_ext = os.path.splitext(file_name)
output_file = os.path.join(file_dir, f"{file_base}_cropped{file_ext}")
crop_info = crop_settings[input_file]
start_x_percent, start_y_percent, end_x_percent, end_y_percent = crop_info
width, height = set_slider_max_values(input_file)
if width is None or height is None:
print(f"Skipping {input_file} due to read error.")
continue
start_x = int(start_x_percent / 100 * width)
start_y = int(start_y_percent / 100 * height)
end_x = int(end_x_percent / 100 * width)
end_y = int(end_y_percent / 100 * height)
crop_width = end_x - start_x
crop_height = end_y - start_y
if crop_width <= 0 or crop_height <= 0:
print(f"Invalid crop dimensions for {input_file}")
continue
try:
streams = ffmpeg.input(input_file)
video_stream = streams.video.filter('crop', x=start_x, y=start_y, out_w=crop_width, out_h=crop_height)
(
ffmpeg
.output(video_stream, streams.audio, output_file, vcodec='libx264', acodec='aac', audio_bitrate='192k')
.run(overwrite_output=True)
)
print(f"Cropped and saved as: {output_file}")
except ffmpeg.Error as e:
print("File conversion failed")
print(e.stdout.decode('utf8'))
print(e.stderr.decode('utf8'))
except Exception as e:
print(f"Unexpected error: {str(e)}")
set_button = widgets.Button(description="Set Crop for Current Video")
set_button.on_click(lambda b: set_crop_for_current_file())
next_button = widgets.Button(description="Next Video")
next_button.on_click(lambda b: next_video())
crop_all_button = widgets.Button(description="Start Cropping All Videos")
crop_all_button.on_click(lambda b: crop_videos())
update_sliders_for_current_file()
show_preview()
What to Do:
Verify File Extensions: Double-check that your files have the correct extensions.
Check Directory: Confirm selection of the correct folder that contains videos.
The code now incorporates better debugging information to help you locate and resolve the problem with accessing the video files.
# Install necessary packages
!pip install opencv-python-headless ffmpeg-python -q
import os
import cv2
import ffmpeg
from google.colab import drive
import ipywidgets as widgets
from IPython.display import display, clear_output
import matplotlib.pyplot as plt
# Mount Google Drive
drive.mount('/content/drive')
# Function to browse directories in Google Drive
def browse_subfolders(base_folder='/content/drive/My Drive'):
"""Returns a list of subfolder paths."""
folder_list = [base_folder]
for dirname, _, _ in os.walk(base_folder):
folder_list.append(dirname)
return folder_list
# Initial setup without attempting to list files immediately
drive_folder = '/content/drive/My Drive'
folder_dropdown = widgets.Dropdown(
options=browse_subfolders(drive_folder),
description='Select Folder:',
layout=widgets.Layout(width='100%')
)
display(folder_dropdown)
files_list = []
current_file_index = 0
crop_settings = {}
x_start_slider = widgets.IntSlider(value=0, min=0, max=100, layout=widgets.Layout(width='50%'), description="Start X (%)")
y_start_slider = widgets.IntSlider(value=0, min=0, max=100, layout=widgets.Layout(width='50%'), description="Start Y (%)")
x_end_slider = widgets.IntSlider(value=100, min=0, max=100, layout=widgets.Layout(width='50%'), description="End X (%)")
y_end_slider = widgets.IntSlider(value=100, min=0, max=100, layout=widgets.Layout(width='50%'), description="End Y (%)")
image_widget = widgets.Output()
def set_slider_max_values(video_path):
cap = cv2.VideoCapture(video_path)
ret, frame = cap.read()
cap.release()
if not ret:
print("Error reading video frame.")
return None, None # Return None to indicate failure
height, width = frame.shape[:2]
return width, height
def update_folder_path(change):
global drive_folder, files_list, crop_settings
drive_folder = change.new
print(f'Selected folder: {drive_folder}')
files_list = [os.path.join(drive_folder, f) for f in os.listdir(drive_folder) if f.lower().endswith(('.mp4', '.avi', '.mov', '.mkv'))]
if not files_list:
print("No video files found in the selected folder.")
return
else:
print(f"Found {len(files_list)} video files.")
current_file_index = 0
crop_settings = {file: (0, 0, 100, 100) for file in files_list}
update_sliders_for_current_file()
show_preview()
folder_dropdown.observe(update_folder_path, names='value')
def update_sliders_for_current_file():
if files_list: # Check if the list is not empty
current_file = files_list[current_file_index]
start_x, start_y, end_x, end_y = crop_settings[current_file]
x_start_slider.value = start_x
y_start_slider.value = start_y
x_end_slider.value = end_x
y_end_slider.value = end_y
else:
print("No video files available to set sliders.")
def show_preview():
clear_output(wait=True)
if not files_list:
print("No video files available to preview.")
return
display(folder_dropdown, x_start_slider, y_start_slider, x_end_slider, y_end_slider, set_button, next_button, crop_all_button)
current_file = files_list[current_file_index]
cap = cv2.VideoCapture(current_file)
ret, frame = cap.read()
cap.release()
if not ret:
print(f"Error reading video: {current_file}")
return
width, height = frame.shape[1], frame.shape[0]
frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
fig, ax = plt.subplots(figsize=(4, 3))
ax.imshow(frame_rgb)
ax.set_title(f'Crop area for: {os.path.basename(current_file)}')
start_x = int(x_start_slider.value / 100 * width)
start_y = int(y_start_slider.value / 100 * height)
end_x = int(x_end_slider.value / 100 * width)
end_y = int(y_end_slider.value / 100 * height)
crop_area = [(start_x, start_y), (end_x, end_y)]
rect = plt.Rectangle(crop_area[0], crop_area[1][0] - crop_area[0][0], crop_area[1][1] - crop_area[0][1],
linewidth=1, edgecolor='r', facecolor='none')
ax.add_patch(rect)
plt.show()
def set_crop_for_current_file():
if files_list: # Check if there are videos to set
current_file = files_list[current_file_index]
crop_settings[current_file] = (x_start_slider.value, y_start_slider.value, x_end_slider.value, y_end_slider.value)
print(f"Set crop for {os.path.basename(current_file)}: {crop_settings[current_file]}")
def next_video(*args):
global current_file_index
if current_file_index < len(files_list) - 1:
current_file_index += 1
update_sliders_for_current_file()
show_preview()
def crop_videos():
if not files_list:
print("No videos to crop.")
return
print("Starting crop...")
for input_file in files_list:
file_dir, file_name = os.path.split(input_file)
file_base, file_ext = os.path.splitext(file_name)
output_file = os.path.join(file_dir, f"{file_base}_cropped{file_ext}")
crop_info = crop_settings[input_file]
start_x_percent, start_y_percent, end_x_percent, end_y_percent = crop_info
width, height = set_slider_max_values(input_file)
if width is None or height is None:
print(f"Skipping {input_file} due to read error.")
continue
start_x = int(start_x_percent / 100 * width)
start_y = int(start_y_percent / 100 * height)
end_x = int(end_x_percent / 100 * width)
end_y = int(end_y_percent / 100 * height)
crop_width = end_x - start_x
crop_height = end_y - start_y
if crop_width <= 0 or crop_height <= 0:
print(f"Invalid crop dimensions for {input_file}")
continue
try:
streams = ffmpeg.input(input_file)
video_stream = streams.video.filter('crop', x=start_x, y=start_y, out_w=crop_width, out_h=crop_height)
(
ffmpeg
.output(video_stream, streams.audio, output_file, vcodec='libx264', acodec='aac', audio_bitrate='192k')
.run(overwrite_output=True)
)
print(f"Cropped and saved as: {output_file}")
except ffmpeg.Error as e:
print("File conversion failed")
print(e.stdout.decode('utf8'))
print(e.stderr.decode('utf8'))
except Exception as e:
print(f"Unexpected error: {str(e)}")
set_button = widgets.Button(description="Set Crop for Current Video")
set_button.on_click(lambda b: set_crop_for_current_file())
next_button = widgets.Button(description="Next Video")
next_button.on_click(lambda b: next_video())
crop_all_button = widgets.Button(description="Start Cropping All Videos")
crop_all_button.on_click(lambda b: crop_videos())
Key Adjustments:
Deferred Video Processing: The script does not attempt to list videos or display previews until a folder is selected.
Robust Initialization: Properly initializes lists and checks for the presence of videos before allowing navigation and cropping setup.
Debug Output: Provides detailed output to verify the process at each step.
This setup should ensure that the script runs properly, responding after you select a folder containing video files. Test by navigating directories to identify the correct video folder.
# Install necessary packages
!pip install opencv-python-headless ffmpeg-python -q
import os
import cv2
import ffmpeg
from google.colab import drive
import ipywidgets as widgets
from IPython.display import display, clear_output
import matplotlib.pyplot as plt
# Mount Google Drive
drive.mount('/content/drive')
# Function to browse directories in Google Drive
def browse_subfolders(base_folder='/content/drive/My Drive'):
"""Returns a list of subfolder paths."""
folder_list = [base_folder]
for dirname, _, _ in os.walk(base_folder):
folder_list.append(dirname)
return folder_list
# Dropdown for folder selection
drive_folder = '/content/drive/My Drive'
folder_dropdown = widgets.Dropdown(
options=browse_subfolders(drive_folder),
description='Select Folder:',
layout=widgets.Layout(width='100%')
)
display(folder_dropdown)
files_list = []
current_file_index = 0
crop_settings = {}
x_start_slider = widgets.IntSlider(value=0, min=0, max=100, layout=widgets.Layout(width='50%'), description="Start X (%)")
y_start_slider = widgets.IntSlider(value=0, min=0, max=100, layout=widgets.Layout(width='50%'), description="Start Y (%)")
x_end_slider = widgets.IntSlider(value=100, min=0, max=100, layout=widgets.Layout(width='50%'), description="End X (%)")
y_end_slider = widgets.IntSlider(value=100, min=0, max=100, layout=widgets.Layout(width='50%'), description="End Y (%)")
image_widget = widgets.Output()
def set_slider_max_values(video_path):
cap = cv2.VideoCapture(video_path)
ret, frame = cap.read()
cap.release()
if not ret:
print("Error reading video frame.")
return None, None # Return None to indicate failure
height, width = frame.shape[:2]
return width, height
def update_folder_path(change):
global drive_folder, files_list, crop_settings
drive_folder = change.new
print(f'Selected folder: {drive_folder}')
files_list = [os.path.join(drive_folder, f) for f in os.listdir(drive_folder) if f.lower().endswith(('.mp4', '.avi', '.mov', '.mkv'))]
if not files_list:
print("No video files found in the selected folder.")
return
else:
print(f"Found {len(files_list)} video files.")
current_file_index = 0
crop_settings = {file: (0, 0, 100, 100) for file in files_list}
update_sliders_for_current_file()
show_preview()
folder_dropdown.observe(update_folder_path, names='value')
def update_sliders_for_current_file():
if files_list: # Check if the list is not empty
current_file = files_list[current_file_index]
start_x, start_y, end_x, end_y = crop_settings[current_file]
x_start_slider.value = start_x
y_start_slider.value = start_y
x_end_slider.value = end_x
y_end_slider.value = end_y
else:
print("No video files available to set sliders.")
def show_preview(*args):
clear_output(wait=True)
if not files_list:
print("No video files available to preview.")
return
display(folder_dropdown, x_start_slider, y_start_slider, x_end_slider, y_end_slider, set_button, next_button, crop_all_button)
current_file = files_list[current_file_index]
cap = cv2.VideoCapture(current_file)
ret, frame = cap.read()
cap.release()
if not ret:
print(f"Error reading video: {current_file}")
return
width, height = frame.shape[1], frame.shape[0]
frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
fig, ax = plt.subplots(figsize=(4, 3))
ax.imshow(frame_rgb)
ax.set_title(f'Crop area for: {os.path.basename(current_file)}')
start_x = int(x_start_slider.value / 100 * width)
start_y = int(y_start_slider.value / 100 * height)
end_x = int(x_end_slider.value / 100 * width)
end_y = int(y_end_slider.value / 100 * height)
crop_area = [(start_x, start_y), (end_x, end_y)]
rect = plt.Rectangle(crop_area[0], crop_area[1][0] - crop_area[0][0], crop_area[1][1] - crop_area[0][1],
linewidth=1, edgecolor='r', facecolor='none')
ax.add_patch(rect)
plt.show()
def set_crop_for_current_file():
if files_list: # Check if there are videos to set
current_file = files_list[current_file_index]
crop_settings[current_file] = (x_start_slider.value, y_start_slider.value, x_end_slider.value, y_end_slider.value)
print(f"Set crop for {os.path.basename(current_file)}: {crop_settings[current_file]}")
def next_video(*args):
global current_file_index
if current_file_index < len(files_list) - 1:
current_file_index += 1
update_sliders_for_current_file()
show_preview()
def crop_videos():
if not files_list:
print("No videos to crop.")
return
print("Starting crop...")
for input_file in files_list:
file_dir, file_name = os.path.split(input_file)
file_base, file_ext = os.path.splitext(file_name)
output_file = os.path.join(file_dir, f"{file_base}_cropped{file_ext}")
crop_info = crop_settings[input_file]
start_x_percent, start_y_percent, end_x_percent, end_y_percent = crop_info
width, height = set_slider_max_values(input_file)
if width is None or height is None:
print(f"Skipping {input_file} due to read error.")
continue
start_x = int(start_x_percent / 100 * width)
start_y = int(start_y_percent / 100 * height)
end_x = int(end_x_percent / 100 * width)
end_y = int(end_y_percent / 100 * height)
crop_width = end_x - start_x
crop_height = end_y - start_y
if crop_width <= 0 or crop_height <= 0:
print(f"Invalid crop dimensions for {input_file}")
continue
try:
streams = ffmpeg.input(input_file)
video_stream = streams.video.filter('crop', x=start_x, y=start_y, out_w=crop_width, out_h=crop_height)
(
ffmpeg
.output(video_stream, streams.audio, output_file, vcodec='libx264', acodec='aac', audio_bitrate='192k')
.run(overwrite_output=True)
)
print(f"Cropped and saved as: {output_file}")
except ffmpeg.Error as e:
print("File conversion failed")
print(e.stdout.decode('utf8'))
print(e.stderr.decode('utf8'))
except Exception as e:
print(f"Unexpected error: {str(e)}")
set_button = widgets.Button(description="Set Crop for Current Video")
set_button.on_click(lambda b: set_crop_for_current_file())
next_button = widgets.Button(description="Next Video")
next_button.on_click(lambda b: next_video())
crop_all_button = widgets.Button(description="Start Cropping All Videos")
crop_all_button.on_click(lambda b: crop_videos())
# Automatically update the preview when sliders are adjusted
x_start_slider.observe(show_preview, names='value')
y_start_slider.observe(show_preview, names='value')
x_end_slider.observe(show_preview, names='value')
y_end_slider.observe(show_preview, names='value')
Key Adjustments:
Real-Time Updates: The preview updates automatically when any slider (crop area) is adjusted.
Dynamic Slider Observation: The show_preview function is called whenever any slider value changes, ensuring the preview is synchronized with cropping selections.
This setup allows you to immediately visualize the selected crop area, enhancing usability and efficiency when setting up your crops.