i have a video cropping script, but sometime I don't get sounds in output processed…
- User
i have a video cropping script, but sometime I don't get sounds in output processed videos. can you make a robust approch so that I can get output sounds without any error. here is my full script import tkinter as tk from tkinter import filedialog, messagebox, ttk import cv2 import ffmpeg from PIL import Image, ImageTk import os
Initialize global variables
start_x, start_y, end_x, end_y = 0, 0, 0, 0 rect_id = None input_files = [] crop_areas = {} current_file_index = 0 original_width, original_height = 0, 0 canvas_width, canvas_height = 640, 480 resize_ratio = 1.0
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()
def load_next_frame(): global frame, img_tk, input_files, current_file_index, original_width, original_height, resize_ratio if current_file_index >= len(input_files): messagebox.showinfo("Info", "All rectangles drawn. Starting to crop and flip videos.") crop_videos() return input_file = input_files[current_file_index] cap = cv2.VideoCapture(input_file) ret, frame = cap.read() cap.release() if ret: original_height, original_width = frame.shape[:2] aspect_ratio = original_width / original_height if aspect_ratio > 1: new_width = canvas_width new_height = int(canvas_width / aspect_ratio) else: new_height = canvas_height new_width = int(canvas_height * aspect_ratio) resize_ratio = original_width / new_width resized_frame = cv2.resize(frame, (new_width, new_height)) frame = cv2.cvtColor(resized_frame, cv2.COLOR_BGR2RGB) img = Image.fromarray(frame) img_tk = ImageTk.PhotoImage(image=img) canvas.create_image(0, 0, anchor=tk.NW, image=img_tk) root.update() print(f"Loaded frame from {input_file}")
def load_previous_frame(): global current_file_index if current_file_index > 0: current_file_index -= 1 load_next_frame()
def on_enter(event): global current_file_index crop_areas[input_files[current_file_index]] = (start_x, start_y, end_x, end_y) print(f"Crop area for {input_files[current_file_index]}: ({start_x}, {start_y}, {end_x}, {end_y})") current_file_index += 1 load_next_frame()
def clear_selection(): global rect_id if rect_id: canvas.delete(rect_id) rect_id = None print("Selection cleared")
def crop_videos(): try: progress["maximum"] = len(input_files) for i, input_file in enumerate(input_files): parent_dir = os.path.dirname(input_file) output_dir = os.path.join(parent_dir, "CROPPED VIDEO") os.makedirs(output_dir, exist_ok=True) output_file = os.path.join(output_dir, os.path.basename(input_file)) start_x, start_y, end_x, end_y = crop_areas[input_file] # Map coordinates back to original size start_x = int(start_x * resize_ratio) start_y = int(start_y * resize_ratio) end_x = int(end_x * resize_ratio) end_y = int(end_y * resize_ratio) 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_x}, start_y={start_y}, end_x={end_x}, end_y={end_y}, width={width}, height={height}") 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}") progress["value"] = i + 1 root.update_idletasks() messagebox.showinfo("Task Completed", "All videos have been cropped and flipped successfully!") except Exception as e: print(f"Error: {e}")
root = tk.Tk() root.title("Video Cropper")
canvas = tk.Canvas(root, width=canvas_width, height=canvas_height) canvas.pack()
canvas.bind("", select_area) canvas.bind("", crop_area) root.bind("", on_enter)
Organize buttons in a frame
button_frame = tk.Frame(root) button_frame.pack()
load_button = tk.Button(button_frame, text="Load Videos", command=load_frames) load_button.grid(row=0, column=0)
prev_button = tk.Button(button_frame, text="Previous Video", command=load_previous_frame) prev_button.grid(row=0, column=1)
next_button = tk.Button(button_frame, text="Next Video", command=load_next_frame) next_button.grid(row=0, column=2)
clear_button = tk.Button(button_frame, text="Clear Selection", command=clear_selection) clear_button.grid(row=0, column=3)
progress = ttk.Progressbar(root, orient="horizontal", length=300, mode="determinate") progress.pack()
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
The issue you're facing with missing audio in the output videos might be due to not explicitly including the audio stream in your ffmpeg command. By default, some ffmpeg operations might only handle the video stream unless specified to include audio. To ensure that audio is retained in the output video, you'll need to include it in your FFmpeg command.
Here’s a revised version of your
crop_videosfunction that should handle both video and audio streams by explicitly mapping both streams:def crop_videos(): try: progress["maximum"] = len(input_files) for i, input_file in enumerate(input_files): parent_dir = os.path.dirname(input_file) output_dir = os.path.join(parent_dir, "CROPPED VIDEO") os.makedirs(output_dir, exist_ok=True) output_file = os.path.join(output_dir, os.path.basename(input_file)) start_x, start_y, end_x, end_y = crop_areas[input_file] # Map coordinates back to original size start_x = int(start_x * resize_ratio) start_y = int(start_y * resize_ratio) end_x = int(end_x * resize_ratio) end_y = int(end_y * resize_ratio) 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_x}, start_y={start_y}, end_x={end_x}, end_y={end_y}, width={width}, height={height}") try: # Process the video and audio with ffmpeg input_ffmpeg = ffmpeg.input(input_file) video = input_ffmpeg.video.crop(x=start_x, y=start_y, width=width, height=height).hflip() audio = input_ffmpeg.audio ffmpeg.output(video, audio, output_file).run() print(f"Video {input_file} cropped and flipped successfully!") except ffmpeg.Error as e: print(f"FFmpeg error: {e.stderr.decode('utf-8')}") except Exception as e: print(f"Unexpected error: {e}") progress["value"] = i + 1 root.update_idletasks() messagebox.showinfo("Task Completed", "All videos have been cropped and flipped successfully!") except Exception as e: print(f"Error: {e}")Key Changes:
- Audio Inclusion: The ffmpeg process now explicitly maps the video and audio streams (
video = input_ffmpeg.videoandaudio = input_ffmpeg.audio) to ensure that both are processed and included in the output file. - Error Messages: Improved error logging to provide more detailed information from ffmpeg failures by decoding stderr.
Additional Tips:
- Make sure that your FFmpeg installation is up-to-date and available in your system path.
- Test with a single video with known working parameters before scaling to multiple files to debug any additional issues that might arise.
- Ensure that your
ffmpegPython module is installed. If not, you can install it viapip install ffmpeg-python.
By following these steps, the modifications should help in retaining the audio in the processed videos.
- Audio Inclusion: The ffmpeg process now explicitly maps the video and audio streams (
- User
kindly provide me full updated script
- Assistant
Here's the full updated script, incorporating the changes to ensure audio is properly included in the output videos:
import tkinter as tk from tkinter import filedialog, messagebox, ttk import cv2 import ffmpeg from PIL import Image, ImageTk import os # Initialize global variables start_x, start_y, end_x, end_y = 0, 0, 0, 0 rect_id = None input_files = [] crop_areas = {} current_file_index = 0 original_width, original_height = 0, 0 canvas_width, canvas_height = 640, 480 resize_ratio = 1.0 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() def load_next_frame(): global frame, img_tk, input_files, current_file_index, original_width, original_height, resize_ratio if current_file_index >= len(input_files): messagebox.showinfo("Info", "All rectangles drawn. Starting to crop and flip videos.") crop_videos() return input_file = input_files[current_file_index] cap = cv2.VideoCapture(input_file) ret, frame = cap.read() cap.release() if ret: original_height, original_width = frame.shape[:2] aspect_ratio = original_width / original_height if aspect_ratio > 1: new_width = canvas_width new_height = int(canvas_width / aspect_ratio) else: new_height = canvas_height new_width = int(canvas_height * aspect_ratio) resize_ratio = original_width / new_width resized_frame = cv2.resize(frame, (new_width, new_height)) frame = cv2.cvtColor(resized_frame, cv2.COLOR_BGR2RGB) img = Image.fromarray(frame) img_tk = ImageTk.PhotoImage(image=img) canvas.create_image(0, 0, anchor=tk.NW, image=img_tk) root.update() print(f"Loaded frame from {input_file}") def load_previous_frame(): global current_file_index if current_file_index > 0: current_file_index -= 1 load_next_frame() def on_enter(event): global current_file_index crop_areas[input_files[current_file_index]] = (start_x, start_y, end_x, end_y) print(f"Crop area for {input_files[current_file_index]}: ({start_x}, {start_y}, {end_x}, {end_y})") current_file_index += 1 load_next_frame() def clear_selection(): global rect_id if rect_id: canvas.delete(rect_id) rect_id = None print("Selection cleared") def crop_videos(): try: progress["maximum"] = len(input_files) for i, input_file in enumerate(input_files): parent_dir = os.path.dirname(input_file) output_dir = os.path.join(parent_dir, "CROPPED VIDEO") os.makedirs(output_dir, exist_ok=True) output_file = os.path.join(output_dir, os.path.basename(input_file)) start_x, start_y, end_x, end_y = crop_areas[input_file] # Map coordinates back to original size start_x = int(start_x * resize_ratio) start_y = int(start_y * resize_ratio) end_x = int(end_x * resize_ratio) end_y = int(end_y * resize_ratio) 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_x}, start_y={start_y}, end_x={end_x}, end_y={end_y}, width={width}, height={height}") try: # Process the video and audio with ffmpeg input_ffmpeg = ffmpeg.input(input_file) video = input_ffmpeg.video.crop(x=start_x, y=start_y, width=width, height=height).hflip() audio = input_ffmpeg.audio ffmpeg.output(video, audio, output_file).run(overwrite_output=True) print(f"Video {input_file} cropped and flipped successfully!") except ffmpeg.Error as e: print(f"FFmpeg error: {e.stderr.decode('utf-8')}") except Exception as e: print(f"Unexpected error: {e}") progress["value"] = i + 1 root.update_idletasks() messagebox.showinfo("Task Completed", "All videos have been cropped and flipped successfully!") except Exception as e: print(f"Error: {e}") root = tk.Tk() root.title("Video Cropper") canvas = tk.Canvas(root, width=canvas_width, height=canvas_height) canvas.pack() canvas.bind("<Button-1>", select_area) canvas.bind("<B1-Motion>", crop_area) root.bind("<Return>", on_enter) # Organize buttons in a frame button_frame = tk.Frame(root) button_frame.pack() load_button = tk.Button(button_frame, text="Load Videos", command=load_frames) load_button.grid(row=0, column=0) prev_button = tk.Button(button_frame, text="Previous Video", command=load_previous_frame) prev_button.grid(row=0, column=1) next_button = tk.Button(button_frame, text="Next Video", command=load_next_frame) next_button.grid(row=0, column=2) clear_button = tk.Button(button_frame, text="Clear Selection", command=clear_selection) clear_button.grid(row=0, column=3) progress = ttk.Progressbar(root, orient="horizontal", length=300, mode="determinate") progress.pack() 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()Key Points:
- Audio Stream: The script now explicitly processes both video and audio streams using
input_ffmpeg.videoandinput_ffmpeg.audio, ensuring audio is included in the output. - Overwrite Option: The
.run(overwrite_output=True)option allows ffmpeg to overwrite existing files without prompting, ensuring smoother operation without interruptions. - Error Handling: The FFmpeg error messages are more descriptive with
e.stderr.decode('utf-8').
This full script should maintain the audio track in the output video files while performing the desired cropping and transformation tasks. Make sure to test it in your environment to confirm that it works as expected.
- Audio Stream: The script now explicitly processes both video and audio streams using
- User
is it flipping also videos? if not then add a option to flip videos horizontally before starting to processing of videos
- Assistant
The existing script already includes a horizontal flip operation using
.hflip()in theffmpegcommand. However, if you want to provide a toggle option for flipping videos (i.e., whether to flip or not based on user input), we can add a checkbox to the GUI that allows users to choose whether or not they want to flip the videos. Here’s how you can incorporate this feature:import tkinter as tk from tkinter import filedialog, messagebox, ttk import cv2 import ffmpeg from PIL import Image, ImageTk import os # Initialize global variables start_x, start_y, end_x, end_y = 0, 0, 0, 0 rect_id = None input_files = [] crop_areas = {} current_file_index = 0 original_width, original_height = 0, 0 canvas_width, canvas_height = 640, 480 resize_ratio = 1.0 flip_enabled = tk.BooleanVar(value=True) # New variable to track flip option 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() def load_next_frame(): global frame, img_tk, input_files, current_file_index, original_width, original_height, resize_ratio if current_file_index >= len(input_files): messagebox.showinfo("Info", "All rectangles drawn. Starting to crop and flip videos.") crop_videos() return input_file = input_files[current_file_index] cap = cv2.VideoCapture(input_file) ret, frame = cap.read() cap.release() if ret: original_height, original_width = frame.shape[:2] aspect_ratio = original_width / original_height if aspect_ratio > 1: new_width = canvas_width new_height = int(canvas_width / aspect_ratio) else: new_height = canvas_height new_width = int(canvas_height * aspect_ratio) resize_ratio = original_width / new_width resized_frame = cv2.resize(frame, (new_width, new_height)) frame = cv2.cvtColor(resized_frame, cv2.COLOR_BGR2RGB) img = Image.fromarray(frame) img_tk = ImageTk.PhotoImage(image=img) canvas.create_image(0, 0, anchor=tk.NW, image=img_tk) root.update() print(f"Loaded frame from {input_file}") def load_previous_frame(): global current_file_index if current_file_index > 0: current_file_index -= 1 load_next_frame() def on_enter(event): global current_file_index crop_areas[input_files[current_file_index]] = (start_x, start_y, end_x, end_y) print(f"Crop area for {input_files[current_file_index]}: ({start_x}, {start_y}, {end_x}, {end_y})") current_file_index += 1 load_next_frame() def clear_selection(): global rect_id if rect_id: canvas.delete(rect_id) rect_id = None print("Selection cleared") def crop_videos(): try: progress["maximum"] = len(input_files) for i, input_file in enumerate(input_files): parent_dir = os.path.dirname(input_file) output_dir = os.path.join(parent_dir, "CROPPED VIDEO") os.makedirs(output_dir, exist_ok=True) output_file = os.path.join(output_dir, os.path.basename(input_file)) start_x, start_y, end_x, end_y = crop_areas[input_file] # Map coordinates back to original size start_x = int(start_x * resize_ratio) start_y = int(start_y * resize_ratio) end_x = int(end_x * resize_ratio) end_y = int(end_y * resize_ratio) 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_x}, start_y={start_y}, end_x={end_x}, end_y={end_y}, width={width}, height={height}") try: # Process the video and audio with ffmpeg input_ffmpeg = ffmpeg.input(input_file) video = input_ffmpeg.video.crop(x=start_x, y=start_y, width=width, height=height) if flip_enabled.get(): video = video.hflip() audio = input_ffmpeg.audio ffmpeg.output(video, audio, output_file).run(overwrite_output=True) print(f"Video {input_file} cropped and flipped successfully!") except ffmpeg.Error as e: print(f"FFmpeg error: {e.stderr.decode('utf-8')}") except Exception as e: print(f"Unexpected error: {e}") progress["value"] = i + 1 root.update_idletasks() messagebox.showinfo("Task Completed", "All videos have been cropped and flipped successfully!") except Exception as e: print(f"Error: {e}") root = tk.Tk() root.title("Video Cropper") canvas = tk.Canvas(root, width=canvas_width, height=canvas_height) canvas.pack() canvas.bind("<Button-1>", select_area) canvas.bind("<B1-Motion>", crop_area) root.bind("<Return>", on_enter) # Organize buttons in a frame button_frame = tk.Frame(root) button_frame.pack() load_button = tk.Button(button_frame, text="Load Videos", command=load_frames) load_button.grid(row=0, column=0) prev_button = tk.Button(button_frame, text="Previous Video", command=load_previous_frame) prev_button.grid(row=0, column=1) next_button = tk.Button(button_frame, text="Next Video", command=load_next_frame) next_button.grid(row=0, column=2) clear_button = tk.Button(button_frame, text="Clear Selection", command=clear_selection) clear_button.grid(row=0, column=3) # Add a checkbox to toggle flip flip_checkbox = tk.Checkbutton(button_frame, text="Flip Horizontally", variable=flip_enabled) flip_checkbox.grid(row=0, column=4) progress = ttk.Progressbar(root, orient="horizontal", length=300, mode="determinate") progress.pack() 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.\n6. Check 'Flip Horizontally' to apply flipping.") instructions.pack() root.mainloop()Key Changes:
- Flip Option Toggle: Added a
tk.BooleanVarnamedflip_enabledto hold the checkbox state for flipping, initialized toTrue. - Checkbox: Added a
Checkbuttonto the GUI labeled "Flip Horizontally". Users can check or uncheck this box to enable or disable video flipping. - Conditional Flip: Adjusted the
crop_videosfunction to conditionally applyhflip()based on the state offlip_enabled.
With these changes, users can choose whether or not they want to flip videos by interacting with the checkbox in the GUI.
- Flip Option Toggle: Added a
- User
also make sure if I don't select any areas within a video I e just press enter it means I want to skip Cropping that particular video
- Assistant
To ensure that pressing Enter without selecting any area skips cropping for that particular video, you'll need to implement a check to see if any cropping area was selected. If no area was selected (i.e.,
start_x == end_xorstart_y == end_y), then just add the video to a list of files that require no cropping. Here's how you can implement this logic:import tkinter as tk from tkinter import filedialog, messagebox, ttk import cv2 import ffmpeg from PIL import Image, ImageTk import os # Initialize global variables start_x, start_y, end_x, end_y = 0, 0, 0, 0 rect_id = None input_files = [] crop_areas = {} current_file_index = 0 original_width, original_height = 0, 0 canvas_width, canvas_height = 640, 480 resize_ratio = 1.0 flip_enabled = tk.BooleanVar(value=True) skip_cropping = set() # New set to keep track of videos that shouldn't be cropped 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() def load_next_frame(): global frame, img_tk, input_files, current_file_index, original_width, original_height, resize_ratio if current_file_index >= len(input_files): messagebox.showinfo("Info", "All rectangles drawn. Starting to crop and flip videos.") crop_videos() return input_file = input_files[current_file_index] cap = cv2.VideoCapture(input_file) ret, frame = cap.read() cap.release() if ret: original_height, original_width = frame.shape[:2] aspect_ratio = original_width / original_height if aspect_ratio > 1: new_width = canvas_width new_height = int(canvas_width / aspect_ratio) else: new_height = canvas_height new_width = int(canvas_height * aspect_ratio) resize_ratio = original_width / new_width resized_frame = cv2.resize(frame, (new_width, new_height)) frame = cv2.cvtColor(resized_frame, cv2.COLOR_BGR2RGB) img = Image.fromarray(frame) img_tk = ImageTk.PhotoImage(image=img) canvas.create_image(0, 0, anchor=tk.NW, image=img_tk) root.update() print(f"Loaded frame from {input_file}") def load_previous_frame(): global current_file_index if current_file_index > 0: current_file_index -= 1 load_next_frame() def on_enter(event): global current_file_index if start_x == end_x or start_y == end_y: # No cropping area selected, skip cropping for this video skip_cropping.add(input_files[current_file_index]) print(f"No cropping area selected for {input_files[current_file_index]}. Skipping cropping.") else: # Store cropping area crop_areas[input_files[current_file_index]] = (start_x, start_y, end_x, end_y) print(f"Crop area for {input_files[current_file_index]}: ({start_x}, {start_y}, {end_x}, {end_y})") current_file_index += 1 load_next_frame() def clear_selection(): global rect_id if rect_id: canvas.delete(rect_id) rect_id = None print("Selection cleared") def crop_videos(): try: progress["maximum"] = len(input_files) for i, input_file in enumerate(input_files): parent_dir = os.path.dirname(input_file) output_dir = os.path.join(parent_dir, "CROPPED VIDEO") os.makedirs(output_dir, exist_ok=True) output_file = os.path.join(output_dir, os.path.basename(input_file)) if input_file in skip_cropping: try: # Just flip the video (if enabled) without cropping input_ffmpeg = ffmpeg.input(input_file) video = input_ffmpeg.video if flip_enabled.get(): video = video.hflip() audio = input_ffmpeg.audio ffmpeg.output(video, audio, output_file).run(overwrite_output=True) print(f"Video {input_file} skipped cropping, flipped successfully!") except ffmpeg.Error as e: print(f"FFmpeg error: {e.stderr.decode('utf-8')}") except Exception as e: print(f"Unexpected error: {e}") else: start_x, start_y, end_x, end_y = crop_areas[input_file] start_x = int(start_x * resize_ratio) start_y = int(start_y * resize_ratio) end_x = int(end_x * resize_ratio) end_y = int(end_y * resize_ratio) 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_x}, start_y={start_y}, end_x={end_x}, end_y={end_y}, width={width}, height={height}") try: input_ffmpeg = ffmpeg.input(input_file) video = input_ffmpeg.video.crop(x=start_x, y=start_y, width=width, height=height) if flip_enabled.get(): video = video.hflip() audio = input_ffmpeg.audio ffmpeg.output(video, audio, output_file).run(overwrite_output=True) print(f"Video {input_file} cropped and flipped successfully!") except ffmpeg.Error as e: print(f"FFmpeg error: {e.stderr.decode('utf-8')}") except Exception as e: print(f"Unexpected error: {e}") progress["value"] = i + 1 root.update_idletasks() messagebox.showinfo("Task Completed", "All videos have been processed successfully!") except Exception as e: print(f"Error: {e}") root = tk.Tk() root.title("Video Cropper") canvas = tk.Canvas(root, width=canvas_width, height=canvas_height) canvas.pack() canvas.bind("<Button-1>", select_area) canvas.bind("<B1-Motion>", crop_area) root.bind("<Return>", on_enter) # Organize buttons in a frame button_frame = tk.Frame(root) button_frame.pack() load_button = tk.Button(button_frame, text="Load Videos", command=load_frames) load_button.grid(row=0, column=0) prev_button = tk.Button(button_frame, text="Previous Video", command=load_previous_frame) prev_button.grid(row=0, column=1) next_button = tk.Button(button_frame, text="Next Video", command=load_next_frame) next_button.grid(row=0, column=2) clear_button = tk.Button(button_frame, text="Clear Selection", command=clear_selection) clear_button.grid(row=0, column=3) # Add a checkbox to toggle flip flip_checkbox = tk.Checkbutton(button_frame, text="Flip Horizontally", variable=flip_enabled) flip_checkbox.grid(row=0, column=4) progress = ttk.Progressbar(root, orient="horizontal", length=300, mode="determinate") progress.pack() 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.\n6. Check 'Flip Horizontally' to apply flipping.\n7. Press Enter without selecting to skip cropping.") instructions.pack() root.mainloop()Key Updates:
-
Skipping Cropping:
- Added a new set
skip_croppingto keep track of videos for which the cropping should be skipped. - When no area is selected (i.e., pressing Enter without drawing), add the video to
skip_cropping.
- Added a new set
-
Selective Processing:
- In the
crop_videosfunction, if a video is in theskip_croppingset, it will be processed without cropping, while applying the flip if enabled.
- In the
With these changes, the script will skip cropping for those videos where no cropping area is selected, while still allowing for optional horizontal flipping as per the user's input.
-
- User
Traceback (most recent call last): File "C:\Users\mosto\Desktop\VIDEO CROPPING AND FLIPPING.py", line 17, in flip_enabled = tk.BooleanVar(value=True) ^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\mosto\AppData\Local\Programs\Python\Python312\Lib\tkinter_init_.py", line 635, in init Variable.init(self, master, value, name) File "C:\Users\mosto\AppData\Local\Programs\Python\Python312\Lib\tkinter_init_.py", line 397, in init master = get_default_root('create variable') ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\mosto\AppData\Local\Programs\Python\Python312\Lib\tkinter_init.py", line 323, in _get_default_root raise RuntimeError(f"Too early to {what}: no default root window") RuntimeError: Too early to create variable: no default root window
- Assistant
The error message indicates that the
tk.BooleanVarinstance is being created before a default Tkinter root window has been initialized. In Tkinter, all widgets and variables need a master window to associate with, typically created withroot = tk.Tk(). Let's ensure that the root window is created before any other Tkinter-related operations.Here's the corrected script with
flip_enabledinitialized after the root window is created:import tkinter as tk from tkinter import filedialog, messagebox, ttk import cv2 import ffmpeg from PIL import Image, ImageTk import os # Initialize global variables start_x, start_y, end_x, end_y = 0, 0, 0, 0 rect_id = None input_files = [] crop_areas = {} current_file_index = 0 original_width, original_height = 0, 0 canvas_width, canvas_height = 640, 480 resize_ratio = 1.0 skip_cropping = set() # Set to keep track of videos that shouldn't be cropped 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() def load_next_frame(): global frame, img_tk, input_files, current_file_index, original_width, original_height, resize_ratio if current_file_index >= len(input_files): messagebox.showinfo("Info", "All rectangles drawn. Starting to crop and flip videos.") crop_videos() return input_file = input_files[current_file_index] cap = cv2.VideoCapture(input_file) ret, frame = cap.read() cap.release() if ret: original_height, original_width = frame.shape[:2] aspect_ratio = original_width / original_height if aspect_ratio > 1: new_width = canvas_width new_height = int(canvas_width / aspect_ratio) else: new_height = canvas_height new_width = int(canvas_height * aspect_ratio) resize_ratio = original_width / new_width resized_frame = cv2.resize(frame, (new_width, new_height)) frame = cv2.cvtColor(resized_frame, cv2.COLOR_BGR2RGB) img = Image.fromarray(frame) img_tk = ImageTk.PhotoImage(image=img) canvas.create_image(0, 0, anchor=tk.NW, image=img_tk) root.update() print(f"Loaded frame from {input_file}") def load_previous_frame(): global current_file_index if current_file_index > 0: current_file_index -= 1 load_next_frame() def on_enter(event): global current_file_index if start_x == end_x or start_y == end_y: # No cropping area selected, skip cropping for this video skip_cropping.add(input_files[current_file_index]) print(f"No cropping area selected for {input_files[current_file_index]}. Skipping cropping.") else: # Store cropping area crop_areas[input_files[current_file_index]] = (start_x, start_y, end_x, end_y) print(f"Crop area for {input_files[current_file_index]}: ({start_x}, {start_y}, {end_x}, {end_y})") current_file_index += 1 load_next_frame() def clear_selection(): global rect_id if rect_id: canvas.delete(rect_id) rect_id = None print("Selection cleared") def crop_videos(): try: progress["maximum"] = len(input_files) for i, input_file in enumerate(input_files): parent_dir = os.path.dirname(input_file) output_dir = os.path.join(parent_dir, "CROPPED VIDEO") os.makedirs(output_dir, exist_ok=True) output_file = os.path.join(output_dir, os.path.basename(input_file)) if input_file in skip_cropping: try: # Just flip the video (if enabled) without cropping input_ffmpeg = ffmpeg.input(input_file) video = input_ffmpeg.video if flip_enabled.get(): video = video.hflip() audio = input_ffmpeg.audio ffmpeg.output(video, audio, output_file).run(overwrite_output=True) print(f"Video {input_file} skipped cropping, flipped successfully!") except ffmpeg.Error as e: print(f"FFmpeg error: {e.stderr.decode('utf-8')}") except Exception as e: print(f"Unexpected error: {e}") else: start_x, start_y, end_x, end_y = crop_areas[input_file] start_x = int(start_x * resize_ratio) start_y = int(start_y * resize_ratio) end_x = int(end_x * resize_ratio) end_y = int(end_y * resize_ratio) 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_x}, start_y={start_y}, end_x={end_x}, end_y={end_y}, width={width}, height={height}") try: input_ffmpeg = ffmpeg.input(input_file) video = input_ffmpeg.video.crop(x=start_x, y=start_y, width=width, height=height) if flip_enabled.get(): video = video.hflip() audio = input_ffmpeg.audio ffmpeg.output(video, audio, output_file).run(overwrite_output=True) print(f"Video {input_file} cropped and flipped successfully!") except ffmpeg.Error as e: print(f"FFmpeg error: {e.stderr.decode('utf-8')}") except Exception as e: print(f"Unexpected error: {e}") progress["value"] = i + 1 root.update_idletasks() messagebox.showinfo("Task Completed", "All videos have been processed successfully!") except Exception as e: print(f"Error: {e}") root = tk.Tk() root.title("Video Cropper") canvas = tk.Canvas(root, width=canvas_width, height=canvas_height) canvas.pack() canvas.bind("<Button-1>", select_area) canvas.bind("<B1-Motion>", crop_area) root.bind("<Return>", on_enter) # Initialize flip enabled variable after root flip_enabled = tk.BooleanVar(value=True) # Organize buttons in a frame button_frame = tk.Frame(root) button_frame.pack() load_button = tk.Button(button_frame, text="Load Videos", command=load_frames) load_button.grid(row=0, column=0) prev_button = tk.Button(button_frame, text="Previous Video", command=load_previous_frame) prev_button.grid(row=0, column=1) next_button = tk.Button(button_frame, text="Next Video", command=load_next_frame) next_button.grid(row=0, column=2) clear_button = tk.Button(button_frame, text="Clear Selection", command=clear_selection) clear_button.grid(row=0, column=3) # Add a checkbox to toggle flip flip_checkbox = tk.Checkbutton(button_frame, text="Flip Horizontally", variable=flip_enabled) flip_checkbox.grid(row=0, column=4) progress = ttk.Progressbar(root, orient="horizontal", length=300, mode="determinate") progress.pack() 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.\n6. Check 'Flip Horizontally' to apply flipping.\n7. Press Enter without selecting to skip cropping.") instructions.pack() root.mainloop()Key Adjustment:
- Initialization Order: Move the
flip_enabledvariable initialization after creating the root window withroot = tk.Tk(). This ensures thatflip_enabledgets properly associated with the root window.
This change addresses the runtime error and ensures the application initializes correctly.
- Initialization Order: Move the