pythonpython-imaging-librarysubdirectoryos.walkdirectory-traversal

Iterative folder open, process and save image one by one


I have a folder "Images-2" which has more than 100 sub folders, these sub folders consist of one image per folder. def main() opens each image, and def run(img) takes the image and processes it, but now I am unable to save that image in it's sub folder.

e.g def main c:/Images-2/1/1.png (1 is the folder name, so I have 100 folders in Images-2)

if condition will save processed image(zero.png) in folder Images-2/1/

How will it work for 100 folders, 1 image each folder?

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()

Solution

  • You are calling os.walk twice. That is your problem. This is what I meant in my comment:

    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()