mathplotlib imshow complex 2D array

后端 未结 4 1800
心在旅途
心在旅途 2021-02-05 16:32

Is there any good way how to plot 2D array of complex numbers as image in mathplotlib ?

It makes very much sense to map magnitude of complex number as \"brightness\" or

4条回答
  •  醉酒成梦
    2021-02-05 17:19

    You can use matplotlib.colors.hsv_to_rgb instead of colorsys.hls_to_rgb. The matplotlib function is about 10 times faster! See the results below:

    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)))
    

    here is the method of picked answer by @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
    

    Testing the results from the two method with 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"
    

    This result on my old laptop:

    Complex2HSV method: 0.250999927521 s
    colorize method: 2.03200006485 s
    

提交回复
热议问题