create account

Image processing in Python with Pillow by pars.team

View this thread on: hive.blogpeakd.comecency.com
· @pars.team ·
$0.18
Image processing in Python with Pillow
<center>![Image processing with Pillow](https://files.peakd.com/file/peakd-hive/pars.team/23yJXaVSd2gwTQ2nAYsu7RruHoHyETLM1MhzJ9Gq8x9B11CQUJitCs9CpUq7Afc13NAJU.png)</center>

<p>Python is currently one of the most widely used programming languages. It can be used to perform various tasks using a simple code. One of these tasks is image processing in Python.</p>
<p>One of the important things that Python can do is the automatic processing of digital images, which can be done using Pillow.</p>
<p>In this post, I will show you how to process an image in Python using the Pillow module. Then, I'll take it a step further and show how to perform some basic image operations.</p>
<h3>What is Pillow?</h3>
<p>Pillow is a subset of Python image processing libraries called PIL. This library is free and open source and is used to manipulate and process images.</p>
<p>PIL is a powerful library in its own right, but it hasn't been updated since 2009 and doesn't support Python 3. Pillow provides additional features and support for Python 3.</p>
<p>Pillow supports a wide range of image formats such as PNG, JPEG, PPM, GIF, TIFF and BMP. Using this library, you can perform various operations on images such as cropping, resizing, adding text, rotating, changing color, and more.</p>
<h3>Project installation</h3>
<p>You can install Pillow using pip, a package management tool for Python:</p>
<pre><code>python3 -m pip install --upgrade pip<br />
python3 -m pip install --upgrade Pillow</code></pre>
<p>Pillow provides the <code>Image</code> object, which has built-in functions and properties that can be used to manipulate images.</p>
<p>To start, first import the <code>Image</code> object in the Python code.</p>
<pre><code>from PIL import Image</code></pre>
<p>Then, load the image by calling the <code>Image.open()</code> function, whose return type is a value of the <code>Image</code> object type.</p>
<pre><code>image = Image.open('sample.jpg')</code></pre>
<p>For my app, I'm using a sample image from <a href="https://unsplash.com/s/photos/purple-pictures">Unsplash</a>.</p>
<p>It is also important to mention that the images must be in the same directory as the python file is running.</p>
<h3>Properties of the Image object</h3>
<p>The image has features that we can access to get more information from the image. Including:</p>
<ul>
<li>width Returns the length of the image</li>
<li>height returns the width of the image</li>
<li>format Returns the format of the image file (eg, JPEG, BMP, PNG, etc.)</li>
<li>size returns the height and weight of the image</li>
<li>palette Returns the color palette table, if any</li>
<li>mode Returns the pixel format of the image (eg, 1, L, RGB, CMYK)</li>
</ul>
<h3>Basic operation for image</h3>
<p>We can also process and manipulate our images using various operations.</p>
<p>Any changes made to the <code>Image</code> object can be saved to an image file with the <code>save()</code> method. All rotations, resizing, cropping, drawing and other image manipulations are done through calls on this <code>Image</code> object.</p>
<p>Let's dive deeper and explore some of these operations in more detail.</p>
<h3>Change the image format</h3>
<p>Pillow supports a wide variety of image formats. An image can be converted from one format to another as follows:</p>
<pre><code>image = Image.open('sample.jpg')<br />
image.save('sample_formatted.png')</code></pre>
<p>The image is loaded first. Then Pillow considers the specified file extension as PNG, that is, it converts the image to <code>.PNG</code> before saving it to the file.</p>
<h3>Create thumbnails</h3>
<p>You can resize images by creating a thumbnail of the image using Pillow.</p>
<p>Using the <code>thumbnail</code> function, the size of the image is changed to maintain its aspect ratio. This function takes two values representing the maximum width and maximum height of the thumbnail.</p>
<pre><code>image = Image.open('sample.jpg')
image.thumbnail((200, 200))
image.save('sample_thumbnail.jpg')</code></pre>

<center>![Create thumbnails](https://files.peakd.com/file/peakd-hive/pars.team/23yJX39kYa4ThFGhqW7rnrSqggzBtc1pniC1rcPuSbydMwCX1cYGQyeCC84UAco3mkAQ5.png)</center>

<h3>Flip and rotate images</h3>
<p>If you need the image flipped or rotated, Pillow lets you do that. This is done using the <code>transpose</code> function, which takes the following parameters:</p>
<ul>
<li><code>FLIP_LEFT_RIGHT</code>, which flips the image horizontally</li>
<li><code>FLIP_TOP_BOTTOM</code>, which flips the image vertically</li>
<li><code>ROTATE_90</code> , which rotates the image somewhat by the size of the angle</li>
</ul>
<pre><code>image = Image.open('sample.jpg')
image.transpose(Image.FLIP_TOP_BOTTOM)
image.save('sample_flip.jpg')</code></pre>

<center>![Flip and rotate images](https://files.peakd.com/file/peakd-hive/pars.team/EpA6QBPBxZRyXWPHWh2QxWQiQHF4weA8Cq2dQWHt497mEw1Jh5H4LRd6DhSh9wQwLNb.png)</center>

<p>You can also rotate images using the <code>rotate()</code> method. This function takes an integer or decimal argument representing the degree of rotation and returns a new <code>Image</code> object of the rotated image. The rotation is counterclockwise.</p>
<pre><code>image = Image.open('sample.jpg')<br /><br /><br />
image.rotate(90)
image.save('image_rotate90.jpg')</code></pre>

<center>![rotate](https://files.peakd.com/file/peakd-hive/pars.team/23y96C1NXtQ5U8m4Wsd5yUkQPJNiVNBT6Q2ZJxRM3L28W9kd2Zvc69JR6GyxkMP2stydf.png)</center>

<h3>Crop images</h3>
<p>Cropping an image means cutting only a specific part of it, which is often used when editing images for web applications.</p>
<p>The <code>crop</code> function in Pillow cuts the image rectangularly. This method takes a tuple specifying the position and size of the cropped area and returns an <code>Image</code> object representing the cropped image. The cutting area is defined by a Tuple whose coordinates are (left, top, right, bottom).</p>
<pre><code>image = Image.open('sample.jpg')
image.crop(200, 50, 450, 300)
image.save('sample_cropped.jpg')</code></pre>

<center>![Crop images](https://files.peakd.com/file/peakd-hive/pars.team/23xf15pmm73ZgXuv9YqxbVDxi7vHbWKP6wGh7qVsb2jMAAQPyDTCsaiwaJZHyYy7oU2gL.png)</center>

<p>In the example above, the first two values indicate the starting location for the cut from the top left. The third and fourth values indicate the distance in pixels from the starting position to the right and bottom.</p>
<h3>color change</h3>
<p>There are different ways to represent pixels, including L (luminance), RGB, and CMYK.</p>
<p>Pillow allows you to convert images to pixel values for different displays using the <code>convert</code> method. This library supports conversion between any supported mode as well as "L" and "RGB" modes. To convert between other modes, you may have to use an "RGB" image.</p>
<pre><code>image = Image.open('sample.jpg')<br /><br /><br />
grayscale_image = image.convert('L')
grayscale_image.save('sample_grayscale.jpg')</code></pre>

<center>![color change](https://files.peakd.com/file/peakd-hive/pars.team/23yJXaVSd2gwTQ2nAYsu7RruHoHyETLM1MhzJ9Gq8x9B11CQUJitCs9CpUq7Afc13NAJU.png)</center>

<p>Using the convert function, the sample image is converted from RGB mode to L (luminance) mode, resulting in a grayscale image.</p>
<h3>Image filtering</h3>
<p>The act of editing and improving images to improve their appearance can be called filtering.</p>
<p>Using Pillow's ImageFilter module, you can use the filter method and use various filtering techniques, including:</p>
<ul>
<li>BLUR</li>
<li>CONTOUR</li>
<li>DETAIL</li>
<li>EDGE_ENHANCE</li>
<li>EDGE_ENHANCE_MORE</li>
<li>EMBOSS</li>
<li>FIND_EDGES</li>
<li>SHARPEN</li>
<li>SMOOTH</li>
<li>SMOOTH_MORE</li>
</ul>
<p>For example, let's take a look at the <code>FIND_EDGES filter</code>:</p>
<pre><code>from PIL import Image, ImageFilter<br />
image = Image.open('sample.jpg')
edges_image = image.filter(ImageFilter.FIND_EDGES)
edges_image.save('sample_edges.jpg')</code></pre>

<center>![Image filtering](https://files.peakd.com/file/peakd-hive/pars.team/23yx212wtzjgCJskV2EZH2WmZoLgHkcU5FGa7teoCsqMC13rp5jSaykkrBEKS4ESiQzMb.png)</center>

<h3>Image processing with Pillow: a practical example</h3>
<p>Now that we have a basic understanding of the library, let's create a simple Python file to automate the processing of various image types.</p>
<p>Suppose you are given a group of images and you are asked to add a watermark to each image.</p>
<p>To solve the problem, you can create a python file called <code>script.py</code> in the same folder as the images.</p>
<p>First, import all necessary modules:</p>
<pre><code>import os
from PIL import Image</code></pre>
<p>The <code>os</code> module in Python provides functions to create and delete directories and to change and identify the current directory.</p>
<p>Create a directory for the processed image:</p>
<pre><code>os.makedirs('watermarked_images')</code></pre>
<p>Save the length and width of the logo image:</p>
<pre><code>logo_image = Image.open('watermark_logo.png')
logo_image = logo_image.resize((50, 50))
logo_width, logo_height = logo_image.size</code></pre>
<p>Use the <code>os.listdir</code> function with a <code>for</code> loop:</p>
<pre><code>for image in os.listdir('./images'):
try:
# Separting the filepath from the image's name
path, filename = os.path.split(image)
filename = os.path.splitext(filename)[0]
Open the image:
image = Image.open('./images/'+image)
#Resizing the image to a set size.
edited_image = image.resize((300, 300))
#Setting the position for the placement
width = edited_image.width
height = edited_image.height</code></pre>
<p>Use the <code>paste</code> function to place the logo on the image:</p>
<pre><code>edited_image.paste(logo_image, (width - logo_width, height - logo_height), logo_image)</code></pre>
<p>Save the images in the new directory:</p>
<pre><code>edited_image.save('./watermarked_Images/' + filename + ".jpg")</code></pre>
<p>Each image in the directory is processed and a watermark is added to it. This code enables us to do the work in the best way in less time.</p>
👍  , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ,
properties (23)
authorpars.team
permlinkimage-processing-in-python-with-pillow
categoryhive-169321
json_metadata"{"app":"peakd/2023.10.1","format":"markdown","author":"pars.team","description":"In this post, I'll show you how to process an image in Python using the Pillow module.","tags":["development","programming","gosh","threads","hive-engine","chessbrothers","neoxian","stem","tricks","leofinance"],"users":[],"image":["https://files.peakd.com/file/peakd-hive/pars.team/23yJXaVSd2gwTQ2nAYsu7RruHoHyETLM1MhzJ9Gq8x9B11CQUJitCs9CpUq7Afc13NAJU.png","https://files.peakd.com/file/peakd-hive/pars.team/23yJX39kYa4ThFGhqW7rnrSqggzBtc1pniC1rcPuSbydMwCX1cYGQyeCC84UAco3mkAQ5.png","https://files.peakd.com/file/peakd-hive/pars.team/EpA6QBPBxZRyXWPHWh2QxWQiQHF4weA8Cq2dQWHt497mEw1Jh5H4LRd6DhSh9wQwLNb.png","https://files.peakd.com/file/peakd-hive/pars.team/23y96C1NXtQ5U8m4Wsd5yUkQPJNiVNBT6Q2ZJxRM3L28W9kd2Zvc69JR6GyxkMP2stydf.png","https://files.peakd.com/file/peakd-hive/pars.team/23xf15pmm73ZgXuv9YqxbVDxi7vHbWKP6wGh7qVsb2jMAAQPyDTCsaiwaJZHyYy7oU2gL.png","https://files.peakd.com/file/peakd-hive/pars.team/23yx212wtzjgCJskV2EZH2WmZoLgHkcU5FGa7teoCsqMC13rp5jSaykkrBEKS4ESiQzMb.png"]}"
created2023-11-13 21:32:09
last_update2023-11-13 21:32:09
depth0
children5
last_payout2023-11-20 21:32:09
cashout_time1969-12-31 23:59:59
total_payout_value0.090 HBD
curator_payout_value0.088 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length10,107
author_reputation1,044,473,769,173
root_title"Image processing in Python with Pillow"
beneficiaries
0.
accounthive-169321
weight200
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id128,831,773
net_rshares386,269,801,492
author_curate_reward""
vote details (32)
@albro ·
!LUV
properties (22)
authoralbro
permlinkre-parsteam-20231210t24553542z
categoryhive-169321
json_metadata{"tags":["development","programming","gosh","threads","hive-engine","chessbrothers","neoxian","stem","tricks","leofinance"],"app":"ecency/3.0.37-vision","format":"markdown+html"}
created2023-12-09 23:15:54
last_update2023-12-09 23:15:54
depth1
children1
last_payout2023-12-16 23:15:54
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length4
author_reputation30,477,419,385,789
root_title"Image processing in Python with Pillow"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id129,545,562
net_rshares0
@luvshares ·
<center><p>@albro sent you LUV 🙂 <sub>(1/10)</sub></p>
<p>Made with <a href="https://hive.blog/@luvshares">LUV</a> by <a href="https://hive.blog/@crrdlx">crrdlx</a></p></center>
properties (22)
authorluvshares
permlinkre-re-parsteam-20231210t24553542z-20231209t231609z
categoryhive-169321
json_metadata"{"app": "beem/0.24.26"}"
created2023-12-09 23:16:09
last_update2023-12-09 23:16:09
depth2
children0
last_payout2023-12-16 23:16:09
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length177
author_reputation5,651,102,754,153
root_title"Image processing in Python with Pillow"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id129,545,564
net_rshares0
@hivebuzz ·
Congratulations @pars.team! You have completed the following achievement on the Hive blockchain And have been rewarded with New badge(s)

<table><tr><td><img src="https://images.hive.blog/60x70/http://hivebuzz.me/@pars.team/upvoted.png?202312030549"></td><td>You received more than 100 upvotes.<br>Your next target is to reach 200 upvotes.</td></tr>
</table>

<sub>_You can view your badges on [your board](https://hivebuzz.me/@pars.team) and compare yourself to others in the [Ranking](https://hivebuzz.me/ranking)_</sub>
<sub>_If you no longer want to receive notifications, reply to this comment with the word_ `STOP`</sub>



**Check out our last posts:**
<table><tr><td><a href="/hive-122221/@hivebuzz/pum-202311-delegations"><img src="https://images.hive.blog/64x128/https://i.imgur.com/fg8QnBc.png"></a></td><td><a href="/hive-122221/@hivebuzz/pum-202311-delegations">Our Hive Power Delegations to the November PUM Winners</a></td></tr><tr><td><a href="/hive-122221/@hivebuzz/pud-202312-feedback"><img src="https://images.hive.blog/64x128/https://i.imgur.com/zHjYI1k.jpg"></a></td><td><a href="/hive-122221/@hivebuzz/pud-202312-feedback">Feedback from the December Hive Power Up Day</a></td></tr><tr><td><a href="/hive-122221/@hivebuzz/pum-202311-result"><img src="https://images.hive.blog/64x128/https://i.imgur.com/mzwqdSL.png"></a></td><td><a href="/hive-122221/@hivebuzz/pum-202311-result">Hive Power Up Month Challenge - November 2023 Winners List</a></td></tr></table>
properties (22)
authorhivebuzz
permlinknotify-parsteam-20231203t060719
categoryhive-169321
json_metadata{"image":["http://hivebuzz.me/notify.t6.png"]}
created2023-12-03 06:07:18
last_update2023-12-03 06:07:18
depth1
children0
last_payout2023-12-10 06:07:18
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length1,481
author_reputation369,388,574,797,661
root_title"Image processing in Python with Pillow"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id129,367,076
net_rshares0
@poshthreads ·
https://inleo.io/threads/pars.team/re-leothreads-21j9twu4g
<sub> The rewards earned on this comment will go directly to the people ( pars.team ) sharing the post on LeoThreads,LikeTu,dBuzz.</sub>
properties (22)
authorposhthreads
permlinkre-parsteam-image-processing-in-python-with-pillow-1144
categoryhive-169321
json_metadata"{"app":"Poshtoken 0.0.2","payoutToUser":["pars.team"]}"
created2023-11-13 21:45:24
last_update2023-11-13 21:45:24
depth1
children0
last_payout2023-11-20 21:45:24
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length196
author_reputation415,471,585,053,248
root_title"Image processing in Python with Pillow"
beneficiaries
0.
accountnomnomnomnom
weight10,000
max_accepted_payout1,000,000.000 HBD
percent_hbd0
post_id128,832,117
net_rshares0
@prizefund ·
!HBIT !hbit !hivebits $HBIT !WUSANG !wusang !BLAQ !blaq 👍
properties (22)
authorprizefund
permlinkre-parsteam-20231210t23853166z
categoryhive-169321
json_metadata{"tags":["development","programming","gosh","threads","hive-engine","chessbrothers","neoxian","stem","tricks","leofinance"],"app":"ecency/3.0.37-vision","format":"markdown+html"}
created2023-12-09 23:08:54
last_update2023-12-09 23:08:54
depth1
children0
last_payout2023-12-16 23:08:54
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length57
author_reputation30,363,599,460
root_title"Image processing in Python with Pillow"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id129,545,435
net_rshares0