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

前端 未结 4 850
面向向阳花
面向向阳花 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:25

    I highly recommend you use the tobytes function of the Image object. After some timing checks this is much more efficient.

    def jpg_image_to_array(image_path):
      """
      Loads JPEG image into 3D Numpy array of shape 
      (width, height, channels)
      """
      with Image.open(image_path) as image:         
        im_arr = np.fromstring(image.tobytes(), dtype=np.uint8)
        im_arr = im_arr.reshape((image.size[1], image.size[0], 3))                                   
      return im_arr
    

    The timings I ran on my laptop show

    In [76]: %timeit np.fromstring(im.tobytes(), dtype=np.uint8)
    1000 loops, best of 3: 230 µs per loop
    
    In [77]: %timeit np.array(im.getdata(), dtype=np.uint8)
    10 loops, best of 3: 114 ms per loop
    

    ```

提交回复
热议问题