{"record":{"id":"b98d1bed37802b2c","repo":"deepinsight/insightface","slug":"nv21-data-size-is-not-enough-expected-expected-s","errorCode":null,"errorMessage":"NV21 data size is not enough: expected {expected_size} bytes, actual {len(yuv)} bytes","messagePattern":"NV21 data size is not enough: expected (.+?) bytes, actual (.+?) bytes","errorType":"validation","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"cpp-package/inspireface/python/read_nv21.py","lineNumber":15,"sourceCode":"import cv2\nimport numpy as np\nfrom inspireface import ImageStream\nimport inspireface as isf\n\n\ndef read_nv21(file_path, width, height, rotate=0):\n    with open(file_path, 'rb') as f:\n        nv21_data = f.read()\n    \n    yuv = np.frombuffer(nv21_data, dtype=np.uint8)\n    \n    expected_size = width * height * 3 // 2\n    if len(yuv) < expected_size:\n        raise ValueError(f\"NV21 data size is not enough: expected {expected_size} bytes, actual {len(yuv)} bytes\")\n    \n    yuv_mat = np.zeros((height * 3 // 2, width), dtype=np.uint8)\n    yuv_mat[:] = yuv[:height * width * 3 // 2].reshape(height * 3 // 2, width)\n    \n    bgr_mat = cv2.cvtColor(yuv_mat, cv2.COLOR_YUV2BGR_NV21)\n    \n    # add reverse rotate\n    if rotate != 0:\n        # calculate reverse rotate angle\n        reverse_angle = (360 - rotate) % 360\n        \n        # select rotate method by angle\n        if reverse_angle == 90:\n            bgr_mat = cv2.rotate(bgr_mat, cv2.ROTATE_90_CLOCKWISE)\n        elif reverse_angle == 180:\n            bgr_mat = cv2.rotate(bgr_mat, cv2.ROTATE_180)\n        elif reverse_angle == 270:\n            bgr_mat = cv2.rotate(bgr_mat, cv2.ROTATE_90_COUNTERCLOCKWISE)","sourceCodeStart":1,"sourceCodeEnd":33,"githubUrl":"https://github.com/deepinsight/insightface/blob/7fadd420c2351d0ffa8cac403421c1a3ed733365/cpp-package/inspireface/python/read_nv21.py#L1-L33","documentation":"read_nv21 validates that the raw file holds at least width*height*3/2 bytes (Y plane + interleaved VU plane) before reshape and cv2.cvtColor(COLOR_YUV2BGR_NV21). If the buffer is smaller, conversion is impossible, so it raises this ValueError instead of producing garbage.","triggerScenarios":"Calling read_nv21(path, width, height) where the file has fewer bytes than width*height*3//2 — wrong width/height passed for the file, a truncated capture, or a file that is actually NV12/RGB/JPEG rather than NV21.","commonSituations":"Mismatch between camera capture resolution and the reader arguments, feeding an RGB or grayscale dump into the NV21 reader, truncated camera-HAL dumps, or buffers that lost the chroma planes during copy.","solutions":["Check the file size equals width*height*3//2 and fix width/height to match the actual capture resolution.","Confirm the data really is NV21 (Y plane then interleaved V/U), not NV12, RGB, or compressed.","If the file is truncated, re-capture the frame — do not pad, fix the producer side."],"exampleFix":"# before\nbgr = read_nv21('frame.nv21', 1080, 1920)  # ValueError: expected 3110400 bytes, actual 2073600\n\n# after\nimport os\nw, h = 1080, 1920\nassert os.path.getsize('frame.nv21') >= w * h * 3 // 2, 'truncated NV21 file'\nbgr = read_nv21('frame.nv21', w, h)","handlingStrategy":"validation","validationCode":"import os\nw, h = 1080, 1920\nassert os.path.getsize(path) >= w * h * 3 // 2, 'NV21 file too small for given width/height'","typeGuard":"def is_valid_nv21(buf: bytes, w: int, h: int) -> bool:\n    return isinstance(buf, (bytes, bytearray)) and len(buf) >= w * h * 3 // 2","tryCatchPattern":"try:\n    bgr = read_nv21(p, w, h)\nexcept ValueError as e:\n    if 'NV21 data size' in str(e):\n        raise RuntimeError(f'bad frame {p}: {e}') from e\n    raise","preventionTips":["Size-check buffers against w*h*3//2 before conversion.","Source capture resolution and reader args from one config constant."],"tags":["nv21","yuv","opencv","buffer-size","valueerror"],"backgroundTag":"yuv-buffer-size-mismatch","analyzedSha":"7fadd420c2351d0ffa8cac403421c1a3ed733365","analyzedAt":"2026-08-28T15:44:01.850Z","schemaVersion":2},"datasetVersion":"2026-08-28T16:17:29.566Z"}