How to check dimensions of all images in a directory using python?

后端 未结 7 717
無奈伤痛
無奈伤痛 2020-12-09 05:15

I need to check the dimensions of images in a directory. Currently it has ~700 images. I just need to check the sizes, and if the size does not match a given dimension, it w

7条回答
  •  情深已故
    2020-12-09 05:53

    Here is a script that does what you need:

    #!/usr/bin/env python
    
    """
    Get information about images in a folder.
    """
    
    from os import listdir
    from os.path import isfile, join
    
    from PIL import Image
    
    
    def print_data(data):
        """
        Parameters
        ----------
        data : dict
        """
        for k, v in data.items():
            print("%s:\t%s" % (k, v))
        print("Min width: %i" % data['min_width'])
        print("Max width: %i" % data['max_width'])
        print("Min height: %i" % data['min_height'])
        print("Max height: %i" % data['max_height'])
    
    
    def main(path):
        """
        Parameters
        ----------
        path : str
            Path where to look for image files.
        """
        onlyfiles = [f for f in listdir(path) if isfile(join(path, f))]
    
        # Filter files by extension
        onlyfiles = [f for f in onlyfiles if f.endswith('.jpg')]
    
        data = {}
        data['images_count'] = len(onlyfiles)
        data['min_width'] = 10**100  # No image will be bigger than that
        data['max_width'] = 0
        data['min_height'] = 10**100  # No image will be bigger than that
        data['max_height'] = 0
    
        for filename in onlyfiles:
            im = Image.open(filename)
            width, height = im.size
            data['min_width'] = min(width, data['min_width'])
            data['max_width'] = max(width, data['max_width'])
            data['min_height'] = min(height, data['min_height'])
            data['max_height'] = max(height, data['max_height'])
    
        print_data(data)
    
    
    if __name__ == '__main__':
        main(path='.')
    

提交回复
热议问题