Is there a way to use Pillows “Image.convert()” on an existing variable?

前端 未结 3 1245
星月不相逢
星月不相逢 2021-01-25 03:28

Hello,

maybe this question looks stupid, but I try to use Pillows Image.convert() to convert an image to grayscale. This image I have store

相关标签:
3条回答
  • 2021-01-25 03:56

    You can use

    img = Image.fromarray(img)
    

    to convert to a PIL Image type. From there, you should be able to use PIL's convert() function

    img = img.convert('LA')
    

    then, to access the pixel values directly you can either convert back to a numpy array

    img_array = np.asarray(img)
    

    or get pixel access to the PIL Image using

    pixels = img.load()
    
    0 讨论(0)
  • 2021-01-25 04:06

    Instead of saying Image.convert() use your image variable: img e.g img = img.convert('') and in this case:

    img = img.convert('LA')

    0 讨论(0)
  • 2021-01-25 04:15

    Whilst you could perfectly well convert your Numpy array to a PIL Image and then convert that to greyscale and then convert back to a Numpy array like this:

    PILImage = Image.fromarray(Numpyimg)
    PILgrey  = PILImage.convert('L')
    Numpygrey= np.array(PILgrey)
    

    You might as well just do the ITU-R 601-2 luma transform yourself, i.e.

    L = 0.299 * Red + 0.587 * Green + 0.114 * Blue
    

    So, you would get:

    Numpygrey = np.dot(Numpyimg[...,:3], [0.299, 0.587, 0.114]).astype(np.uint8)
    
    0 讨论(0)
提交回复
热议问题