Wboy
Wboy

Reputation: 2542

Numpy flatten array of array from cv2

Wait! Before you 'harrumph' and downvote, this seems like a repeat question but I've looked at the other questions and they don't really fit my use case.

I was reading images one by one into a list with cv2, with the intention of running a classifier over them. eg:

lst = []

for picture in directory:
    img = cv2.imread(picture)
    img = img.flatten() # because classifiers require it to be flat
    lst.append(img)

This resulted in the lst array being like so:

array([array([43, 25,  8, ..., 70, 68, 50], dtype=uint8),
       array([ 24,  40,  16, ..., 182, 183, 167], dtype=uint8),
       array([ 39,  35,  34, ..., 117, 114, 106], dtype=uint8), ...,
       array([31, 50, 41, ..., 16, 16, 10], dtype=uint8),
       array([ 14,  17,  15, ...,  95, 109, 105], dtype=uint8),
       array([101, 102, 122, ..., 178, 187, 214], dtype=uint8)], dtype=object)

Which is not really what i wanted. I wanted lst to be an (10000,311520) array which can be thrown to a classifier, but now lst is an (10000,) array, while the individual elements are of shape (311520,)

I've tried np.flatten (doh) , np.concatenate, np.hstack / vstack. None of them help.

Is there something im missing that would help? Is this even the right way of doing it?

Thanks so much for your help! :)

Upvotes: 1

Views: 4128

Answers (1)

Aguy
Aguy

Reputation: 8059

Here's a suggestion. Only works if all images are indeed the same size after flattening.

lst = []
for picture in directory:
    img = cv2.imread(picture)
    img = img.flatten() # because classifiers require it to be flat
    if lst = []:
        lst = img
    else:
        lst = concatenate((lst, [img]), axis=0)

Upvotes: 2

Related Questions