You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python OpenCV提取视频中两条红线间的图像?

Got it! Let's tackle how to extract the regions between two red lines from your video. Since you already have edge detection working for the red lines, here's how to extend your code to grab those target regions:

Extract Regions Between Two Red Lines from Video

First, let's break down the core steps we'll add to your existing workflow:

  1. For each frame, detect the two red line edges and capture their key coordinates (e.g., y-values for horizontal lines, x-values for vertical lines).
  2. Validate we have exactly two distinct lines (to avoid errors from missing or extra lines).
  3. Crop the frame to the area sandwiched between these two lines.
  4. Save or process the cropped region as needed.

Here's the extended code built from your initial snippet:

import cv2
import numpy as np
import matplotlib.pyplot as plt

# Initialize video capture
video = cv2.VideoCapture("/home/ksourav/AGS/SampleVideos/Trail1.mp4")

# Define HSV color ranges for red (adjust these to match your video's red shade)
lower_red1 = np.array([0, 120, 70])
upper_red1 = np.array([10, 255, 255])
lower_red2 = np.array([170, 120, 70])
upper_red2 = np.array([180, 255, 255])

frame_counter = 0

while video.isOpened():
    ret, frame = video.read()
    if not ret:
        break  # Exit loop when video ends
    
    # Convert frame to HSV for better color-based detection
    hsv_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
    
    # Create combined mask for red color (covers both ends of HSV hue spectrum)
    red_mask1 = cv2.inRange(hsv_frame, lower_red1, upper_red1)
    red_mask2 = cv2.inRange(hsv_frame, lower_red2, upper_red2)
    full_red_mask = cv2.bitwise_or(red_mask1, red_mask2)
    
    # Run edge detection (your existing step)
    red_edges = cv2.Canny(full_red_mask, 50, 150)
    
    # Detect lines using Hough Transform (tweak params for your specific lines)
    detected_lines = cv2.HoughLinesP(
        red_edges,
        rho=1,
        theta=np.pi/180,
        threshold=50,
        minLineLength=100,
        maxLineGap=10
    )
    
    if detected_lines is not None:
        # Extract line positions (assuming horizontal lines; swap to x if vertical)
        line_y_positions = []
        for line in detected_lines:
            x1, y1, x2, y2 = line[0]
            # Average y-coordinates to get a single position for horizontal lines
            avg_y = (y1 + y2) // 2
            line_y_positions.append(avg_y)
        
        # Deduplicate and sort positions to get top and bottom lines
        unique_line_positions = sorted(list(set(line_y_positions)))
        
        # Only proceed if we have exactly two lines
        if len(unique_line_positions) == 2:
            top_line_y = min(unique_line_positions)
            bottom_line_y = max(unique_line_positions)
            # Crop the region between the two lines
            cropped_region = frame[top_line_y:bottom_line_y, :]
            
            # Save the cropped image (adjust path/filename as needed)
            cv2.imwrite(f"cropped_region_{frame_counter}.png", cropped_region)
            
            # Optional: Display the result in real-time
            cv2.imshow("Cropped Region", cropped_region)
    
    frame_counter += 1
    
    # Press 'q' to exit early
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

# Clean up resources
video.release()
cv2.destroyAllWindows()

Key Adjustments for Your Video:

  • Color Calibration: Tweak the HSV red ranges to match the exact shade of red in your video. You can use a simple HSV color picker tool to get precise values.
  • Line Detection Params: Adjust threshold, minLineLength, and maxLineGap in cv2.HoughLinesP() to ensure only your target red lines are detected. If your lines are vertical, modify the code to track x-coordinates instead of y.
  • Edge Case Handling: Add logic to skip frames where fewer than two lines are detected (e.g., print a warning or log the frame number for later review).
  • Fixed Lines Optimization: If your red lines don't move across frames, detect their positions once at the start and hardcode them—this will speed up processing significantly.

Pro Tip: To verify your mask is correctly isolating red lines, add a cv2.imshow("Red Mask", full_red_mask) line after creating the mask.

内容的提问来源于stack exchange,提问作者ksouravdas

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 09:06:27