代码之家  ›  专栏  ›  技术社区  ›  Dims

在PIL中如何将灰度图像转换成给定的彩色monchrome图像?

  •  1
  • Dims  · 技术社区  · 6 年前

    我看到矩阵参数 convert 功能,但其描述尚不清楚。它说,应该是4元组或12元组,不需要解释成分的含义。

    代码:

    from PIL import Image
    import matplotlib.pyplot as plt
    
    with open('myimage.png', 'rb') as fp:
        #matrix = (0, 1, 0, 1)
        matrix = (0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1)
        im = Image.open(fp)
        im = im.convert('RGB', matrix)
        plt.imshow(im)
        plt.show()
    

     ValueError: image has wrong mode
    

    在Image.py代码中

        if matrix:
            # matrix conversion
            if mode not in ("L", "RGB"):
                raise ValueError("illegal conversion")
            >>>>>> im = self.im.convert_matrix(mode, matrix)
            return self._new(im)
    

    我也不明白,因为这里没有抛出代码,只是引用一个对象。我查不到。

    1 回复  |  直到 6 年前
        1
  •  2
  •   Mark Setchell    6 年前

    我想你正在尝试这样做,也许有一个苍白的形象:

    #!/usr/bin/env python3
    from PIL import Image
    
    # Open and ensure in RGB mode - in case image is palettised
    im = Image.open('toystory.png').convert('RGB')
    
    # Crude conversion to black and white using 20% red, 50% green and 30% blue
    matrix = (0.2, 0.5, 0.3, 0.0, 0.2, 0.5, 0.3, 0.0, 0.2, 0.5, 0.3, 0.0)
    
    result = im.convert('RGB',matrix)
    
    result.save('result.png')
    

    enter image description here

    对此:

    enter image description here


    matrix = (0,0,1,0, 0,1,0,0, 1,0,0,0) 
    

    enter image description here