Python-是否有函数或公式来查找rgb代码的互补色?
作者:互联网
我试图在Python 3中找到一个好的公式来计算rgb代码的互补色,例如. a = b的互补.有没有办法做到这一点?
解决方法:
以下是如何直接计算RGB颜色的补码.它给出了与使用colorsys的算法相同的结果,如Iva Klass的答案所示,但在我的测试中,它的速度提高了约50%.请注意,它适用于任何RGB方案,RGB组件是整数还是浮点数无关紧要(只要每个组件使用相同的范围!).
函数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()
输入图像
输出图像
这是一个Numpy版本的complement_image.在我的机器上,它处理“眼镜”图像的速度比前一版本快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)
标签:python-3-5,python,rgb,colors 来源: https://codeday.me/bug/20191008/1870920.html