How to convert a PIL Image into a numpy array?

后端 未结 8 2371
不知归路
不知归路 2020-11-22 17:12

Alright, I\'m toying around with converting a PIL image object back and forth to a numpy array so I can do some faster pixel by pixel transformations than PIL\'s Pixel

8条回答
  •  孤独总比滥情好
    2020-11-22 17:33

    The example, I have used today:

    import PIL
    import numpy
    from PIL import Image
    
    def resize_image(numpy_array_image, new_height):
        # convert nympy array image to PIL.Image
        image = Image.fromarray(numpy.uint8(numpy_array_image))
        old_width = float(image.size[0])
        old_height = float(image.size[1])
        ratio = float( new_height / old_height)
        new_width = int(old_width * ratio)
        image = image.resize((new_width, new_height), PIL.Image.ANTIALIAS)
        # convert PIL.Image into nympy array back again
        return array(image)
    

提交回复
热议问题