Create an account


Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tut] How to Get the Size of an Image with PIL in Python

#1
How to Get the Size of an Image with PIL in Python

<div><div class="kk-star-ratings kksr-valign-top kksr-align-left " data-payload="{&quot;align&quot;:&quot;left&quot;,&quot;id&quot;:&quot;362009&quot;,&quot;slug&quot;:&quot;default&quot;,&quot;valign&quot;:&quot;top&quot;,&quot;reference&quot;:&quot;auto&quot;,&quot;count&quot;:&quot;0&quot;,&quot;readonly&quot;:&quot;&quot;,&quot;score&quot;:&quot;0&quot;,&quot;best&quot;:&quot;5&quot;,&quot;gap&quot;:&quot;5&quot;,&quot;greet&quot;:&quot;Rate this post&quot;,&quot;legend&quot;:&quot;0\/5 - (0 votes)&quot;,&quot;size&quot;:&quot;24&quot;,&quot;width&quot;:&quot;0&quot;,&quot;_legend&quot;:&quot;{score}\/{best} - ({count} {votes})&quot;}">
<div class="kksr-stars">
<div class="kksr-stars-inactive">
<div class="kksr-star" data-star="1" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" data-star="2" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" data-star="3" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" data-star="4" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" data-star="5" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
</p></div>
<div class="kksr-stars-active" style="width: 0px;">
<div class="kksr-star" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
</p></div>
</div>
<div class="kksr-legend"> <span class="kksr-muted">Rate this post</span> </div>
</div>
<h2><strong>Problem Formulation</strong></h2>
<p><strong>Given an image, how to get the size of the image with PIL or any other Python library?</strong></p>
<p>Getting the size of an image with Python PIL(Python Image Library) basically implies that you want to get its height and width in pixels. </p>
<p><strong>Example:</strong> Consider the following image:</p>
<figure class="wp-block-image size-full is-style-default"><img loading="lazy" width="604" height="396" src="https://blog.finxter.com/wp-content/uploads/2022/05/image-153.png" alt="" class="wp-image-362174" srcset="https://blog.finxter.com/wp-content/uploads/2022/05/image-153.png 604w, https://blog.finxter.com/wp-content/uplo...00x197.png 300w" sizes="(max-width: 604px) 100vw, 604px" /></figure>
<div class="wp-block-file"><a href="https://blog.finxter.com/wp-content/uploads/2022/05/image.jpg" class="wp-block-file__button" download aria-describedby="wp-block-file--media-a63084d8-f30a-43ff-8494-6f90888c1b37"><strong>Download Image Here</strong></a></div>
<p class="has-base-background-color has-background"><img src="https://s.w.org/images/core/emoji/13.1.0/72x72/1f525.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" /><strong>Challenge: </strong>Get the size of the above image with PIL or any other Python library.</p>
<h2><strong>Method 1: </strong>Using img.size</h2>
<p class="has-background" style="background-color:#dff2fc"><strong>Approach:</strong> To get the size of the image:<br />➢ open it up by calling the PIL function <code>Image.open('image file path')</code>.<br />➢ Then use the PIL property <code>image.size</code> on the opened image. This returns a <a rel="noreferrer noopener" href="https://blog.finxter.com/the-ultimate-guide-to-python-tuples/" target="_blank"><strong>tuple</strong></a> containing the width and height of the image in pixels.<br />➢ Unpack the tuple in two different variables to store the width and height individually.</p>
<p><strong>code:</strong></p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="3" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">from PIL import Image
img = Image.open("image.jpg")
width, height = img.size
print(f'width: {width}\nheight: {height}')</pre>
<p><strong>Output:</strong></p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">width: 640
height: 426</pre>
<p><strong>#Alternative Formulation</strong></p>
<p>Instead of using the img.size property, you can use the <strong>img.width </strong>and <strong>img.height </strong>properties to store/display the height and width of the image separately.</p>
<p>Here’s the code that demonstrates how you can use the width and height properties of the PIL library.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="3,4" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">from PIL import Image
img = Image.open("image.jpg")
width = img.width
height = img.height
print(f'width: {width}\nheight: {height}')</pre>
<p><strong>Output:</strong></p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">width: 640
height: 426</pre>
<p><img src="https://s.w.org/images/core/emoji/13.1.0/72x72/1f5e8.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" /><strong>TRIVIA: </strong><em>PIL</em>(Python Imaging Library) is a Python library that is used for image processing. It supports numerous image formats which include “<code>jpeg</code>”, “<code>png</code>”, “<code>ppm</code>”, “<code>tiff</code>”, “<code>bmp</code>”, “<code>gif</code>”, etc. It is an extremely useful library that provides a plethora of image editing capabilities like getting the size of an image, cropping an image, etc. The <code>Image</code> module of the PIL library is used to represent the <em>PIL</em> images. </p>
<ul>
<li>To install the PIL, execute the following command in your terminal: <code>pip install pillow </code></li>
</ul>
<h2><strong>Method 2: Get Image Size Using Open-CV</strong></h2>
<p class="has-background" style="background-color:#dff2f2"><strong>Approach: </strong>To get the size of an image using <em>OpenC</em>V:<br />➢ Load the image from the specified path by calling OpenCV function <strong><code>imread('file_path')</code></strong>.<br />➢ Use the <strong>.shape</strong> property on this image. This returns a tuple consisting of the height, width in pixels, and the number of channels of the image.<br />➢ Unpack these values individually in three different variables and display the output accordingly.</p>
<p><strong>Code:</strong></p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="3" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import cv2
image = cv2.imread('image.jpg')
height, width, channel = image.shape
print(f"width:{width}\nheight:{height}")</pre>
<p><strong>Output:</strong></p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">width: 640
height: 426</pre>
<p><img src="https://s.w.org/images/core/emoji/13.1.0/72x72/270f.png" alt="✏" class="wp-smiley" style="height: 1em; max-height: 1em;" /><strong>Note: </strong>Use the following command to install OpenCV: <code>pip install opencv-python</code></p>
<h2><strong>Method 3:</strong> Get the Image Size Using Pygame</h2>
<ul class="has-background" style="background-color:#dff2f2">
<li><strong>Approach: </strong>
<ul>
<li>Load the image from its path using the pygame function <code>pygame.image.load('filepath')</code>.</li>
<li>Use the methods <code>img.get_width()</code> and <code>img.get_height()</code> to get the image width and height in pixels.</li>
</ul>
</li>
</ul>
<p><strong>Code:</strong></p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="2-4" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import pygame
img = pygame.image.load('image.jpg')
width = img.get_width()
height = img.get_height()
print("width: ", width)
print("height: ", height)</pre>
<p><strong>Output:</strong></p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">pygame 2.1.2 (SDL 2.0.18, Python 3.9.10)
Hello from the pygame community. https://www.pygame.org/contribute.html
width: 640
height: 426</pre>
<p><strong><img src="https://s.w.org/images/core/emoji/13.1.0/72x72/1f5e8.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" />TRIVIA: </strong><code>pygame</code> is a Python wrapper for the <a href="https://www.libsdl.org/">SDL library</a> (<strong>Simple DirectMedia Layer)</strong>. SDL allows cross-platform access to the system’s underlying multimedia hardware components, such as video, sound, keyboard, mouse, and joystick. Since both SDL and <code>pygame</code> facilitate us with a cross-platform nature, we can write game programs and create rich multimedia Python programs for almost every platform that is supported by them.</p>
<p>To install <code>pygame</code>, use the following pip command on your terminal: <code>pip install pygame</code></p>
<h2>▣ How to Get Image Size in Bytes?</h2>
<p>Previously, we found out the size of the image, that is, the image dimensions (width and height). However, you may also need to find out the file size in bytes to decide how to use the image file. Hence, let us dive into the methods that will help us to find the image size in <strong>bytes</strong>.</p>
<h3>◩ <strong>Using <a rel="noreferrer noopener" href="https://docs.python.org/3/library/stat.html" target="_blank">os.stat</a></strong></h3>
<p><strong>Approach: </strong>Call the <code>os.stat()</code> method on the image file and then use the <code>st_size</code> property upon this image to get its size in bytes.</p>
<p><strong>Code:</strong></p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import os
print(os.stat('image.jpg').st_size) # 48297</pre>
<h3><strong>◩ Using os.path.getsize</strong></h3>
<p><strong>Approach:</strong> <code>os.path.getsize()</code> is a method of the os module that is used to get the size of a specified path. Pass the image path to this function to get the size of the image file in bytes.</p>
<p><strong>Code:</strong></p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import os
print(os.path.getsize('image.jpg')) # 48297</pre>
<h3><strong>◩ Using PIL</strong></h3>
<p><strong>Approach: </strong>Call the PIL function <code>Image.open()</code> to open the image and then use the <code>len()</code> method to find its length after reading the image. </p>
<p><strong>Code:</strong></p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">from PIL import Image
img = Image.open('image.jpg')
print("File Size In Bytes:- "+str(len(img.fp.read())))</pre>
<h2><img src="https://s.w.org/images/core/emoji/13.1.0/72x72/1f381.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" /><strong>Bonus: Get the Size of an Image by Loading Image from an URL</strong></h2>
<p>The following code demonstrates how you can load an image from an URL and then get its size.</p>
<p><strong>Code:</strong></p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import requests
from PIL import Image
from io import BytesIO
header = {'User-Agent': 'Mozilla/5.0 (X11; CrOS x86_64 14588.98.0) AppleWebKit/537.36 (KHTML, like Gecko) ' 'Chrome/101.0.4951.59 Safari/537.36'}
res = requests.get("https://blog.finxter.com/wp-content/uploads/2022/05/sample_img.png", headers=header)
# create image from binary content
img = Image.open(BytesIO(res.content))
width, height = img.size
print(f'width:{width}, height:{height}')</pre>
<p><strong>Output:</strong></p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">width:867, height:489</pre>
<h2><strong>Conclusion</strong></h2>
<p>We successfully unearthed the answer to numerous questions, including how to use different libraries to find the image size – dimensions as well as the size in bytes. I hope this tutorial helped you. Please <strong><a href="https://blog.finxter.com/subscribe/" target="_blank" rel="noreferrer noopener">subscribe</a></strong> and stay tuned for more interesting tutorials. </p>
<ul class="has-base-background-color has-background">
<li><strong>Recommended Tutorials</strong>
<ul>
<li><strong><a href="https://blog.finxter.com/how-to-crop-an-image-using-pil/" target="_blank" rel="noreferrer noopener">How to Crop an Image Using PIL?</a></strong></li>
<li><strong><a href="https://blog.finxter.com/how-to-crop-an-image-using-opencv/" target="_blank" rel="noreferrer noopener">How to Crop an Image Using OpenCV?</a></strong></li>
<li><strong><a href="https://blog.finxter.com/five-useful-image-processing-techniques-in-python-using-opencv/" target="_blank" rel="noreferrer noopener">Python OpenCV Image Processing – Resize, Blend, Blur, Threshold, Convert</a></strong></li>
</ul>
</li>
</ul>
<p>Happy learning!<img src="https://s.w.org/images/core/emoji/13.1.0/72x72/1f60a.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>
<hr class="wp-block-separator" />
<ul>
<li>One of the most sought-after skills on Fiverr and Upwork is&nbsp;<strong>web scraping</strong>. Make no mistake:&nbsp;<em><strong>extracting data programmatically from websites&nbsp;</strong></em>is a critical life skill in today’s world that’s shaped by the web and remote work.</li>
<li>So, do you want to master the art of web scraping using Python’s BeautifulSoup?</li>
<li>If the answer is yes – this course will take you from beginner to expert in Web Scraping.</li>
</ul>
<div class="wp-block-image is-style-default">
<figure class="aligncenter"><a href="https://academy.finxter.com/university/web-scraping-with-beautifulsoup/" target="_blank" rel="noreferrer noopener"><img loading="lazy" width="480" height="360" src="https://blog.finxter.com/wp-content/uploads/2021/06/scrape_bs4.png" alt="" class="wp-image-32250" srcset="https://blog.finxter.com/wp-content/uploads/2021/06/scrape_bs4.png 480w, https://blog.finxter.com/wp-content/uplo...00x225.png 300w" sizes="(max-width: 480px) 100vw, 480px" /></a><figcaption><strong><a href="https://academy.finxter.com/university/web-scraping-with-beautifulsoup/" target="_blank" rel="noreferrer noopener">Join the Web Scraping with BeautifulSoup Masterclass</a></strong>&nbsp;now, and master it by tomorrow!</figcaption></figure>
</div>
</div>


https://www.sickgaming.net/blog/2022/05/...in-python/
Reply



Forum Jump:


Users browsing this thread:
1 Guest(s)

Forum software by © MyBB Theme © iAndrew 2016