Changing the Image color space using OpenCV and Python

I have started working on Image dataset for one of my projects and one who is working or worked on image dataset can tell how much important is image processing. Like any other dataset type, the image data also need to be converted into computer understandable format, it also has noise which needs to be removed before feature extraction for any application. I use OpenCV for all image-related processing and feature extractions.

In this post, we will look into the method of changing the colorspaces of an image using OpenCV and Python.

To work with OpenCV first we need to install that. To install OpenCV using pip we need to execute below command on your command prompt.

python -m pip install opencv-python

To show how we can change colorspace we need an input image on which we will experiment. 
download the image from : 
https://www.pexels.com/photo/beautiful-bright-colorful-colourful-190195/

cv_sample


       
import numpy as np
import cv2

#Reading image using OpenCV imread function
image = cv2.imread('cv_sample.jpeg')


#using while loop to run for indenfitnite time and stop when key 'q' is pressed from keyboard
while(1):
    
    
    # using cvtColor to change the color of the image 
    gray = cv2.cvtColor(image,  cv2.COLOR_BGR2GRAY)
    hsv = cv2.cvtColor(image,  cv2.COLOR_BGR2HSV)
    rgb = cv2.cvtColor(image,  cv2.COLOR_BGR2RGB)
    cv2.imshow('Original',image)
    cv2.imshow('gray',gray)
    cv2.imshow('hsv',hsv)
    cv2.imshow('rgb',rgb)
    if cv2.waitKey(0) & 0xFF == ord('q'):
        break

cv2.destroyAllWindows()


I have used the cvtColor method which converts the image from one color space to another and in our code, we have converted the image from the default color space which BGR to the formats like HSV, gray, RGB. I used cv2.imshow method to display the color space converted image. We can save the image usig using cv2.imwrite() method

Note: There are more than 150 color-space conversion methods available in OpenCV.

Try to run this code with sample image provided and please let me know if you have face any issue or you can share your finding in the comments.



You Might Also Like

0 comments