【发布时间】:2021-09-24 07:39:32
【问题描述】:
我有包含不同数量对象的二进制图像,我必须计算每个对象内的点数(这些点的坐标来自 csv 文件)。 我的代码在处理单个图像和单个 csv 文件时有效,但我需要编写它以便它可以迭代文件夹中的所有图像和 csv 文件对。
这第一部分有效:
def process(tif_file, csv_file):
pos = mpimg.imread(tif_file)
coord = np.genfromtxt(csv_file, delimiter=",")
label_im = label(pos) #Label the objects of the input image depending on the connecitivty of the pixels to each other
regions = regionprops(label_im)
max_number_of_cells = np.amax(label_im) #find the highest number of objects in all the images
#select only the object of interest by setting its pixel values == 1 and all the others == 0:
cells_array = []
index = 0
for x in range(1, max_number_of_cells+1):
cells_array.append(np.where(label_im != x, 0, label_im))
cells_array[index] = (np.where(cells_array[index] == x, 1, cells_array[index]))
index = index+1
#convert spots coordinates to a 515x512 image where each spot has value 1:
x = coord[:,2]
y = coord[:,1]
#make an array from x,y coordinates
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")
#invert image and convert to binary
im_invert = ImageOps.invert(img)
bin_img = im_invert.convert('1')
#the spots values are 255, therefore they need to be converted to 1 (I only want to work with zeros and ones):
bin_img = np.where(bin_img == 255, 1, bin_img)
bin_img = bin_img.astype(np.int64)
bin_img.dtype
#convert arrays from 2d to 1d
index = 0
for x in range(1, max_number_of_cells+1):
cells_array[index] = cells_array[index].flatten()
index = index+1
bin_img = bin_img.flatten()
这是我开始遇到问题的部分:
#Multiply arrays so that only the spots inside the selected object are equal to 1. It should create a different array for each object containing the result of the multiplication, but in this way it creates a single array!
spots_counted = []
for index in range(0, max_number_of_cells):
for num1, num2 in zip(cells_array[index], bin_img):
spots_counted.append(num1*num2)
index = index+1
最后,我需要计算每个对象内的点数(每个数组中有多少个值 == 1)
#count spots
for index in range(0, max_number_of_cells):
spots_counted[index] = sum(float(num) == 1 for num in spots_counted[index])
index = index+1
print(spots_counted)
最后我还需要一个 csv 文件,其中包含每个对象中计数的点(每一行应该对应一个对象)。
非常感谢您的帮助!
【问题讨论】:
-
我刚刚意识到我可以将相乘的数组除以 max_number_of_cells: split_spots_counted = np.array_split(spots_counted, np.amax(label_im)) 但也许这不是最优雅的方法。
标签: python python-3.x loops iterator iteration