pythonlistimagestack

Python - How to handle image file sets whose names are sequential (list operation)


I have a dataset with 50 .png image files. How can I stack them into lists according to the condition in their file and pass each list into a function? I'm a beginner of Python, and I couldn't find a concrete data handling example in my text book.

(****1st to 50th dataset-> sample1)

(1st data set of sample1 fabricated with condition1, each number of picture is 20)
sample1-condition1-no0001.png sample1-condition1-no0002.png ... sample1-condition1-no0020.png

(2nd data set of sample1 fabricated with condition2, 20 data)
sample1-condition2-no0001.png sample1-condition2-no0002.png ... sample1-condition2-no0020.png

...

(50th data set of sample1 fabricated with condition50, 20 data)
sample1-condition50-no0001.png sample1-condition50-no0002.png ... sample1-condition50-no0020.png

I want to stack each data set as:

pictsample1 = np.stack([
    imageio.imread("sample1-condition{i}-no{:04d}.png".format(n)) >50
    for n in range(1, 20) 
    for i in range(1,50)
], axis=0)

This didn't work. I think it's because the grammar is wrong.

Then I want to put in some function for each dataset, like below:

answerlist{k}=function(pictsample1{k}, signed=True)

If anyone who knows about list operations, could you please tell me?

I have tried to handle single data as follows:

import imageio
import numpy as np
import matplotlib.pyplot as plt
import cv2

# Handling only the first data of the first data set

image_test = imageio.imread("experiment/sample1-condition1-no0001.png")
plt.imshow(image_test, "gray")
np.max(image_test)
np.min(image_test)
np.count_nonzero(img_diff)

# Handling only the 20 data of the first data set

pictsample1 = np.stack([
        imageio.imread("sample1-condition{i}-no{:04d}.png".format(n)) >50
        for n in range(1, 20) 
    ],
    axis=0)

nonzerolist=np.nonzero(pict)
print(nonzerolist)

Now I want to do things like above but for each data set however I cannot stack data. Please tell me how to do this.


Solution

  • You’ve mixed up two different formatting styles - f-strings ({i}) and .format ({:04d}).

    If you wanted to stack all 1000 images in a single array, you’d use this for the inner list comprehension:

    [
        imageio.imread(f"sample1-condition{i+1}-no{n+1:04d}.png") >50
        for n in range(20) 
        for i in range(50)
    ]
    

    Note that the >50 at the end will threshold your images to binary; make sure that’s what you wanted.