如何将字节图像从灰度转换为 BGR

时间:2021-05-11 00:38:06

标签: python matplotlib opencv-python bytesio

我有这个函数可以将图像转换为字节,并将字节转换为 np.array。

当我传入灰度图像时,经常会出现以下错误。

open_cv_image = np.array(image) IndexError: too many indices for array: array is 2-dimensional, but 3 were indexed

但是当我传入RGB图像时不会发生错误

def read_imagefile(file) -> Image.Image:
    image = Image.open(BytesIO(file))
    open_cv_image = np.array(image)
    print(open_cv_image.shape())
    if open_cv_image.shape[-1] > 2:
        open_cv_image = open_cv_image[:, :, ::-1].copy() # Convert RGB to BGR
    else:
        open_cv_image =   cv2.merge((open_cv_image, open_cv_image, open_cv_image)).copy() #cv2.cvtColor(open_cv_image, cv2.COLOR_GRAY2BGR)
    return open_cv_image

1 个答案:

答案 0 :(得分:0)

看来你打算这样做

# this
if len(open_cv_image.shape) > 2:
# instead of this
if open_cv_image.shape[-1] > 2:

但是将灰度图像转换为 RGB 的方法是转换 Image 对象。并且不要忘记为函数使用正确的输入提示。

def read_imagefile(file) -> np.ndarray:
    img = Image.open(BytesIO(file))
    if img.mode == 'L':
        img = img.convert('RGB')
    return np.array(img)[...,::-1]