File size: 14,406 Bytes
91fd92a 057cf2a 91fd92a 057cf2a 91fd92a | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 | import cv2
import numpy as np
import os
from PIL import Image, ExifTags
import random
import argparse
import time
# Increase OpenCV/FFMPEG frame read retry attempts for long or unstable video reads
os.environ["OPENCV_FFMPEG_READ_ATTEMPTS"] = "50000"
# Default values (can be overridden via command line)
video_path = "path/to/video.mp4"
output_dir = "outputs/preprocessed"
frame_interval = 60 # Extract every nth frame
zoom_level = 5.0 # 5x zoom -> crop 1/5 of original frame, then resize to 640x640
crops_per_frame = 10 # Number of random crops per extracted frame
manual_crop = False # If True, use one fixed crop position instead of random crops
crop_x_center = 0.5 # Manual crop center X (relative: 0.0 to 1.0)
crop_y_center = 0.5 # Manual crop center Y (relative: 0.0 to 1.0)
def extract_and_preprocess_frames(
video_path,
output_dir,
frame_interval=10,
zoom_level=5.0,
crops_per_frame=5,
manual_crop=False,
crop_x=0.5,
crop_y=0.5,
start_frame=0,
end_frame=None,
segment_id=0,
):
"""
Extract frames from a video segment and generate zoomed crops.
Workflow:
1) Read video frames in a specified frame range [start_frame, end_frame)
2) Keep every nth frame (frame_interval)
3) Optional EXIF-based orientation correction (mostly useful for images, harmless for video frames)
4) Crop a zoom window (manual or random position)
5) Resize crop to 640x640
6) Apply CLAHE contrast enhancement
7) Save as JPG with frame and crop position encoded in filename
Returns:
saved_count (int): Number of extracted frames processed (not total crops)
total_saved (int): Total number of crops saved
"""
# Create base output directory
os.makedirs(output_dir, exist_ok=True)
# Open video
cap = cv2.VideoCapture(video_path)
if not cap.isOpened():
raise ValueError(f"Could not open video file: {video_path}")
# Video metadata
total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
fps = cap.get(cv2.CAP_PROP_FPS)
# Clamp end_frame to video length
if end_frame is None or end_frame > total_frames:
end_frame = total_frames
print(f"Video loaded: {video_path}")
print(f"Total frames: {total_frames}")
print(f"FPS: {fps}")
print(f"Processing segment {segment_id + 1}: frames {start_frame} to {end_frame}")
print(f"Extracting every {frame_interval} frames")
print(f"Zooming {zoom_level * 100}% and cropping to 640x640")
print(f"Crops per frame: {crops_per_frame}")
print(f"Manual crop: {manual_crop}, Position: ({crop_x}, {crop_y})")
# CLAHE for local contrast enhancement (helps visibility in crack-like textures)
clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8, 8))
# Seek to start frame
cap.set(cv2.CAP_PROP_POS_FRAMES, start_frame)
count = start_frame
saved_count = 0 # Counts processed frames (not crops)
# Save segment outputs in separate subfolder
segment_dir = os.path.join(output_dir, f"segment_{segment_id + 1}")
os.makedirs(segment_dir, exist_ok=True)
while count < end_frame:
ret, frame = cap.read()
if not ret:
print(f"Error reading frame at position {count}. Breaking out of loop.")
break
# Process every nth frame inside this segment
if (count - start_frame) % frame_interval == 0:
# Convert to PIL for optional EXIF orientation correction
pil_img = Image.fromarray(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB))
# EXIF orientation correction (videos usually don't have EXIF, so this often does nothing)
try:
orientation_tag = None
for tag_id, tag_name in ExifTags.TAGS.items():
if tag_name == "Orientation":
orientation_tag = tag_id
break
exif = dict(pil_img.getexif().items())
if orientation_tag is not None and orientation_tag in exif:
if exif[orientation_tag] == 3:
pil_img = pil_img.rotate(180, expand=True)
elif exif[orientation_tag] == 6:
pil_img = pil_img.rotate(270, expand=True)
elif exif[orientation_tag] == 8:
pil_img = pil_img.rotate(90, expand=True)
except (AttributeError, KeyError, IndexError, TypeError):
# No EXIF or EXIF not readable
pass
# Back to OpenCV BGR
frame = cv2.cvtColor(np.array(pil_img), cv2.COLOR_RGB2BGR)
# Original frame size
height, width = frame.shape[:2]
# Compute crop window size from zoom factor
# Example: zoom=5 -> crop 1/5 width and 1/5 height, then upscale to 640x640
crop_width = int(width / zoom_level)
crop_height = int(height / zoom_level)
# Safety check for invalid crop sizes
if crop_width <= 0 or crop_height <= 0:
print(f"Skipping frame {count}: invalid crop size ({crop_width}, {crop_height})")
count += 1
continue
if manual_crop:
# Single deterministic crop at user-defined relative position
process_crop(
frame, count, 0, crop_x, crop_y,
crop_width, crop_height, width, height,
segment_dir, clahe
)
saved_count += 1
else:
# Multiple random crops per frame
for i in range(crops_per_frame):
# Avoid edges slightly to reduce out-of-frame crop clipping
random_x = random.uniform(0.1, 0.9)
random_y = random.uniform(0.1, 0.9)
process_crop(
frame, count, i, random_x, random_y,
crop_width, crop_height, width, height,
segment_dir, clahe
)
saved_count += 1
if saved_count % 10 == 0:
print(f"Segment {segment_id + 1}: Processed {saved_count} extracted frames (current frame={count})")
count += 1
cap.release()
# Total number of crop images written
total_saved = saved_count * (1 if manual_crop else crops_per_frame)
print(
f"Segment {segment_id + 1} completed! "
f"Processed {saved_count} extracted frames and saved {total_saved} crops."
)
return saved_count, total_saved
def process_crop(
frame,
frame_count,
crop_index,
rel_x,
rel_y,
crop_width,
crop_height,
width,
height,
output_dir,
clahe,
):
"""
Create one crop from a frame, resize to 640x640, enhance contrast, and save.
Args:
rel_x, rel_y: Relative crop center coordinates in [0, 1]
"""
# Convert relative center coords to pixel coordinates
center_x = int(rel_x * width)
center_y = int(rel_y * height)
# Top-left crop corner
start_x = center_x - (crop_width // 2)
start_y = center_y - (crop_height // 2)
# Clamp crop start so crop stays inside frame
start_x = max(0, min(start_x, width - crop_width))
start_y = max(0, min(start_y, height - crop_height))
# Compute crop end
end_x = min(start_x + crop_width, width)
end_y = min(start_y + crop_height, height)
# Final adjustment if crop was clipped
if end_x - start_x < crop_width:
start_x = max(0, end_x - crop_width)
if end_y - start_y < crop_height:
start_y = max(0, end_y - crop_height)
try:
# Crop region from original frame
cropped = frame[start_y:end_y, start_x:end_x]
# Skip empty crops (rare edge case)
if cropped.size == 0:
print(f"Empty crop at frame {frame_count}, crop {crop_index}")
return
# Resize to model-friendly input size
zoomed = cv2.resize(cropped, (640, 640), interpolation=cv2.INTER_LINEAR)
# Apply CLAHE
if len(zoomed.shape) == 3:
# Color image: apply CLAHE channel-wise in BGR space
# Note: This may shift colors slightly. For more natural results, apply on LAB L-channel.
enhanced = cv2.merge([
clahe.apply(zoomed[:, :, 0]),
clahe.apply(zoomed[:, :, 1]),
clahe.apply(zoomed[:, :, 2]),
])
else:
# Grayscale image
enhanced = clahe.apply(zoomed)
# Filename convention
# crop_index == 0 is first crop; in manual mode this is the only crop
if crop_index == 0:
filename = f"frame5_{frame_count:06d}"
else:
filename = f"frame5_{frame_count:06d}_crop{crop_index}"
# Encode crop center position (% of frame) for traceability
pos_info = f"_x{int(rel_x * 100):03d}_y{int(rel_y * 100):03d}"
frame_filename = os.path.join(output_dir, f"{filename}{pos_info}.jpg")
cv2.imwrite(frame_filename, enhanced)
except Exception as e:
print(f"Error processing crop at frame {frame_count}, crop {crop_index}: {e}")
def process_video_in_segments(
video_path,
output_dir,
frame_interval,
zoom_level,
crops_per_frame,
manual_crop,
crop_x,
crop_y,
segment_size=5000,
overlap=100,
):
"""
Process video in segments to avoid memory/decoder instability on long videos.
Note:
- Overlap can help avoid missing frames near segment boundaries.
- But overlap can also create duplicate outputs if the same frame is processed in two segments.
"""
cap = cv2.VideoCapture(video_path)
if not cap.isOpened():
raise ValueError(f"Could not open video file: {video_path}")
total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
cap.release()
print(f"Total frames in video: {total_frames}")
print(f"Processing in segments of {segment_size} frames with {overlap} frame overlap")
# Prevent invalid step size
if segment_size <= overlap:
raise ValueError("segment_size must be greater than overlap")
# Segment start indices
start_frames = list(range(0, total_frames, segment_size - overlap))
total_frames_processed = 0 # processed extracted frames
total_crops_processed = 0 # saved crop images
for i, start_frame in enumerate(start_frames):
end_frame = min(start_frame + segment_size, total_frames)
print(f"\n{'=' * 80}")
print(f"Processing segment {i + 1}/{len(start_frames)}: frames {start_frame} to {end_frame}")
print(f"{'=' * 80}\n")
# Small pause between segments (helps file handles / decoder stability)
if i > 0:
time.sleep(2)
try:
frames_processed, crops_processed = extract_and_preprocess_frames(
video_path=video_path,
output_dir=output_dir,
frame_interval=frame_interval,
zoom_level=zoom_level,
crops_per_frame=crops_per_frame,
manual_crop=manual_crop,
crop_x=crop_x,
crop_y=crop_y,
start_frame=start_frame,
end_frame=end_frame,
segment_id=i,
)
total_frames_processed += frames_processed
total_crops_processed += crops_processed
except Exception as e:
print(f"Error processing segment {i + 1}: {e}")
print("Continuing with next segment...")
print(f"\n{'=' * 80}")
print(
f"Processing complete! "
f"Processed {total_frames_processed} extracted frames and saved {total_crops_processed} crops."
)
print(f"{'=' * 80}")
if __name__ == "__main__":
parser = argparse.ArgumentParser(
description="Extract frames from a video and generate zoomed crops with optional CLAHE enhancement"
)
# Input/output
parser.add_argument("--video", type=str, default=video_path, help="Path to input video")
parser.add_argument("--output", type=str, default=output_dir, help="Directory to save processed crops")
# Extraction/cropping settings
parser.add_argument("--interval", type=int, default=frame_interval, help="Extract every nth frame")
parser.add_argument("--zoom", type=float, default=zoom_level, help="Zoom factor (e.g., 5.0 = 500%%)")
parser.add_argument("--crops", type=int, default=crops_per_frame, help="Random crops per extracted frame")
parser.add_argument("--manual", action="store_true", help="Use one manual crop position instead of random crops")
parser.add_argument("--crop_x", type=float, default=crop_x_center, help="Manual crop center X in [0,1]")
parser.add_argument("--crop_y", type=float, default=crop_y_center, help="Manual crop center Y in [0,1]")
# Segmentation settings (for long videos)
parser.add_argument("--segment_size", type=int, default=5000, help="Frames per segment")
parser.add_argument("--overlap", type=int, default=100, help="Segment overlap in frames")
args = parser.parse_args()
# Basic input validation
if not args.video or not os.path.isfile(args.video):
print(f"Error: Video file '{args.video}' does not exist.")
raise SystemExit(1)
if args.interval <= 0:
print("Error: --interval must be > 0")
raise SystemExit(1)
if args.zoom <= 0:
print("Error: --zoom must be > 0")
raise SystemExit(1)
if args.crops <= 0 and not args.manual:
print("Error: --crops must be > 0 when not using --manual")
raise SystemExit(1)
if not (0.0 <= args.crop_x <= 1.0 and 0.0 <= args.crop_y <= 1.0):
print("Error: --crop_x and --crop_y must be in [0,1]")
raise SystemExit(1)
try:
process_video_in_segments(
video_path=args.video,
output_dir=args.output,
frame_interval=args.interval,
zoom_level=args.zoom,
crops_per_frame=args.crops,
manual_crop=args.manual,
crop_x=args.crop_x,
crop_y=args.crop_y,
segment_size=args.segment_size,
overlap=args.overlap,
)
except Exception as e:
print(f"An error occurred: {e}") |