Splitting Image using OpenCV in python

Question:

I have an image and want to split it into three RGB channel images using CV2 in python.

I also want good documentation where I can find all the functions of openCV, as I am completely new to OpenCV.

Asked By: Sagar

||

Answers:

That is as simple as loading an image using cv2.imread and then use cv2.split:

>>> import cv2
>>> import numpy as np
>>> img = cv2.imread("foo.jpg")
>>> b,g,r = cv2.split(img)

OpenCV documentation is available from docs.opencv.org

Answered By: jabaldonedo

As mentioned in the documentation tutorial, the cv2.split() is a costly operation in terms of performance(time) if you don’t want to operate on all the channels but only one/two, so the numpy indexing is preferred:

import cv2
import numpy as np
img = cv2.imread("foo.jpg")
b = img[:,:,0]
g = img[:,:,1]
r = img[:,:,2]

Remember that opencv reads the images as BGR instead of RGB

Edit: @Mitch McMabers, Thanks for pointing this out. Please use this method for max efficiency if you want to work on just one/two channels separately. If you want to operate on all three channels, access the channels using cv2.split() as mentioned in @jabaldeno’s answer.

Answered By: Mohit Motwani
  • b , g , r = cv2.split(img)
  • r , g , b = cv2.split(img)
    Are they the same ? Thanks so much
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.