Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I convert RGB to CMYK and vice versa in python?

Tags:

python

colors

If I had a RGB decimal such as 255, 165, 0, what could I do to convert this to CMYK?

For example:

>>> red, green, blue = 255, 165, 0
>>> rgb_to_cmyk(red, green, blue)
(0, 35, 100, 0)
like image 839
Hairr Avatar asked Dec 30 '12 04:12

Hairr


People also ask

How do I convert RGB to CMYK?

To create a new CMYK document in Photoshop, go to File > New. In the New Document window, simply switch the color mode to CMYK (Photoshop defaults to RGB). If you're wanting to convert an image from RGB to CMYK, then simply open the image in Photoshop. Then, navigate to Image > Mode > CMYK.

How do I convert RGB to CMYK without Adobe?

Using GIMP If you are looking for a way to convert RGB to CMYK without photoshop, you can use the GIMP open-source editing tool. Like the online converter, GIMP is a free tool that can change the color space of your file without license purchases.

What programs convert RGB to CMYK?

To put it simply, Adobe design tools can convert RGB to CMYK and are the most commonly used design software. Microsoft Publisher, Corel Draw and Quark Xpress can also convert from RGB to CMYK.


Video Answer


1 Answers

Here's a Python port of a Javascript implementation.

RGB_SCALE = 255
CMYK_SCALE = 100


def rgb_to_cmyk(r, g, b):
    if (r, g, b) == (0, 0, 0):
        # black
        return 0, 0, 0, CMYK_SCALE

    # rgb [0,255] -> cmy [0,1]
    c = 1 - r / RGB_SCALE
    m = 1 - g / RGB_SCALE
    y = 1 - b / RGB_SCALE

    # extract out k [0, 1]
    min_cmy = min(c, m, y)
    c = (c - min_cmy) / (1 - min_cmy)
    m = (m - min_cmy) / (1 - min_cmy)
    y = (y - min_cmy) / (1 - min_cmy)
    k = min_cmy

    # rescale to the range [0,CMYK_SCALE]
    return c * CMYK_SCALE, m * CMYK_SCALE, y * CMYK_SCALE, k * CMYK_SCALE
like image 113
Mr Fooz Avatar answered Sep 19 '22 14:09

Mr Fooz