How to convert RGB to CMYK using OpenCV and NumPy

You can convert an image from RGB to CMYK using OpenCV Python by following the given steps. I highly recommend you get the “Computer Vision: Models, Learning, and Inference Book” to learn Computer Vision.

How to convert RGB to CMYK in OpenCV
How to convert RGB to CMYK in OpenCV

Step 1

Import the OpenCV and NumPy library. If OpenCV is not installed in your system then first install it using This Method.

import cv2
import numpy as np
#cv2 is used for OpenCV library

Step 2

Now read the image from the location. In my case “F:\\AiHints” is the location and “apple.jpg” is the name of the image. Change it according to your image location and name.

image = cv2.imread("C://AiHints//apple.jpg")
#imread is use to read an image from a location

Step 3

Now convert the RGB image into CMYK using NumPy Library.

img = image.astype(np.float64)/255.
K = 1 - np.max(img, axis=2)
C = (1-img[...,2] - K)/(1-K)
M = (1-img[...,1] - K)/(1-K)
Y = (1-img[...,0] - K)/(1-K)

CMYK_image= (np.dstack((C,M,Y,K)) * 255).astype(np.uint8)

Step 4

Now display the original, and CMYK image using the following code.

cv2.imshow("Original Image", image)
cv2.imshow("CMYK Image", CMYK_image)

Step 5

waitKey() open the image for a specific time in milliseconds until you press any key. The function cv2.destroyAllWindows() will destroy all the windows that we created.

Original Image
CMYK Image

Leave a Comment

Your email address will not be published.