Getting Image Sizes of an Image Set

Python

This is an example where we have a train csv that contains image ID and label that we import into a dataframe but would like to add the width and height of each image as new columns. We use the PIL Image library to extract the size from each image and add as columns in the new dataframe.

 1|  import pandas as pd
 2|  from PIL import Image 
 3|  PATH = 'data/raw/train_images/'
 4|  
 5|  #Import train csv
 6|  train = pd.read_csv('data/raw/train.csv')
 7|  #Train csv contains image_id field with the format "image_name.jpg"
 8|  
 9|  def get_image_size(row):
10|      im = Image.open(PATH + row['image_id'])
11|      row['width'], row['height'] = im.size
12|      return row
13|  df = train.apply(get_image_size,axis=1)
Did you find this snippet useful?

Sign up for free to to add this to your code library