opencv assertion_error ai_generated partial

cv::error: (-215:Assertion failed) total() == 0 || data != NULL in function 'Mat::create'

ID: opencv/core-mat-initialization-size-overflow

Also available as: JSON · Markdown · 中文
80%Fix Rate
84%Confidence
1Evidence
2023-09-05First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
4.5.5 active
4.6.0 active
4.7.0 active
4.8.1 active
4.9.0 active

Root Cause

Creating a cv::Mat with extremely large dimensions (e.g., width or height exceeding memory limits) causes memory allocation failure or overflow, leaving data pointer null.

generic

中文

创建具有极大尺寸(例如宽度或高度超过内存限制)的 cv::Mat 会导致内存分配失败或溢出,使数据指针为 null。

Official Documentation

https://docs.opencv.org/4.x/d3/d63/classcv_1_1Mat.html

Workarounds

  1. 90% success Validate dimensions before creating the matrix: if (width <= 0 || height <= 0 || width > 10000 || height > 10000) { /* handle error */ }
    Validate dimensions before creating the matrix: if (width <= 0 || height <= 0 || width > 10000 || height > 10000) { /* handle error */ }
  2. 85% success Use cv::Mat::reshape or tiling to process large images in chunks, e.g., cv::Mat tile = img(cv::Rect(0, 0, 1000, 1000));
    Use cv::Mat::reshape or tiling to process large images in chunks, e.g., cv::Mat tile = img(cv::Rect(0, 0, 1000, 1000));

中文步骤

  1. Validate dimensions before creating the matrix: if (width <= 0 || height <= 0 || width > 10000 || height > 10000) { /* handle error */ }
  2. Use cv::Mat::reshape or tiling to process large images in chunks, e.g., cv::Mat tile = img(cv::Rect(0, 0, 1000, 1000));

Dead Ends

Common approaches that don't work:

  1. Using cv::Mat::zeros with the same large size hoping it handles memory differently 100% fail

    zeros() internally calls create() with the same allocation logic.

  2. Reducing the number of channels to 1 to save memory 60% fail

    If the dimensions are already too large, reducing channels may not be enough; the size itself is the issue.

  3. Allocating on GPU using cv::cuda::GpuMat 75% fail

    GPU memory is even more limited; the same overflow can occur if dimensions exceed GPU memory.