这是直接计算RGB颜色补数的方法。它给出的结果与
colorsysIva Klass的答案中使用的算法相同
,但在我的测试中,速度提高了约50%。请注意,它适用于任何RGB方案,无论RGB分量是整数还是浮点数都没有关系(只要每个分量使用相同的范围!)。
该函数
hilo实现了一个简单的排序网络,以对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 + cdef 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 sysfrom 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 + cdef 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 npdef 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)


