Is it possible to convert an RGBA image to BGRA without using the following code, i.e. without using opencv?
image = self.cv2.cvtColor(image, self.cv2.COLOR_RGBA2BGRA)
CodePudding user response:
You can convert an image from BGRA to RGBA with this line of code:
image[..., :3] = image[..., 2::-1]
Of course, it modifies the existing array rather than creating a new one (which is good if you don't plan on using the old one again as it's more efficient). Another way is image = image[..., [2,1,0,3]]
, but since it uses fancy indexing, rather than modifying the old array, it creates a copy of the old array which takes up more memory.
Using the same line of code again converts the image back from RGBA to BGRA.
CodePudding user response:
Like this with "fancy indexing":
# Make a dummy, random 4-channel image
RGBA = np.random.randint(0,256,(2,3,4), np.uint8)
In [3]: RGBA
Out[3]:
array([[[102, 204, 36, 128],
[178, 151, 166, 45],
[199, 49, 104, 98]],
[[ 79, 33, 223, 62],
[ 26, 34, 233, 254],
[ 62, 20, 57, 149]]], dtype=uint8)
# Convert RGBA to BGRA
BGRA = RGBA[..., [2,1,0,3]]
In [5]: BGRA
Out[5]:
array([[[ 36, 204, 102, 128],
[166, 151, 178, 45],
[104, 49, 199, 98]],
[[223, 33, 79, 62],
[233, 34, 26, 254],
[ 57, 20, 62, 149]]], dtype=uint8)
I think OpenCV likes its data contiguous, so if you get issues, use:
BGRA = RGBA[..., [2,1,0,3]].copy()