Jatin Katyal
Jatin Katyal

Reputation: 21

Difference between numpy 3D array and openCV imread object

This is the code I used to generate CSV file for all images.

"""Generate data.csv from data folder in working directory. """
from cv2 import imread,cvtColor,COLOR_RGB2GRAY,resize
from os import listdir
from numpy import array,savetxt,hstack

data=[]
for c in listdir('data'):
    i = listdir('data').index(c)
    print('Reading',c)
    for sample in listdir('data/'+c):
        path = 'data/' + c + '/' + sample
        img = imread(path)
        #img = cvtColor(img,COLOR_RGB2GRAY)
        img = resize(img,(150,150))
        row = hstack([img.ravel(),i])
        data.append(row)

data = array(data)
savetxt('data.csv',data,delimiter=',',fmt='%i')

i recover this data using

print('Reading data...')
data = genfromtxt('data.csv',delimiter=',')
X = reshape(data[:,:-1],(data.shape[0],150,150,3))
y = data[:,-1]
print('Data: ',X.shape)

when i use imshow function on this data, it shows white box with some random colored pixels, but when i save this with imsave it saves a normal image.

Why it appeared different for imshow?

I imported numpy, opencv and os for these scripts.

Upvotes: 0

Views: 540

Answers (1)

Jatin Katyal
Jatin Katyal

Reputation: 21

Since no one answered it so far, imshow from open CV displays numpy arrays of dtype int and of shape (h,w,3) with values between 0 and 255 or dtype float and values between 0 and 1 and shape (h,w,3). If image is shown as white and some random pixel it could be because of values in range (0,255) but of dtype float or anything else.

Like suggested by @Miki, changing dtype to uint should solve the problem too.

Upvotes: 1

Related Questions