How to slice an image into red, green and blue channels with misc.imread

前端 未结 2 1766
滥情空心
滥情空心 2021-02-08 21:48

I am trying to slice an image into RGB and I have a problem with plotting these images. I obtain all images from a certain folder with this function:

def get_im         


        
2条回答
  •  说谎
    说谎 (楼主)
    2021-02-08 22:34

    So, you want to show in different colors the different RGB channels of an image...

    import matplotlib.pyplot as plt
    from matplotlib.cbook import get_sample_data
    
    image = plt.imread(get_sample_data('grace_hopper.jpg'))
    
    titles = ['Grace Hopper', 'Red channel', 'Green channel', 'Blue channel']
    cmaps = [None, plt.cm.Reds_r, plt.cm.Greens_r, plt.cm.Blues_r]
    
    fig, axes = plt.subplots(1, 4, figsize=(13,3))
    objs = zip(axes, (image, *image.transpose(2,0,1)), titles, cmaps)
    
    for ax, channel, title, cmap in objs:
        ax.imshow(channel, cmap=cmap)
        ax.set_title(title)
        ax.set_xticks(())
        ax.set_yticks(())
    
    plt.savefig('RGB1.png')
    

    Note that when you have a dark room with a red pen on a dark table, if you turn on a red lamp you percept the pen as almost white...

    Another possibility is to create a different image for each color, with the pixel values for the other colors turned to zero. Starting from where we left we define a function to extract a channel into an otherwise black image

    ...
    from numpy import array, zeros_like
    def channel(image, color):
        if color not in (0, 1, 2): return image
        c = image[..., color]
        z = zeros_like(c)
        return array([(c, z, z), (z, c, z), (z, z, c)][color]).transpose(1,2,0)
    

    and finally use it...

    colors = range(-1, 3)
    fig, axes = plt.subplots(1, 4, figsize=(13,3))
    objs = zip(axes, titles, colors)
    for ax, title, color in objs:
        ax.imshow(channel(image, color))
        ax.set_title(title)
        ax.set_xticks(())
        ax.set_yticks(())
    
    plt.savefig('RGB2.png')
    

    I can't tell which is the version that I like better, perhaps the 1st one is looking more realistic to me (maybe it looks less artificial) but it's quite subjective...

提交回复
热议问题