How to convert a PIL Image into a numpy array?

后端 未结 8 2394
不知归路
不知归路 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:31

    If your image is stored in a Blob format (i.e. in a database) you can use the same technique explained by Billal Begueradj to convert your image from Blobs to a byte array.

    In my case, I needed my images where stored in a blob column in a db table:

    def select_all_X_values(conn):
        cur = conn.cursor()
        cur.execute("SELECT ImageData from PiecesTable")    
        rows = cur.fetchall()    
        return rows
    

    I then created a helper function to change my dataset into np.array:

    X_dataset = select_all_X_values(conn)
    imagesList = convertToByteIO(np.array(X_dataset))
    
    def convertToByteIO(imagesArray):
        """
        # Converts an array of images into an array of Bytes
        """
        imagesList = []
    
        for i in range(len(imagesArray)):  
            img = Image.open(BytesIO(imagesArray[i])).convert("RGB")
            imagesList.insert(i, np.array(img))
    
        return imagesList
    

    After this, I was able to use the byteArrays in my Neural Network.

    plt.imshow(imagesList[0])
    

提交回复
热议问题