简体   繁体   English

在python中使用相应的蒙版进行图像分割

[英]Image segmentation using corresponding masks in python

I have corresponding masks to the images that I want to segment. 我要分割的图像具有相应的蒙版。

I put the images in one folder and their corresponding masks in another folder. 我将图像放在一个文件夹中,并将它们对应的遮罩放在另一个文件夹中。 I'm trying to apply those masks or multiply them by the images using two for loops in python to get the segmented images. 我正在尝试应用这些蒙版或使用python中的两个for循环将它们乘以图像,以获取分段图像。

I'm using the code below: 我正在使用以下代码:

def ImageSegmentation():

SegmentedImages = []

for img_path in os.listdir('C:/Users/mab/Desktop/images/'):
    img=io.imread('C:/Users/mab/Desktop/data/'+img_path)
    for img_path2 in os.listdir('C:/Users/mab/Desktop/masks/'):
        Mask = io.imread('C:/Users/mab/Desktop/masks/'+img_path2)

        [indx, indy] = np.where(Mask==0)
        Color_Masked = img.copy()
        Color_Masked[indx,indy] = 0

        matplotlib.image.imsave('C:/Users/mab/Desktop/SegmentedImages/'+img_path2,Color_Masked)
        segs.append(Color_Masked)
 return np.vstack(Color_Masked)

This code works when I try it for a single image and a single mask (without the folders and loops). 当我为单个图像和单个蒙版(没有文件夹和循环)尝试此代码时,此代码有效。

However, when I try to loop over the images and masks I have in the two folders, I get output images that are segmented by the wrong mask (not their corresponding mask). 但是,当我尝试遍历两个文件夹中的图像和蒙版时,我得到的输出图像被错误的蒙版(而不是其对应的蒙版)分割。

I can't segment each single image alone without looping because I have more than 500 Images and their masks. 我无法单独分割每个图像而不会循环播放,因为我有500多个图像及其遮罩。

I don't know what I'm missing or placing wrong in this code and how can I fix it? 我不知道我在此代码中缺少什么或放置了什么错误,我该如何解决? Also, is there an easier way to get the segmented images? 另外,有没有更简单的方法来获取分割的图像?

Unless I have grossly misunderstood, you just need something like this: 除非我被严重误解,否则您只需要以下内容:

import glob

filelist = glob.glob('C:/Users/mab/Desktop/images/*.png') 
for i in filelist:
    mask = i.replace("images","masks")
    print(i,mask)

On my iMac, that sort of thing produces: 在我的iMac上,这种事情会产生:

/Users/mark/StackOverflow/images/b.png /Users/mark/StackOverflow/masks/b.png
/Users/mark/StackOverflow/images/a.png /Users/mark/StackOverflow/masks/a.png

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM