﻿ Convert RGB to CMYK in Python | Adam Dimech's Coding Blog

Dear Internet Explorer user: Your browser is no longer supported

Please switch to a modern browser such as Microsoft Edge, Mozilla Firefox or Google Chrome to view this website's content.

# Convert RGB to CMYK in Python

Efficient Python code for taking a RGB image and converting it to CMYK before splitting the relevant channels out.

When conducting analysis of images, it may be useful to separate out individual channels from an image and examine them separately. The CMYK colour model is an additive model frequently used in the commercial printing industry. In my work with image analysis, I have found it useful to split and isolate CMYK channels.

CMYK stands for Cyan, Magenta, Yellow and Key (Black). Each of these channels can be isolated in Python with some relatively simple code. The mathematics for the channel conversions from RGB to CMYK are as follows:

$K = 1-max(R’,G’,B’)$
$C = \frac{(1-R’-K)}{1-K}$
$M = \frac{(1-G’-K)}{1-K}$
$Y = \frac{(1-B’-K)}{1-K}$

The numpy, matplotlib and OpenCV (cv2) modules are required for the following example script to work:

#!/usr/bin/python

import numpy as np
import matplotlib.pyplot as plt
import cv2

# Import image

# Create float
bgr = img.astype(float)/255.

# Extract channels
with np.errstate(invalid='ignore', divide='ignore'):
K = 1 - np.max(bgr, axis=2)
C = (1-bgr[...,2] - K)/(1-K)
M = (1-bgr[...,1] - K)/(1-K)
Y = (1-bgr[...,0] - K)/(1-K)

# Convert the input BGR image to CMYK colorspace
CMYK = (np.dstack((C,M,Y,K)) * 255).astype(np.uint8)

# Split CMYK channels
Y, M, C, K = cv2.split(CMYK)

np.isfinite(C).all()
np.isfinite(M).all()
np.isfinite(K).all()
np.isfinite(Y).all()

# Save channels
cv2.imwrite('C:/path/to/C.jpg', C)
cv2.imwrite('C:/path/to/M.jpg', M)
cv2.imwrite('C:/path/to/Y.jpg', Y)
cv2.imwrite('C:/path/to/K.jpg', K)

The code takes a RGB image, converts it to CMYK and splits the channels saving each as a greyscale image. Using the above code, this RGB image of a plant was converted into CMYK and the four channels split:

<a href="" title=""> <b> <blockquote cite=""> <code> <em> <i> <q cite=""> <strike> <strong>