Skip to content

Commit 6971af2

Browse files
authored
feat: RGB to CMYK color converter (TheAlgorithms#10741)
* feat: code functional, commented, tested * fix: compering types, exception msg, line length * fix: type hints
1 parent b98312c commit 6971af2

File tree

1 file changed

+71
-0
lines changed

1 file changed

+71
-0
lines changed

conversions/rgb_cmyk_conversion.py

+71
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
def 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))
61+
m = round(100 * (1 - g - k) / (1 - k))
62+
y = round(100 * (1 - b - k) / (1 - k))
63+
k = round(100 * k)
64+
65+
return c, m, y, k
66+
67+
68+
if __name__ == "__main__":
69+
from doctest import testmod
70+
71+
testmod()

0 commit comments

Comments
 (0)