PIL image to array (numpy array to array) - Python

前端 未结 4 845
面向向阳花
面向向阳花 2020-12-13 14:57

I have a .jpg image that I would like to convert to Python array, because I implemented treatment routines handling plain Python arrays.

It seems that PIL images su

4条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-13 15:42

    Based on zenpoy's answer:

    import Image
    import numpy
    
    def image2pixelarray(filepath):
        """
        Parameters
        ----------
        filepath : str
            Path to an image file
    
        Returns
        -------
        list
            A list of lists which make it simple to access the greyscale value by
            im[y][x]
        """
        im = Image.open(filepath).convert('L')
        (width, height) = im.size
        greyscale_map = list(im.getdata())
        greyscale_map = numpy.array(greyscale_map)
        greyscale_map = greyscale_map.reshape((height, width))
        return greyscale_map
    

提交回复
热议问题