pythonopencvimage-loading

batch processing of images in python opencv is not working


I used this code to read series of png format images in a folder. but it reads only one image successfully. What is the reason for that?

from glob import glob

for fn in glob('*.png'):
   im = cv2.imread(fn)

Solution

  • You've only got one variable (called im) so it can only hold one image. You probably want a list of images:

    # Make empty list
    imgs = []
    
    for fn in glob('*.png'):
        im = cv2.imread(fn, cv2.IMREAD_COLOR)
        imgs.append(im)
    

    Or, you can use a "list comprehension":

    imgs = [ cv2.imread(fn, cv2.IMREAD_COLOR) for fn in glob('*.png') ]