我试图在 Python 3 中找到一个很好的公式来计算 rgb 代码的互补色,例如。 a = b 的互补。有什么办法吗?
最佳答案
下面是如何直接计算 RGB 颜色的补色。它给出了与使用 colorsys
的算法相同的结果,如 Iva Klass 的回答所示,但在我的测试中它快了大约 50%。请注意,它适用于任何 RGB 方案,RGB 分量是整数还是 float 并不重要(只要每个分量使用相同的范围!)。
hilo
函数实现了一个简单的 sorting network对 RGB 分量进行排序。
# Sum of the min & max of (a, b, c)
def hilo(a, b, c):
if c < b: b, c = c, b
if b < a: a, b = b, a
if c < b: b, c = c, b
return a + c
def complement(r, g, b):
k = hilo(r, g, b)
return tuple(k - u for u in (r, g, b))
这是一个简短的演示,使用 PIL/Pillow。
#!/usr/bin/env python3
''' Complement the colours in a RGB image
Written by PM 2Ring 2016.10.08
'''
import sys
from PIL import Image
# Sum of the min & max of (a, b, c)
def hilo(a, b, c):
if c < b: b, c = c, b
if b < a: a, b = b, a
if c < b: b, c = c, b
return a + c
def complement(r, g, b):
k = hilo(r, g, b)
return tuple(k - u for u in (r, g, b))
def complement_image(iname, oname):
print('Loading', iname)
img = Image.open(iname)
#img.show()
size = img.size
mode = img.mode
in_data = img.getdata()
print('Complementing...')
out_img = Image.new(mode, size)
out_img.putdata([complement(*rgb) for rgb in in_data])
out_img.show()
out_img.save(oname)
print('Saved to', oname)
def main():
if len(sys.argv) == 3:
complement_image(*sys.argv[1:])
else:
fmt = 'Complement colours.\nUsage: {} input_image output_image'
print(fmt.format(sys.argv[0]))
if __name__ == '__main__':
main()
输入图片
输出图片
这是 complement_image
的 Numpy 版本。在我的机器上,它处理“眼镜”图像的速度比以前的版本快 3.7 倍。
import numpy as np
def complement_image(iname, oname):
print('Loading', iname)
img = Image.open(iname)
#img.show()
in_data = np.asarray(img)
#print(in_data.shape)
print('Complementing...')
lo = np.amin(in_data, axis=2, keepdims=True)
hi = np.amax(in_data, axis=2, keepdims=True)
out_data = (lo + hi) - in_data
out_img = Image.fromarray(out_data)
#out_img.show()
out_img.save(oname)
print('Saved to', oname)
这是一个使用 scikit-image 的简短演示(和 Numpy)在感知上更统一的 CIELuv 色彩空间中创建互补色。
from skimage.color import rgb2luv, luv2rgb
from skimage.util import img_as_ubyte
luv_data = rgb2luv(in_data) * (1, -1, -1)
out_data = img_as_ubyte(luv2rgb(luv_data))
关于Python-是否有函数或公式来查找 rgb 代码的互补色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40233986/