How to create a loop to read several images in a python script?

I use python to work with image processing. I'm used to cut, draw and other things, but for one image. Like in the script below, how can i aply a loop in the script to do for several images?

import PIL

import Image

im=Image.open('test.tif')

box=(50, 50, 200, 200)

im_crop=im.crop(box)

im_crop.show()

Upvotes: 4

Views: 26034

Answers (3)

RichieHindle
RichieHindle

Reputation: 281525

You need to wrap it in a for loop, and give that loop a list of files.

One very easy way to get a list of all the TIF files in the current directory is with glob, like this:

import PIL
import Image
import glob

for filename in glob.glob("*.tif"):
    im=Image.open(filename)
    box=(50, 50, 200, 200)
    im_crop=im.crop(box)
    im_crop.show()

Upvotes: 9

Jacob
Jacob

Reputation: 43229

import PIL
import Image

filelist = ['test.tif','test2.tif']
for imagefile in filelist:
    im=Image.open(imagefile)
    box=(50, 50, 200, 200)
    im_crop=im.crop(box)
    im_crop.show()

Just add the filenames to the list filelist. The for loop iterates over each element of the list and assigns the current value to imagefile. You can use imagefile in the body of your loop to process the image.

Upvotes: 2

combatdave
combatdave

Reputation: 765

Something like this, perhaps?

import PIL

import Image

images = ["test.tif", "test2.tif", "test3.tif"]

for imgName in images:
    im=Image.open(imgName)

    box=(50, 50, 200, 200)

    im_crop=im.crop(box)

    im_crop.show()

Upvotes: 0

Related Questions