简体   繁体   中英

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.

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. And I'm getting the output, but its in BGR format only.

Thanks in advance!

Have you tried using numpy as suggested here ?

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)

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