Sergio Lopez
Sergio Lopez

Reputation: 59

save array 3D in CSV

Sorry I have a problem to save the data in a csv, what I want to save is a 3d array of images, I could save it, the problem arises when reading the csv, since it is saved as a string, so I can not read the data to create the image, try to use the astype ("uint8"), since that is the format I need someone helps me how to save the data with the format I need or change the format when recovering the data.

    new_dt=pd.read_csv('mypic2.csv')

    for x in range(len(a.index)):
        imagess=a.img[x]
        print(imagess)
        cv2.imshow('imagenew', imagess)

Upvotes: 1

Views: 1780

Answers (2)

Quang Hoang
Quang Hoang

Reputation: 150735

I am also not so sure why you would want to save an image as csv. Since you are working with opencv, why don't you use cv2.imwrite, which is compatible with your cv2.imshow.

Another way to save an opencv image is using numpy.save since an opencv image is essentially an np.array.

If you must save it in csv, then you could create a data frame like

          width . height .  0  .  1  . ...
image_1 .   w1  .   h1   .  f0 .  f1 . ...
image_2 .   w2  .   h2   .  f0 .  f1 . ...

where each row contains the image's width and height followed by image.flatten(). Then you could modify your script as

new_dt=pd.read_csv('mypic2.csv')

for x in range(len(dt.index)):
    # recover image's dimension
    width = new_dt.iloc[x,0]
    height = new_dt.iloc[x,1]

    # load image and reshape to original dimension
    images = new_dt.iloc[x,2:].reshape(height, width, -1)
    print(imagess)
    cv2.imshow('imagenew', imagess)

Upvotes: 1

Hiral Bhimani
Hiral Bhimani

Reputation: 120

It is not clear from the question why you would want to use pandas dataframes to store the image. I think this makes things unnecessarily complicated. You may instead directly store the numpy array in binary format and load it again at some point later.

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

#create an image
imar = np.array([[[1.,0.,1.],[0.,0.,1.],[1.,1.,0.]],
                 [[0.,1.,1.],[0.,1.,1.],[1.,2.,3.]],
                 [[0.,0.,1.],[1.,1.,1.],[1.,0.,0.]]]).transpose()
plt.imsave('pic.png', imar)

#create dataframe

df = pd.DataFrame([[0,""]], columns=["Feature1","Feature2"])

# read the image
im = plt.imread('pic.png')

plt.imshow(im)
plt.show()

#save the image array to binary file
np.save('mypic.npy', im)
# store name of image in dataframe
df.iloc[0,1] = 'mypic.npy'
#save dataframe
df.to_csv("mydf.csv")
del df

#read dataframe from csv
df = pd.read_csv("mydf.csv")
# load the image from binary file, given the path from the Dataframe
new_im= np.load(df["Feature2"][0])
# show the loaded image
plt.imshow(new_im)
plt.show()

Upvotes: 1

Related Questions