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?
But for PIL, the input is RGB, while it's BGR for cv2.
We can use cvtColor() method to convert a BGR image to RGB and vice-versa. Parameter: cv2. COLOR_BGR2RGB – BGR image is converted to RGB.
The parameter code when converting from RGB to BGR is cv2. COLOR_RGB2BGR . Use this when reading an image file as a PIL. Image , convert it to ndarray , and save it using OpenCV imwrite() .
What's the Difference between RGB versus BGR? The main difference between RGB versus BGR is the arrangement of the subpixels for Red, Green, and Blue. RGB is arranged like that, but BGR is essentially in reverse with no adverse effect on color vibrancy and accuracy.
I know it's an old question, but I had the same problem and solved it with:
img = img[:,:,::-1]
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With