How to find the average resolution of bunch of images , so that I can feed the dimensions into a CNN layer in tensorflow?

Question:

I am working on a binary image classifier in tensorflow. I want to specify the img_shape in a Conv2D layer. I would like to know if there is a way of finding the average shape of all images in the dataset.

It would help a lot.
Thanks

Asked By: Saaransh Menon

||

Answers:

Found the solution using PIL library (I am using a directory of images)

import PIL
from PIL import Image

widths = []
heights = []

for img in os.listdir(""):
    img_path = os.path.join("") # Making image file path
    im = Image.open(img_path)
    widths.append(im.size[0])
    heights.append(im.size[1])

AVG_HEIGHT = round(sum(heights)/len(heights))
AVG_WIDTH = round(sum(widths)/len(widths))
Answered By: Saaransh Menon

For those who have trouble using the code above, try this one, it works like clockwork!

import os
import PIL
from PIL import Image

widths = []
heights = []

dir_path = r"write your file path in here" # Adding 'r' to make the string a raw string

for img_name in os.listdir(dir_path):
    if img_name.endswith(".jpg") or img_name.endswith(".png") or img_name.endswith(".jpeg") or img_name.endswith(".bmp"):
        img_path = os.path.join(dir_path, img_name) # Adding img_name to the path
        im = Image.open(img_path)
        widths.append(im.size[0])
        heights.append(im.size[1])

AVG_HEIGHT = round(sum(heights)/len(heights))
AVG_WIDTH = round(sum(widths)/len(widths))

print(f"Average Height: {AVG_HEIGHT}")
print(f"Average Width: {AVG_WIDTH}")
Answered By: Vesselchuck