PIL rotate image colors (BGR -> RGB)

后端 未结 11 2186
深忆病人
深忆病人 2020-11-29 21:21

I have an image where the colors are BGR. How can I transform my PIL image to swap the B and R elements of each pixel in an efficient manner?

相关标签:
11条回答
  • 2020-11-29 22:08

    Just to add a more up to date answer:

    With the new cv2 interface images loaded are now numpy arrays automatically.
    But openCV cv2.imread() loads images as BGR while numpy.imread() loads them as RGB.

    The easiest way to convert is to use openCV cvtColor.

    import cv2
    srcBGR = cv2.imread("sample.png")
    destRGB = cv2.cvtColor(srcBGR, cv2.COLOR_BGR2RGB)
    
    0 讨论(0)
  • 2020-11-29 22:10

    You should be able to do this with the ImageMath module.

    Edit:

    Joe's solution is even better, I was overthinking it. :)

    0 讨论(0)
  • 2020-11-29 22:14

    I know it's an old question, but I had the same problem and solved it with:

    img = img[:,:,::-1]
    
    0 讨论(0)
  • 2020-11-29 22:15

    This was my best answer. This does, by the way, work with Alpha too.

    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)
    
    0 讨论(0)
  • 2020-11-29 22:17
    import cv2
    srcBGR = cv2.imread("sample.png")
    destRGB = cv2.cvtColor(srcBGR,cv2.COLOR_BGR2RGB)
    

    Just to clarify Martin Beckets solution, as I am unable to comment. You need cv2. in front of the color constant.

    0 讨论(0)
提交回复
热议问题