1. Home
  2. Docs
  3. Computer Vision
  4. Introduction to OpenCV
  5. Opening Image Files with ...
  6. Change of color space in OpenCV

Change of color space in OpenCV

Conversion code can be used to change the color space

To transform the color from BGR to RGB cvtColor() function is used

fix_img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
  • The cvtColor function in OpenCV converts images from one color space to another.
  • The name cvtColor is a shorthand for “convert color.”

Displaying the image in OpenCV

plt.imshow(fix_img)

To transform the color from BGR to Grey

imgG = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
plt.imshow(imgG, cmap='gray')

Loading the grey scale image  in OpenCV

Converting color space of image at the time of reading

img_gray = cv2.imread("parrot.jpg",cv2.IMREAD_GRAYSCALE)
img_gray.shape
Good to Know
  • cv2.IMREAD_GRAYSCALE is a flag used with the cv2.imread function in OpenCV to specify that an image should be read in grayscale mode.
  • When this flag is used, OpenCV reads the image and converts it to a single-channel grayscale image immediately, instead of reading it in its original color format.

Finding max and min pixels in OpenCV

img_gray

The minimum value in the image

img_gray.min()

The maximum value in the image

img_gray.max()

Displaying the images in OpenCV

The default color value that imshow() uses is virdis, which takes darker values and shows them as bluish and takes lighter values and shows them as yellowish green

plt.imshow(img_gray)
Good to Know
To overcome this, use cmap
plt.imshow(img_gray,cmap='gray')

Save the image in OpenCV

Save the image using imwrite( )

The input is the path of the image file and the image array

cv2.imwrite('GreyParrot.jpg',imgG)

Slice Operation to extract different channels 

Slicing selects each row and column, the final index selects the color channel

Baboon_ = cv2.imread('Baboon.jpg')
blue, green, red = Baboon_[:,:,0],Baboon_[:,:,1],Baboon_[:,:,2]
plt.imshow(blue,cmap="gray")
plt.imshow(green,cmap="gray")
plt.imshow(red,cmap="gray")

Loading

Views: 1

How can we help?

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments