Smooth OpenCV / Numpy Array

I downloaded an RGB image from PIL / OpenCV, and I would like to convert all its channels into a single 1x sequence (3 * width * height) to pass it to ANN. I found that I can just do:

rlist = [] glist = [] blist = [] for i in xrange(im.width): for j in xrange(im.height): r,g,b = im[i,j] rlist.append(r) glist.append(g) blist.append(b) img_vec = rlist + blist + glist 

But obviously this is terribly inefficient. Is there a faster way with some internal OpenCV / numpy routine?

+6
source share
1 answer

As a quick example:

 import Image import numpy as np im = Image.open('temp.png') data = np.array(im) flattened = data.flatten() print data.shape print flattened.shape 

This gives:

 (612, 812, 4) (1987776,) 

Alternatively, instead of calling data.flatten() you can call data.reshape(-1) . -1 used as a placeholder to "determine what this measurement should be."

Note that this will give the vector ( flattened ) r0, g0, b0, r1, g1, b1, ... rn, gn, bn , while you need the vector r0, r1 ... rn, b0, b1, ... bn, g0, g1, ... gn .

To get exactly what you want, just call

 flattened = data.T.flatten() 

instead.

+7
source

Source: https://habr.com/ru/post/899230/


All Articles