基于OpenCV与Python的超声视频自动轮廓识别裁剪技术求助
Hey there! Let's tackle this ultrasound video cropping challenge together—those conical ultrasound regions can be tricky, but we can build a robust pipeline to auto-detect the region, crop it, and export standardized videos. Let's break this down step by step.
Step 1: Traverse All Video Files in a Folder
First, we'll use Python's os module to scan your target folder and grab all video files (adjust the extensions to match your files, like .mjpg, .mp4, etc.).
Step 2: Preprocess Frames to Reduce Noise & Enhance Contours
Ultrasound videos often have random noise, so we'll add preprocessing steps to clean up frames before contour detection:
- Convert frames to grayscale (simplifies contour detection)
- Apply median blur to reduce ultrasound-specific noise
- Use Canny edge detection to highlight the conical region's boundaries
Step 3: Detect the Conical Ultrasound Region
Since the ultrasound region is the largest distinct shape in the frame, we'll:
- Find all contours in the preprocessed frame
- Filter out small, irrelevant contours (keep the largest one, which should be the ultrasound cone)
- Get the bounding box of this contour to define our crop region
Step 4: Crop & Standardize Frame Size
Once we have the bounding box, crop the frame to that region, then resize it to your desired fixed dimensions using cv2.resize().
Step 5: Export the Processed Video
Use cv2.VideoWriter to save the cropped/standardized frames into a new video, matching the original video's frame rate for consistency.
Full Working Code Example
import cv2 import numpy as np import os def process_ultrasound_video(input_path, output_path, target_size=(640, 480)): # Initialize video capture cap = cv2.VideoCapture(input_path) if not cap.isOpened(): print(f"Error opening video file: {input_path}") return # Get original video properties fps = cap.get(cv2.CAP_PROP_FPS) # Initialize video writer (adjust codec based on your output format) fourcc = cv2.VideoWriter_fourcc(*'MJPG') out = cv2.VideoWriter(output_path, fourcc, fps, target_size) while cap.isOpened(): ret, frame = cap.read() if not ret: break # Step 1: Preprocess the frame gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) blurred = cv2.medianBlur(gray, 5) # Reduce ultrasound noise edges = cv2.Canny(blurred, 50, 150) # Adjust thresholds if needed # Step 2: Find contours and select the largest one (ultrasound cone) contours, _ = cv2.findContours(edges.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) if contours: largest_contour = max(contours, key=cv2.contourArea) x, y, w, h = cv2.boundingRect(largest_contour) # Step 3: Crop and standardize frame cropped_frame = frame[y:y+h, x:x+w] standardized_frame = cv2.resize(cropped_frame, target_size) # Write frame to output video out.write(standardized_frame) # Optional preview (press ESC to close early) cv2.imshow('Processed Preview', standardized_frame) if cv2.waitKey(1) & 0xFF == 27: break # Cleanup resources cap.release() out.release() cv2.destroyAllWindows() def process_all_videos_in_folder(input_folder, output_folder, target_size=(640, 480)): # Create output folder if it doesn't exist os.makedirs(output_folder, exist_ok=True) # Supported video extensions - add more if needed video_extensions = ('.mjpg', '.mp4', '.avi', '.mov') for filename in os.listdir(input_folder): if filename.lower().endswith(video_extensions): input_path = os.path.join(input_folder, filename) output_path = os.path.join(output_folder, f"processed_{filename}") print(f"Processing: {filename}") process_ultrasound_video(input_path, output_path, target_size) # Example usage if __name__ == "__main__": INPUT_FOLDER = "path/to/your/ultrasound_videos" OUTPUT_FOLDER = "path/to/save/processed_videos" TARGET_SIZE = (640, 480) # Adjust to your desired fixed size process_all_videos_in_folder(INPUT_FOLDER, OUTPUT_FOLDER, TARGET_SIZE)
Key Adjustments for Your Use Case
- Canny Thresholds: If the contour detection isn't picking up the cone correctly, tweak the
cv2.Canny(blurred, 50, 150)values (lower the first threshold for more edges, raise it to filter out noise). - Contour Filtering: If small irrelevant contours are still showing up, add a minimum area check:
if cv2.contourArea(largest_contour) > 10000:(adjust the number based on your video's resolution). - Codec Selection: If the output video won't save, try a different fourcc code (e.g.,
*'XVID'for AVI,*'mp4v'for MP4). - Rotated Cones: If your ultrasound cone is rotated, use
cv2.minAreaRect()instead ofcv2.boundingRect()to get a rotated bounding box, then perform a perspective transform to crop it—let me know if you need help with that!
内容的提问来源于stack exchange,提问作者Medomatto

