MCPcopy Create free account
hub / github.com/TheAlgorithms/Python / rgb_to_cmyk

Function rgb_to_cmyk

conversions/rgb_cmyk_conversion.py:1–65  ·  view source on GitHub ↗

Simple RGB to CMYK conversion. Returns percentages of CMYK paint. https://www.programmingalgorithms.com/algorithm/rgb-to-cmyk/ Note: this is a very popular algorithm that converts colors linearly and gives only approximate results. Actual preparation for printing requires adva

(r_input: int, g_input: int, b_input: int)

Source from the content-addressed store, hash-verified

1def rgb_to_cmyk(r_input: int, g_input: int, b_input: int) -> tuple[int, int, int, int]:
2 """
3 Simple RGB to CMYK conversion. Returns percentages of CMYK paint.
4 https://www.programmingalgorithms.com/algorithm/rgb-to-cmyk/
5
6 Note: this is a very popular algorithm that converts colors linearly and gives
7 only approximate results. Actual preparation for printing requires advanced color
8 conversion considering the color profiles and parameters of the target device.
9
10 >>> rgb_to_cmyk(255, 200, "a")
11 Traceback (most recent call last):
12 ...
13 ValueError: Expected int, found (<class 'int'>, <class 'int'>, <class 'str'>)
14
15 >>> rgb_to_cmyk(255, 255, 999)
16 Traceback (most recent call last):
17 ...
18 ValueError: Expected int of the range 0..255
19
20 >>> rgb_to_cmyk(255, 255, 255) # white
21 (0, 0, 0, 0)
22
23 >>> rgb_to_cmyk(128, 128, 128) # gray
24 (0, 0, 0, 50)
25
26 >>> rgb_to_cmyk(0, 0, 0) # black
27 (0, 0, 0, 100)
28
29 >>> rgb_to_cmyk(255, 0, 0) # red
30 (0, 100, 100, 0)
31
32 >>> rgb_to_cmyk(0, 255, 0) # green
33 (100, 0, 100, 0)
34
35 >>> rgb_to_cmyk(0, 0, 255) # blue
36 (100, 100, 0, 0)
37 """
38
39 if (
40 not isinstance(r_input, int)
41 or not isinstance(g_input, int)
42 or not isinstance(b_input, int)
43 ):
44 msg = f"Expected int, found {type(r_input), type(g_input), type(b_input)}"
45 raise ValueError(msg)
46
47 if not 0 <= r_input < 256 or not 0 <= g_input < 256 or not 0 <= b_input < 256:
48 raise ValueError("Expected int of the range 0..255")
49
50 # changing range from 0..255 to 0..1
51 r = r_input / 255
52 g = g_input / 255
53 b = b_input / 255
54
55 k = 1 - max(r, g, b)
56
57 if k == 1: # pure black
58 return 0, 0, 0, 100
59
60 c = round(100 * (1 - r - k) / (1 - k))

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected