IT博客汇
  • 首页
  • 精华
  • 技术
  • 设计
  • 资讯
  • 扯淡
  • 权利声明
  • 登录 注册

    用 python 实现数字图像位平面分解的方法

    Hacper\'s Blog发表于 2019-11-10 01:23:09
    love 0

    数字图像位平面分解

    位平面分解是数字图像处理的一种基本方法,我们用 $f(x,y)$来表示一幅数字图像,其中图像的第 $k$ 个颜色通道数据可以用 $f_{k}(x,y)$ 表示。以 RGB 图像为例,RGB 图像有 R、G、B 三个颜色通道,每个颜色通道都是具有 256 级灰度级别的灰度图像,也就是用 8 bit 大小来存储灰度图像的一个像素值。RGB 图像的一个像素值会占用 24 bit 大小,因为 RGB 有 3 个颜色通道。

    按照下面的公式对 RGB 的第 $k$ 个颜色通道进行位平面分解,一个颜色通道可以分解为 8 个位平面,每个位平面用二值图像来表示。

    $$f_{k}^{n}{(x,y)} = f_{k}(x,y) {\&} 2^{n} \quad (n = 0, \ldots, 7) $$

    用 python 来实现数字图像位平面分解

    使用 python 来做位平面分解需要安装 matplotlib、numpy、scikit-image 这三个库,可以使用 pip 命令来安装

    1
    
    pip install matplotlib numpy scikit-image
    

    安装好这三个库之后,导入需要用到的函数

    1
    2
    3
    
    import matplotlib.pyplot as plt
    import numpy as np
    from skimage import data
    

    编写一个函数用来做位平面分解,输入数据是一幅灰度图像

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    
    def bitplane(img:np.ndarray):
        shape = img.shape
        bits = np.unpackbits(img.reshape(-1, 1), axis=1)
        plt.figure(figsize=(8,4))
        for i in range(8):
            bit_plane_i = bits[:,i].reshape(shape)
            plt.subplot(2,4,i+1)
            plt.imshow(bit_plane_i, cmap="gray")
            plt.title('Bit Plane {}'.format(7-i))
            plt.axis('off')
    

    拿 scikit-image 中的一幅 RGB 图像来做测试,选用 coffee 这张图

    1
    
    image = data.coffee()
    
    1
    
    plt.imshow(image);
    

    png

    分解 RGB 三个颜色通道的数据,得到 R、G、B 三个分量

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    
    B = image[:,:,0]
    G = image[:,:,1]
    R = image[:,:,2]
    
    plt.figure(figsize=(10,8))
    plt.subplot(1,3,1)
    plt.imshow(R, cmap="gray")
    plt.title('R')
    
    plt.subplot(1,3,2)
    plt.imshow(G, cmap="gray")
    plt.title('G')
    
    plt.subplot(1,3,3)
    plt.imshow(B, cmap="gray")
    plt.title('B');
    

    png

    对 R 分量进行位平面分解的结果

    1
    
    bitplane(R)
    

    png

    对 G 分量进行位平面分解的结果

    1
    
    bitplane(G)
    

    png

    对 B 分量进行位平面分解的结果

    1
    
    bitplane(B)
    

    png



沪ICP备19023445号-2号
友情链接