微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

For 循环只创建一个数组而不是多个

如何解决For 循环只创建一个数组而不是多个

我有包含不同数量对象的二进制图像,我必须计算每个对象内的点数(这些点的坐标来自 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,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,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 文件,其中包含每个对象中计数的点(每行应对应一个对象)。

非常感谢您的帮助!

解决方法

我设法解决了它。最后一部分现在看起来像这样:

#multiply arrays
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

split_spots_counted = np.array_split(spots_counted,np.amax(label_im))

#count spots (values == 1 in each cell)
counts = []
for index in range(0,max_number_of_cells):
   counts.append(np.count_nonzero(split_spots_counted[index] == 1))
index = index+1

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。