{"record":{"id":"ee03aa933fef37a7","repo":"opendatalab/MinerU","slug":"invalid-image-mode-please-provide-rgb-or-bgr","errorCode":null,"errorMessage":"Invalid image mode. Please provide 'rgb' or 'bgr'.","messagePattern":"Invalid image mode\\. Please provide 'rgb' or 'bgr'\\.","errorType":"validation","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"mineru/utils/span_pre_proc.py","lineNumber":666,"sourceCode":"\n    del span['chars']\n\n\ndef calculate_contrast(img, img_mode) -> float:\n    \"\"\"\n    计算给定图像的对比度。\n    :param img: 图像，类型为numpy.ndarray\n    :Param img_mode = 图像的色彩通道，'rgb' 或 'bgr'\n    :return: 图像的对比度值\n    \"\"\"\n    if img_mode == 'rgb':\n        # 将RGB图像转换为灰度图\n        gray_img = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)\n    elif img_mode == 'bgr':\n        # 将BGR图像转换为灰度图\n        gray_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n    else:\n        raise ValueError(\"Invalid image mode. Please provide 'rgb' or 'bgr'.\")\n\n    # 计算均值和标准差\n    mean_value = np.mean(gray_img)\n    std_dev = np.std(gray_img)\n    # 对比度定义为标准差除以平均值（加上小常数避免除零错误）\n    contrast = std_dev / (mean_value + 1e-6)\n    # logger.debug(f\"contrast: {contrast}\")\n    return round(contrast, 2)\n","sourceCodeStart":648,"sourceCodeEnd":675,"githubUrl":"https://github.com/opendatalab/MinerU/blob/4fe4bde114a23ee5dd637eae99b767f4669bf58c/mineru/utils/span_pre_proc.py#L648-L675","documentation":"Raised by MineRU's image contrast helper (calculate_contrast in span_pre_proc) when img_mode is neither 'rgb' nor 'bgr'. The function converts the input numpy image to grayscale via OpenCV and must know the channel order to pick COLOR_RGB2GRAY vs COLOR_BGR2GRAY; any other string (or a defaulted None) cannot be mapped. The mode is a caller-supplied convention flag, not derived from the array itself.","triggerScenarios":"Calling calculate_contrast(img, img_mode=...) with values like 'RGB' (case matters), 'gray', None, or omitting an explicit value in wrapper code whose default is not one of the two literals. Common with images loaded by PIL (RGB world) passed with a BGR habit from OpenCV code, or vice versa — though swapped-but-valid modes silently skew results rather than raise.","commonSituations":"Wrapper code copies an OpenCV BGR default while feeding PIL-loaded images; an uppercase or abbreviated mode string ('RGB', 'R') is passed; a config-driven pipeline forwards an arbitrary colorspace name ('gray', 'yuv') into a function that only understands the two grayscale-conversion orders.","solutions":["Pass exactly 'rgb' or 'bgr' (lowercase) matching how the array was actually produced: 'bgr' for cv2.imread, 'rgb' for PIL.Image → numpy.","Normalize external inputs: img_mode = img_mode.strip().lower() and validate against {'rgb','bgr'} before calling.","If your images are grayscale (2-D arrays), convert appropriately upstream — this helper only accepts 3-channel orders."],"exampleFix":"# before\nimg = np.array(Image.open(p))          # RGB channels\ncontrast = calculate_contrast(img, img_mode='RGB')  # ValueError\n\n# after\nimg = np.array(Image.open(p))\ncontrast = calculate_contrast(img, img_mode='rgb')","handlingStrategy":"type-guard","validationCode":"IMG_MODES = {'rgb', 'bgr'}\nimg_mode = 'rgb' if loaded_with_pil else 'bgr'\nassert img_mode in IMG_MODES","typeGuard":"from typing import Literal, TypeGuard\nImgMode = Literal['rgb', 'bgr']\n\ndef is_img_mode(v: object) -> TypeGuard[ImgMode]:\n    return isinstance(v, str) and v in ('rgb', 'bgr')","tryCatchPattern":"try:\n    contrast = calculate_contrast(img, img_mode=img_mode)\nexcept ValueError as e:\n    if 'Invalid image mode' in str(e):\n        raise TypeError(f'img_mode must be rgb|bgr, got {img_mode!r}') from e\n    raise","preventionTips":["Normalize the mode once at the boundary: img_mode = img_mode.strip().lower().","Constrain the parameter with Literal['rgb','bgr'] typing so IDEs and mypy catch bad literals.","Standardize on one loading convention (e.g. always cv2.imread → 'bgr') across the pipeline to avoid mixed conventions."],"tags":["image-processing","validation","opencv","mineru"],"backgroundTag":null,"analyzedSha":"4fe4bde114a23ee5dd637eae99b767f4669bf58c","analyzedAt":"2026-08-14T21:29:18.456Z","schemaVersion":2},"datasetVersion":"2026-08-15T22:17:37.221Z"}