您可以使用matplotlib.colors.hsv_to_rgb
而不是colorsys.hls_to_rgb
. 该matplotlib
功能大约快10倍!请参阅以下结果:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import hsv_to_rgb
import time
def Complex2HSV(z, rmin, rmax, hue_start=90):
# get amplidude of z and limit to [rmin, rmax]
amp = np.abs(z)
amp = np.where(amp < rmin, rmin, amp)
amp = np.where(amp > rmax, rmax, amp)
ph = np.angle(z, deg=1) + hue_start
# HSV are values in range [0,1]
h = (ph % 360) / 360
s = 0.85 * np.ones_like(h)
v = (amp -rmin) / (rmax - rmin)
return hsv_to_rgb(np.dstack((h,s,v)))
这是@nadapez选择答案的方法:
from colorsys import hls_to_rgb
def colorize(z):
r = np.abs(z)
arg = np.angle(z)
h = (arg + np.pi) / (2 * np.pi) + 0.5
l = 1.0 - 1.0/(1.0 + r**0.3)
s = 0.8
c = np.vectorize(hls_to_rgb) (h,l,s) # --> tuple
c = np.array(c) # --> array of (3,n,m) shape, but need (n,m,3)
c = c.swapaxes(0,2)
return c
用 1024*1024 2darray 测试两种方法的结果:
N=1024
x, y = np.ogrid[-4:4:N*1j, -4:4:N*1j]
z = x + 1j*y
t0 = time.time()
img = Complex2HSV(z, 0, 4)
t1 = time.time()
print "Complex2HSV method: "+ str (t1 - t0) +" s"
t0 = time.time()
img = colorize(z)
t1 = time.time()
print "colorize method: "+ str (t1 - t0) +" s"
我的旧笔记本电脑上的这个结果:
Complex2HSV method: 0.250999927521 s
colorize method: 2.03200006485 s