0

I am doing model inferencing on images. I have a folder with images, named image_0, image_1 and so on. I need to read each image, do the inference job and then save them with the same name in order to merge them together to form a bigger image. To read the images, I use the next code:

for image_path in sorted(glob.glob(r'/patches/images/*.png')):
    image_np = load_image_into_numpy_array(image_path)

After the inference, to save each image I do:

cv2.imwrite(f'patches/new/image_{n}.png', im_bgr)

The line above is in the same for loop as glob.

n is the number of the image, indicated by a counter in each iteration.

The problem is that glob is not reading the images in the correct order (even if I put sorted before it, as I read in other questions), so when I merge them together, instead of being like this (each number represents an image):

1   2   3
4   5   6
7   8   9

the result is not ordered:

1   6   8
2   9   4
5   7   3

enter image description here

So, how can I make glob to read the images in the correct order?

Thank you!!!

OlegRuskiy
  • 173
  • 2
  • 12
  • 2
    There isn't a lot to go off of here. Do you know that `glob` is the culprit, or are you just assuming that? For example, can you assert that `sorted(glob.glob(r'/patches/images/*.png'))` just by itself contains the paths in the order you expected? Are you sure it isn't actually the code that "stitches" the images together that's causing your problem? – Paul M. Jul 07 '21 at 15:29
  • Also, how many images are in your image folder? Are they all named according to your schema? Do some of them have leading zeros, such as `image_04.png`? – Paul M. Jul 07 '21 at 15:34
  • The order `glob()` reads the filenames is irrelevant because you're sorting them. The problem is most likely what @PaulM said, they are not getting sorted into the order you assume — because it's not being done correctly. Please indicate *exactly* how the files are named. – martineau Jul 07 '21 at 15:51
  • I am 100% sure is nothing related to the tiling/merging code, as it works perfectly without the inference part. Following what @PaulM. said, I added zeros before each number of the image, so instead of being image_1, now is image_01, and that seems to have solved the issue. I will dig more into it and when is solved, I'll post what worked for me. Thank you both for your feedback!! – OlegRuskiy Jul 07 '21 at 17:06
  • Yup, then it was due to lexicographical ordering. Take a look at this [answer](https://stackoverflow.com/questions/55357306/glob-glob-sorting-not-as-expected). – Paul M. Jul 07 '21 at 17:09
  • Exactly, thanks! @PaulM. – OlegRuskiy Jul 07 '21 at 20:59

0 Answers0