Skip to content Skip to sidebar Skip to footer

How To Convert A Rgb Image Into A Cmyk?

I want to convert a rgb image into cmyk. This is my code the first problem is, when I divide each pixel by 255 the value closes to zero so the result image is approximately black!

Solution 1:

You can let PIL/Pillow do it for you like this:

from PIL import Image

# Open image, convert to CMYK and save as TIF
Image.open('drtrump.jpg').convert('CMYK').save('result.tif')

If I use IPython, I can time loading, converting and saving that at 13ms in toto like this:

%timeit Image.open('drtrump.jpg').convert('CMYK').save('PIL.tif')
13.6 ms ± 627 µs per loop (mean ± std. dev. of7 runs, 100 loops each)

If you want to do it yourself by implementing your formula, you would be better off using vectorised Numpy rather than for loops. This takes 35ms.

#!/usr/bin/env python3

import cv2
import numpy as np

# Load image
bgr = cv2.imread('drtrump.jpg')

# Make float and divide by 255 to give BGRdash
bgrdash = bgr.astype(np.float)/255.

# Calculate K as (1 - whatever is biggest out of Rdash, Gdash, Bdash)
K = 1 - np.max(bgrdash, axis=2)

# Calculate C
C = (1-bgrdash[...,2] - K)/(1-K)

# Calculate M
M = (1-bgrdash[...,1] - K)/(1-K)

# Calculate Y
Y = (1-bgrdash[...,0] - K)/(1-K)

# Combine 4 channels into single image and re-scale back up to uint8
CMYK = (np.dstack((C,M,Y,K)) * 255).astype(np.uint8)

If you want to check your results, you need to be aware of a few things. Not all image formats can save CMYK, that's why I saved as TIFF. Secondly, your formula leaves all your values as floats in the range 0..1, so you probably want scale back up by multiplying by 255 and converting to uint8.

Finally, you can be assured of what the correct result is by simply using ImageMagick in the Terminal:

magick drtrump.jpg -colorspace CMYK result.tif

Solution 2:

You don't need to do CMYK = C + M + Y + K.

I don't know how to convert the 1 channel resulted image to 4 channel.

For ndim arrays you can use numpy.dstack. Documentation link.

Edit

The incorrect results are caused due to int division. You need to perform float division. One method to achieve that is to convert array B, G, and R to float

B = img[:, :, 0].astype(float) # float conversion, maybe we can do better. But this results in correct answerG = img[:, :, 1].astype(float) #R = img[:, :, 2].astype(float) #

Post a Comment for "How To Convert A Rgb Image Into A Cmyk?"