简体   繁体   中英

How to read multiple images and create a 3D matrix with them?

I have a bunch of images (300 images of 400 X 400 pixels) with filenames like:

  • 001.bmp
  • 002.bmp
  • 003.bmp
  • ...

First, I tried reading one of them, eg using imread I get a (400L, 400L, 3L) matrix, the problem is the 3L (I think is RBG format), so the question here is: how can I read them and get a (400L, 400L, 1L) matrix that I need to proccess them?

Second, I tried to read the 300 images using a loop like the following:

data = np.zeros((400,400,300))
for i in range(300):
    data[:,:,i] = imread('{0}.bmp'.format(i))

but it doesn't work, very probably my code is wrong. Actually doing this, I want to concatenate each (300) image data (400 X 400) into a matrix of (400 X 400 X 300).

When trying to use:

data[:,:,i] = imread('{0}.bmp'.format(i))

search for '1.bmp' and not '001.bmp' , but due to the list go from 000 to 299, I got a problem with that and I cant write '00{0}.bmp'.format(i) to complete the filename, because for two- and three digits numbers I got '0012.bmp' or '00123.bmp'

Well, after hours, I got to do this

arrays = []
for number in range(0, 299):
    numstr = str(number).zfill(3)
    fname = numstr + '.bmp'
    a = imread(fname, flatten=1)
    arrays.append(a)
data = np.array(arrays)

This code its work well. Thankyou, for give me clues!

First, you are right that the last dimension are the color channels. I assume you want a grayscale image, which you can get with:

data = imread(fname, flatten=1)

That comes from the imread documentation here .

Second, your issue with the loop can be due to a couple of things. First, I don't see indentation in the code in your post, so make sure that is there on the loop body in the code that you are actually trying to run. Second, the code has a ".txt" extension. Are you sure you don't actually want ".bmp"?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM