-215 opencv data_error ai_generated true

cv::error: (-215:Assertion failed) !buf.empty() && buf.data != NULL in function 'cv::imdecode'

ID: opencv/io-imdecode-corrupt-data

Also available as: JSON · Markdown · 中文
90%Fix Rate
87%Confidence
1Evidence
2024-05-18First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
4.7.0 active
4.8.0 active
4.9.0 active

Root Cause

The input buffer to imdecode is empty or contains corrupt image data that cannot be decoded.

generic

中文

imdecode 的输入缓冲区为空或包含无法解码的损坏图像数据。

Official Documentation

https://docs.opencv.org/4.x/d4/da8/group__imgcodecs.html#ga26a67788faa58ade337f8d28ba0eb19e

Workarounds

  1. 95% success Validate the buffer before decoding: check that buf.size() > 0 and optionally check the first few bytes for a valid image signature (e.g., JPEG: 0xFF 0xD8, PNG: 0x89 0x50). Example in C++: if (buf.size() < 4 || buf[0] != 0xFF || buf[1] != 0xD8) { /* handle error */ }.
    Validate the buffer before decoding: check that buf.size() > 0 and optionally check the first few bytes for a valid image signature (e.g., JPEG: 0xFF 0xD8, PNG: 0x89 0x50). Example in C++: if (buf.size() < 4 || buf[0] != 0xFF || buf[1] != 0xD8) { /* handle error */ }.
  2. 85% success If reading from a network stream, use a robust HTTP client that checks Content-Length and verifies the response body is complete before passing to imdecode.
    If reading from a network stream, use a robust HTTP client that checks Content-Length and verifies the response body is complete before passing to imdecode.

中文步骤

  1. Validate the buffer before decoding: check that buf.size() > 0 and optionally check the first few bytes for a valid image signature (e.g., JPEG: 0xFF 0xD8, PNG: 0x89 0x50). Example in C++: if (buf.size() < 4 || buf[0] != 0xFF || buf[1] != 0xD8) { /* handle error */ }.
  2. If reading from a network stream, use a robust HTTP client that checks Content-Length and verifies the response body is complete before passing to imdecode.

Dead Ends

Common approaches that don't work:

  1. Attempting to decode a buffer read from a file that was truncated mid-write 90% fail

    Truncated data is still non-empty but corrupt; imdecode will fail silently or with assertion error.

  2. Passing a buffer that was decoded from base64 without proper validation 85% fail

    Base64 decoding may produce empty or invalid binary data if the input string is malformed.