How do I get a size of a pictures sides with PIL or any other Python library?
open() is used to open the image and then . width and . height property of Image are used to get the height and width of the image.
To resize an image using PIL and maintain its aspect ratio with Python, we can open the image with Image. open . Then we calculate the new width and height to scale the image to according to the new width. And then we resize the image with the resize method and save the new image with the save method.
from PIL import Image im = Image.open('whatever.png') width, height = im.size
According to the documentation.
You can use Pillow (Website, Documentation, GitHub, PyPI). Pillow has the same interface as PIL, but works with Python 3.
$ pip install Pillow
If you don't have administrator rights (sudo on Debian), you can use
$ pip install --user Pillow
Other notes regarding the installation are here.
from PIL import Image with Image.open(filepath) as img: width, height = img.size
This needed 3.21 seconds for 30336 images (JPGs from 31x21 to 424x428, training data from National Data Science Bowl on Kaggle)
This is probably the most important reason to use Pillow instead of something self-written. And you should use Pillow instead of PIL (python-imaging), because it works with Python 3.
I keep scipy.ndimage.imread
as the information is still out there, but keep in mind:
imread is deprecated! imread is deprecated in SciPy 1.0.0, and [was] removed in 1.2.0.
import scipy.ndimage height, width, channels = scipy.ndimage.imread(filepath).shape
import pygame img = pygame.image.load(filepath) width = img.get_width() height = img.get_height()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With