简体   繁体   English

如何在 Python 中使用 PIL 将 BGR 图像转换为 RGB 图像?

[英]How to convert BGR image to RGB image using PIL in Python?

I wanted to display the BGR image to RGB, so I followed one of the procedure mentioned in this PIL rotate image colors (BGR -> RGB) still I'm getting the BGR images.我想将 BGR 图像显示为 RGB,因此我遵循了此PIL 旋转图像颜色 (BGR -> RGB)中提到的程序之一,但我仍在获取 BGR 图像。

My code is:我的代码是:

i = 0
for i inrange(6):
  img = Image.fromarray(resizelist[val])
  im = img.convert("RGBA")
  resized_img = im.resize((200, 200),Image.ANTIALIAS)
  tkimage1 = ImageTk.PhotoImage(resized_img)
  myvar2 = Label(new, image=tkimage1)
  myvar2.image = tkimage1

Here resizelist[val] contains 70 images.这里resizelist[val]包含 70 张图像。 And I'm getting the output, but its in BGR format only.我得到了输出,但它只是 BGR 格式。

Thanks in advance!提前致谢!

Have you tried using numpy as suggested here ?您是否尝试过按照此处的建议使用 numpy ?

from PIL import Image
import numpy as np
import sys 

sub = Image.open(sys.argv[1])
sub = sub.convert("RGBA")
data = np.array(sub) 
red, green, blue, alpha = data.T 
data = np.array([blue, green, red, alpha])
data = data.transpose()
sub = Image.fromarray(data)

An shorter version would be:一个较短的版本是:

from PIL import Image
import numpy as np

path_to_image = 'path_to_image.png'

image_PIL_RGB = Image.open(path_to_image)
image_np_RGB = np.array(image_PIL_RGB)

image_np_BGR = np.flip(image_np_RGB ,-1)
image_PIL_BGR = Image.fromarray(image_np_BGR)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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