【问题标题】:Convert RGBA to RGB in Python在 Python 中将 RGBA 转换为 RGB
【发布时间】:2018-05-14 13:25:22
【问题描述】:

使用 PIL 将 RGBA 图像转换为 RGB 的最简单、最快的方法是什么? 我只需要从一些图像中删除 A 通道。

我找不到简单的方法来做到这一点,我不需要考虑背景。

【问题讨论】:

    标签: python-3.x image type-conversion python-imaging-library rgb


    【解决方案1】:

    您可能想使用图像的转换方法:

    import PIL.Image
    
    
    rgba_image = PIL.Image.open(path_to_image)
    rgb_image = rgba_image.convert('RGB')
    

    【讨论】:

      【解决方案2】:

      numpy数组的情况下,我使用这个解决方案:

      def rgba2rgb( rgba, background=(255,255,255) ):
          row, col, ch = rgba.shape
      
          if ch == 3:
              return rgba
      
          assert ch == 4, 'RGBA image has 4 channels.'
      
          rgb = np.zeros( (row, col, 3), dtype='float32' )
          r, g, b, a = rgba[:,:,0], rgba[:,:,1], rgba[:,:,2], rgba[:,:,3]
      
          a = np.asarray( a, dtype='float32' ) / 255.0
      
          R, G, B = background
      
          rgb[:,:,0] = r * a + (1.0 - a) * R
          rgb[:,:,1] = g * a + (1.0 - a) * G
          rgb[:,:,2] = b * a + (1.0 - a) * B
      
          return np.asarray( rgb, dtype='uint8' )
      

      其中参数rgbanumpy 类型的uint8 数组,具有4 个通道。输出是一个numpy 数组,具有3 个uint8 类型的通道。

      这个数组很容易通过库imageio使用imreadimsave进行I/O。

      【讨论】:

        猜你喜欢
        • 2012-04-11
        • 1970-01-01
        • 1970-01-01
        • 2011-01-04
        • 1970-01-01
        • 2011-10-04
        • 2021-12-17
        • 2012-02-28
        相关资源
        最近更新 更多