Home > Software design >  How to display image size and file name along with image in Python?
How to display image size and file name along with image in Python?

Time:02-27

I have a folder with many images I just want to display a 5 random images with size and the file name. so far I can display the images but not sure how to also add in the size and file name.

images = [ PIL.Image.open(f) for f in glob("/content/gdrive/pics/*.jpg") ]
def imgmap(im):
    if im.mode != 'RGB':
        im = im.convert(mode='RGB')
    return np.fromstring(im.tobytes(), dtype='uint8').reshape((im.size[0], im.size[1], 3))

np_images = [ imgmap(im) for im in images ]

visualize = random.sample(np_images, 5)
for img in visualize:
    plt.figure()
    plt.imshow(img)

CodePudding user response:

To get file size

size = os.stat(f).st_size

to get filename without directory

filename = os.path.basename(f)

And you should create tuples (img, filename, size)

images = [ (PIL.Image.open(f).convert('RGB'), 
            os.path.basename(f), 
            os.stat(f).st_size)
                 for f in glob("/content/gdrive/pics/*.jpg") ]

On my computer plt.imshow() can display PIL.Image so I don't have to convert to np.array. But if you need to convert then you can do it when you create tuple.

images = [ (imgmap(PIL.Image.open(f).convert('RGB')),
            os.path.basename(f), 
            os.stat(f).st_size)
                 for f in glob("/content/gdrive/pics/*.jpg") ]

And later you can get them together

visualize = random.sample(images, 5)

for img, name, size in visualize:
    plt.figure()
    plt.imshow(img)
    plt.title(f"{name} - {size} bytes")

EDIT:

Code could be more readable

def process(path):
    img = imgmap(PIL.Image.open(path).convert('RGB'))
    name = os.path.basename(path)
    size = os.stat(path).st_size
    return (img, name, size)

images = [ process(f) for f in glob("/content/gdrive/pics/*.jpg") ]

Frankly, if you need only 5 images then faster could be first get random filenames and later process only these filenames.

CodePudding user response:

You can do something like this

files = glob("/content/gdrive/pics/*.jpg")

then

fileNames = [os.path.basename(path) for path in files]

and

fileSizes = [os.stat(path).st_size for path in files]

Now you have arrays that contain your file names and file sizes and hopefully you know what todo from there.

  • Related