迭代文件夹打开,处理并逐个保存图像

时间:2017-12-03 07:27:51

标签: python python-imaging-library subdirectory os.walk directory-traversal

我有一个文件夹“Images-2”,它有100多个子文件夹,这些子文件夹由每个文件夹一个图像组成。 def main()打开每个图片,def run(img)获取图像并对其进行处理,但现在我无法将该图像保存在其子文件夹中。

例如def main c:/Images-2/1/1.png(1是文件夹名称,因此我在Images-2中有100个文件夹)

如果条件会将已处理的图片(zero.png)保存在文件夹Images-2/1 /

如何处理100个文件夹,每个文件夹1个图像?

def run(img):
  data = img.load()
  width, height = img.size
  output_img = Image.new("RGB", (100, 100))
  Zero=np.zeros(shape=(100, 100),dtype=np.uint8)

  for (x, y) in labels:
            component = uf.find(labels[(x, y)])
            labels[(x, y)] = component
            path='C:/Python27/cclabel/Images-2/'
            if labels[(x, y)]==0:
                Zero[y][x]=int(255)
                Zeroth = Image.fromarray(Zero)
                for root, dirs in os.walk(path):
                    print root
                    print dirs
                    Zeroth.save(path+'Zero'+'.png','png')
def main():
    # Open the image
    path="C:/Python27/cclabel/Images-2/"
    for root, dirs, files in os.walk(path):
        for file_ in files:
            img = Image.open(os.path.join(root, file_))
            img = img.point(lambda p: p > 190 and 255)
            img = img.convert('1')
            (labels, output_img) = run(img)

if __name__ == "__main__": main()

1 个答案:

答案 0 :(得分:0)

您正在拨打os.walk两次。那是你的问题。这就是我在评论中的意思:

def run(dirname, img):
    data = img.load()
    width, height = img.size
    output_img = Image.new("RGB", (100, 100))
    Zero=np.zeros(shape=(100, 100), dtype=np.uint8)

    for (x, y) in labels:
        component = uf.find(labels[(x, y)])
        labels[(x, y)] = component
        path = 'C:/Python27/cclabel/Images-2/'
        if labels[(x, y)] == 0:
            Zero[y][x] = 255
            Zeroth = Image.fromarray(Zero)
            Zeroth.save(os.path.join(dirname, 'Zero.png'), 'png')


def main():
    path = "C:/Python27/cclabel/Images-2/"
    for root, dirs, files in os.walk(path):
        for file_ in files:
            img = Image.open(os.path.join(root, file_))
            img = img.point(lambda p: p > 190 and 255)
            img = img.convert('1')
            (labels, output_img) = run(root, img)


if __name__ == "__main__":
    main()