简体   繁体   中英

How to convert bytes image from grayscale to BGR

I have this function that converts images to bytes and from bytes to np.array.

When I pass in grayscale images, I often end up with the below error.

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

but the error does not occur when I pass in RGB images

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

It seems you intended to do

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

But the way to convert a grayscale image to RGB is by converting the Image object. And don't forget to use the correct typing hint for the function.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM