将相同的代码应用于同一目录中的多个文件

Apply the same code to multiple files in the same directory

我有一个已经可以使用的代码,但我需要用它来分析同一文件夹中的许多文件。我怎样才能重写它来做到这一点?所有文件都有相似的名称(例如“pos001”、“pos002”、“pos003”)。

这是目前的代码:

pos001 = mpimg.imread('pos001.tif')
coord_pos001 = np.genfromtxt('treat_pos001_fluo__spots.csv', delimiter=",")

这里我将tif文件标记为“pos001”以区分同一图像中的不同对象:

label_im = label(pos001)
regions = regionprops(label_im)

这里我select通过设置它的像素值== 1和所有其他== 0只设置感兴趣的对象(我对很多对象感兴趣,我在这里只显示一个):

cell1 = np.where(label_im != 1, 0, label_im)

在这里,我将 csv 文件中点的 x、y 坐标转换为 515x512 图像,其中每个点的值为 1:

x = coord_pos001[:,2]
y = coord_pos001[:,1]

coords = np.column_stack((x, y))

img = Image.new("RGB", (512,512), "white")
draw = ImageDraw.Draw(img)

dotSize = 1
for (x,y) in coords:
    draw.rectangle([x,y,x+dotSize-1,y+dotSize-1], fill="black")

im_invert = ImageOps.invert(img)
bin_img = im_invert.convert('1')

这里我把csv文件的点的值设置为1:

bin_img = np.where(bin_img == 255, 1, bin_img)

我将数组从 2d 转换为 1d:

bin_img = bin_img.astype(np.int64)
cell1 = cell1.flatten()
bin_img = bin_img.flatten()

我将数组相乘得到一个数组,其中只有与标记对象重叠的点的值 = 1:

spots_cell1 = []
for num1, num2 in zip(cell1, bin_img):
    spots_cell1.append(num1 * num2)

我数了属于那个物体的点:

spots_cell1 = sum(float(num) == 1 for num in spots_cell1)
print(spots_cell1)

我希望一切都清楚。提前致谢!

您可以定义一个函数,它接受 .tif 文件路径和 .csv 文件路径并处理这两个

def process(tif_file, csv_file):
    pos = mpimg.imread(tif_file)
    coord = np.genfromtxt(csv_file, delimiter=",")
    # Do other processing with pos and coord

要处理一对文件,您需要执行以下操作:

process('pos001.tif', 'treat_pos001_fluo__spots.csv')

要列出您的 tif 文件目录中的所有文件,您可以使用 this answer 中的示例:

import os

tif_file_directory = "/home/username/path/to/tif/files"
csv_file_directory = "/home/username/path/to/csv/files"
all_tif_files = os.listdir(tif_file_directory)

for file in all_tif_files:
    if file.endswith(".tif"):                          # Make sure this is a tif file
        fname = file.rstrip(".tif")                    # Get just the file name without the .tif extension
        tif_file = f"{tif_file_directory}/{fname}.tif" # Full path to tif file
        csv_file = f"{csv_file_directory}/treat_{fname}_fluo__spots.csv" # Full path to csv file

        # Just to keep track of what is processed, print them
        print(f"Processing {tif_file} and {csv_file}")
        process(tif_file, csv_file)

f"...{variable}..." 构造称为 f 字符串。更多信息在这里:https://realpython.com/python-f-strings/