PIL rotate image colors (BGR -> RGB)

后端 未结 11 2196
深忆病人
深忆病人 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:01

    Just a quick footnote for anyone writing code that might have to deal with 4-channel images, and discovering that the simple numpy answer seems to be eating their alpha channel.

    np_image[:,:,[0,1,2]] = np_image[:,:,[2,1,0]]
    

    will preserve the alpha data if there is a fourth channel, whereas

    np_image = np_image[:,:,[2,1,0]]
    

    will overwrite the 4-channel image with only reversed 3-channel data. (And the even simpler numpy answer, img = img[:,:,::-1], will give you ARGB data, which would be bad, too. :)

提交回复
热议问题