[英]How to convert bytes image from grayscale to BGR
I have this function that converts images to bytes and from bytes to np.array.我有这个 function 将图像转换为字节和从字节转换为 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但是当我传入 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
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.但是将灰度图像转换为 RGB 的方法是将
Image
object 转换。 And don't forget to use the correct typing hint for the function.并且不要忘记为 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]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.