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

如何用OpenCV将ROI以外区域填充为指定颜色(矩形ROI场景)

How to Fill Areas Outside ROI with a Specified Color in OpenCV

Hey there! Let's break down how to handle both of your ROI-related filling tasks using OpenCV. We'll cover both a general solution for any custom-shaped ROI, and a simpler approach specifically for rectangular ROIs.

General Case: Fill Outside Custom ROI with a Specified Color

If your ROI isn't a rectangle (e.g., a polygon or irregular shape), here's a reliable method:

  1. Create a blank image filled entirely with your desired color.
  2. Generate a mask that marks the ROI area.
  3. Copy the original image's pixels within the ROI onto the colored blank image.

Here's the Python code to implement this:

import cv2
import numpy as np

# Load your input image
img = cv2.imread("your_image_path.jpg")
if img is None:
    raise ValueError("Could not load image! Check the file path.")

# Define your custom ROI (example: a quadrilateral; adjust the points to match your ROI)
roi_points = np.array([[60, 60], [220, 70], [210, 230], [50, 220]], dtype=np.int32)
# Specify the fill color (OpenCV uses *BGR* format: e.g., red = (0, 0, 255), blue = (255, 0, 0))
fill_color = (0, 0, 255)

# Step 1: Create a base image filled with the target color
filled_img = np.full_like(img, fill_color)

# Step 2: Create a mask where the ROI is white (255) and background is black (0)
roi_mask = np.zeros(img.shape[:2], dtype=np.uint8)
cv2.fillPoly(roi_mask, [roi_points], 255)

# Step 3: Copy original ROI pixels into the filled image
filled_img[roi_mask == 255] = img[roi_mask == 255]

# Display and save the result
cv2.imshow("ROI Outside Filled", filled_img)
cv2.waitKey(0)
cv2.destroyAllWindows()
# cv2.imwrite("result.jpg", filled_img)

Key notes:

  • Make sure your roi_points are formatted as a numpy array with int32 dtype.
  • Remember OpenCV uses BGR color space, not RGB, so adjust your color values accordingly.

Special Case: Fill Outside Rectangular ROI with Black

For rectangular ROIs, we can skip the mask step and use array slicing for a faster, simpler solution. Here are two ways to do it:

Method 1: Create a new black image and paste the ROI

import cv2
import numpy as np

img = cv2.imread("your_image_path.jpg")
if img is None:
    raise ValueError("Could not load image! Check the file path.")

# Define your rectangular ROI: (x1, y1) = top-left corner, (x2, y2) = bottom-right corner
x1, y1 = 50, 50
x2, y2 = 200, 200

# Create a fully black image with the same dimensions as the original
black_bg_img = np.zeros_like(img)
# Paste the rectangular ROI from the original image onto the black background
black_bg_img[y1:y2, x1:x2] = img[y1:y2, x1:x2]

# Display the result
cv2.imshow("Rectangular ROI on Black Background", black_bg_img)
cv2.waitKey(0)
cv2.destroyAllWindows()

Method 2: Modify the original image directly

If you prefer to alter the original image (make a copy first to avoid overwriting the original!), you can set the areas outside the rectangle to black:

img_copy = img.copy()

# Set areas outside the rectangle to black
img_copy[:y1, :] = 0  # Area above the ROI
img_copy[y2:, :] = 0  # Area below the ROI
img_copy[y1:y2, :x1] = 0  # Area to the left of the ROI
img_copy[y1:y2, x2:] = 0  # Area to the right of the ROI

cv2.imshow("Modified Original Image", img_copy)
cv2.waitKey(0)
cv2.destroyAllWindows()

Important reminder: When using slicing, OpenCV uses (y, x) order for array indexing, so the first slice is the y-range (vertical) and the second is the x-range (horizontal).

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.06 23:13:10