<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>python image processing tutorial Archives - Be on the Right Side of Change</title>
	<atom:link href="https://blog.finxter.com/tag/python-image-processing-tutorial/feed/" rel="self" type="application/rss+xml" />
	<link>https://blog.finxter.com/tag/python-image-processing-tutorial/</link>
	<description></description>
	<lastBuildDate>Mon, 22 Mar 2021 20:54:12 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.9.4</generator>

<image>
	<url>https://blog.finxter.com/wp-content/uploads/2020/08/cropped-cropped-finxter_nobackground-32x32.png</url>
	<title>python image processing tutorial Archives - Be on the Right Side of Change</title>
	<link>https://blog.finxter.com/tag/python-image-processing-tutorial/</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>Python OpenCV Image Processing &#8211; Resize, Blend, Blur, Threshold, Convert</title>
		<link>https://blog.finxter.com/five-useful-image-processing-techniques-in-python-using-opencv/</link>
		
		<dc:creator><![CDATA[Hwei Geok Ng]]></dc:creator>
		<pubDate>Mon, 22 Mar 2021 20:48:17 +0000</pubDate>
				<category><![CDATA[Data Science]]></category>
		<category><![CDATA[Machine Learning]]></category>
		<category><![CDATA[Matplotlib]]></category>
		<category><![CDATA[OpenCV]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[image processing projects using opencv]]></category>
		<category><![CDATA[opencv python example]]></category>
		<category><![CDATA[opencv python image processing]]></category>
		<category><![CDATA[opencv tutorial]]></category>
		<category><![CDATA[python image processing tutorial]]></category>
		<guid isPermaLink="false">https://blog.finxter.com/?p=26735</guid>

					<description><![CDATA[<p>This tutorial is an introduction to the OpenCV library. Learn how to convert color channels, resize, blend, blur, and threshold images in Python. The OpenCV [1] library contains most of the functions we need for working with images. Handling images in programming requires a different intuition than handling text data. An image is made up ... <a title="Python OpenCV Image Processing &#8211; Resize, Blend, Blur, Threshold, Convert" class="read-more" href="https://blog.finxter.com/five-useful-image-processing-techniques-in-python-using-opencv/" aria-label="Read more about Python OpenCV Image Processing &#8211; Resize, Blend, Blur, Threshold, Convert">Read more</a></p>
<p>The post <a href="https://blog.finxter.com/five-useful-image-processing-techniques-in-python-using-opencv/">Python OpenCV Image Processing &#8211; Resize, Blend, Blur, Threshold, Convert</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>This tutorial is an introduction to the OpenCV library. Learn how to convert color channels, resize, blend, blur, and threshold images in Python.</p>



<figure class="wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
<iframe title="Python OpenCV Image Processing - Resize, Blend, Blur, Threshold, Convert" width="937" height="527" src="https://www.youtube.com/embed/M_TV4cca7oQ?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>
</div></figure>



<p>The OpenCV [1] library contains most of the functions we need for working with images. Handling images in programming requires a different intuition than handling text data. An image is made up of pixels. It looks like a spreadsheet full of cells with numerical values when zoomed in. Each pixel usually contains a value ranging between 0 to 255. The value indicates the degree of brightness for the color it is assigned to. So, how do we work with images in Python? We first need to load them as NumPy arrays, converting all image pixels into numerical values. Only then we can use different computer vision techniques to manipulate them.</p>



<div class="wp-block-image"><figure class="aligncenter size-large"><img fetchpriority="high" decoding="async" width="521" height="347" src="https://blog.finxter.com/wp-content/uploads/2021/03/image-71.png" alt="Photo by Chris Lawton on Unsplash.com." class="wp-image-26736" srcset="https://blog.finxter.com/wp-content/uploads/2021/03/image-71.png 521w, https://blog.finxter.com/wp-content/uploads/2021/03/image-71-300x200.png 300w" sizes="(max-width: 521px) 100vw, 521px" /></figure></div>



<p>In this article, we are going to get our hands dirty experimenting with images using OpenCV. We will look at techniques like color conversion, resizing, blending, blurring, and thresholding. Getting your image data right is a half-way success for a useful machine learning model. Intrigued? Let’s get started.</p>



<h2 class="wp-block-heading">Install and Import Required Modules</h2>



<p>For this tutorial, we need to install the OpenCV, NumPy, and Matplotlib modules. NumPy is used to manipulate image arrays. Matplotlib is used to display images for comparing the &#8220;before and after&#8221;. Feel free to clone the GitHub repo of <a href="https://github.com/nghweigeok/image-processing-opencv" target="_blank" rel="noreferrer noopener" title="https://github.com/nghweigeok/image-processing-opencv">this tutorial</a>.</p>



<p>First, create a virtual environment for this project. Then, install the mentioned modules in a Jupyter notebook:</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="">!pip install opencv-python  
!pip install numpy
!pip install matplotlib</pre>



<p>No surprise here &#8212; the installation should be straightforward and fast. Now execute the following lines of code in your notebook:</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 cv2
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
</pre>



<p>Note that the <em>%matplotlib inline </em>magic command is exclusive for Jupyter notebooks. It is not required in a Python script. It sets the backend of the Matplotlib module to display figures inline and not on a separate window.</p>



<p>Done! Get your favorite photos ready &#8212; it&#8217;s time for experiments!</p>



<h2 class="wp-block-heading">Load Image and Convert Color Channels</h2>



<p>To load an image in the notebook, we use the <em>imread</em> method of the OpenCV module. By default, the method loads an image in color. To load a greyscale image, we need to supply a second parameter of “0’” to the method:</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="">img_greyscale = cv2.imread('./photo.jpg', 0)
img_greyscale.shape
img = cv2.imread('./photo.jpg')
img.shape
</pre>



<p>Note that the images are loaded as NumPy arrays – one greyscale and another one in color. The <em>shape</em> method returns (5563, 3709) for the variable <em>img_greyscale</em> and (5563, 3709, 3) for <em>img</em>. The method returns information in the form of (height, width, channel). Both the variables have the same height and width values. But <em>img_greyscale</em> consists of only one channel (one color) while <em>img</em> has three.</p>



<p>By default, the <em>imread</em> method loads an image with a color order of blue, green, red. It is not the usual red, green, blue. In case you ever wonder why your images look weird in OpenCV, it is that. To display an image, use the <em>imshow</em> method of the Matplotlib module as follows:</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="">plt.imshow(img)</pre>



<div class="wp-block-image"><figure class="aligncenter size-large"><img decoding="async" width="549" height="353" src="https://blog.finxter.com/wp-content/uploads/2021/03/image-72.png" alt="" class="wp-image-26737" srcset="https://blog.finxter.com/wp-content/uploads/2021/03/image-72.png 549w, https://blog.finxter.com/wp-content/uploads/2021/03/image-72-300x193.png 300w" sizes="(max-width: 549px) 100vw, 549px" /><figcaption>Figure 1: (Left) An image with (Blue, Green, Red) color channels. (Right) The same image with (Red, Green, Blue) color channels.</figcaption></figure></div>



<p>Figure 1 shows how different an image can look when its color channels are mixed up. Matplotlib displays the red channel as blue for the image on the left. To fix this, we can use the OpenCV <em>cvtColor</em> method to convert the color channels from (B, G, R) to (R, G, B), as follows:</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="">img_RGB = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)</pre>



<p>The color-corrected image is shown on the right side of Figure 1. We will use the RGB image as an example in the latter sections. But using RGB images is not a requisite &#8212; feel free to use the BGR image if you prefer. Make sure to pick the correct channels in operation.</p>



<h2 class="wp-block-heading">Resize Image</h2>



<p>Quiz time: which OpenCV method should you use to resize an image? You guessed it &#8212; the <em>resize</em> method. It takes an image and an image dimension as parameters. The following code resizes the image to be half its original size:</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 = int(img_RGB.shape[1] / 2)
height = int(img_RGB.shape[0] / 2)

img_RGB_smaller = cv2.resize(src=img_RGB, dsize=(width, height)) 
img_RGB_smaller.shape
</pre>



<p>Note that you can supply any positive integer values to the <em>dsize</em> parameter of the <em>resize</em> method. Yet, it is a good practice to use a scale factor to keep the original aspect ratio of the image. The code shown takes the width and height values of the original image and divides them by two. The output of the <em>img_RGB_smaller.shape</em> is (2781, 1854, 3), which is 50% smaller than its original size, (5563, 3709, 3). You can also make the image larger by multiplying its width and height by two, as follows:</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 = int(img_RGB.shape[1] * 2)
height = int(img_RGB.shape[0] * 2)

img_RGB_bigger = cv2.resize(src=img_RGB, dsize=(width, height)) 
img_RGB_bigger.shape
</pre>



<p>That creates an image of size (11126, 7418, 3). Feel free to be creative with the image dimension definitions. Figure 2 shows the resized images. Both look the same because their aspect ratios are retained. Note the differences in their width and height axes instead.</p>



<div class="wp-block-image"><figure class="aligncenter size-large"><img loading="lazy" decoding="async" width="499" height="322" src="https://blog.finxter.com/wp-content/uploads/2021/03/image-74.png" alt="" class="wp-image-26741" srcset="https://blog.finxter.com/wp-content/uploads/2021/03/image-74.png 499w, https://blog.finxter.com/wp-content/uploads/2021/03/image-74-300x194.png 300w" sizes="auto, (max-width: 499px) 100vw, 499px" /><figcaption>Figure 2: (Left) An image resized to half its original size. (Right) The same image resized to double its original size.</figcaption></figure></div>



<h2 class="wp-block-heading">Blend Images</h2>



<p>Image blending means combining two images with shared transparency. We want two images to “blend into” each other as one image. For this, we need to load another image to our notebook:</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="">img_overlay = cv2.imread('./photo-overlay.jpg')
img_overlay.shape
</pre>



<p>All images used in this code project can be found at Unsplash.com. The second image is loaded as variable <em>img_overlay</em> with dimensions (2000, 1800, 3). Images must have the same size for image blending. As <em>img_overlay</em> is of a different size than the first image, we need to resize it to match the size of the first image:</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="">img_overlay = cv2.resize(img_overlay, (img_RGB.shape[1], img_RGB.shape[0]))
img_overlay.shape
</pre>



<p>Note that the <em>dsize</em> parameter takes a value in the form of (width, height), not (height, width). Thus, we enter <em>(img_RGB.shape[1], img_RGB.shape[0]) </em>as the parameter instead of the other way round. Now, the output of <em>img_overlay.shape</em> should show the same size as <em>img_RGB</em>, which is (5563, 3709, 3). Enter the following code to blend both the images together:</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="">blended = cv2.addWeighted(src1=img_RGB, alpha=0.3, src2=img_overlay, beta=0.7, gamma=0)</pre>



<p>The <em>addWeighted</em> method of OpenCV combines the images with a “transparency weightage”. The <em>src1</em> parameter takes the background image and the <em>src2</em> the foreground image. The <em>alpha</em> parameter sets the transparency of <em>src1</em> and the <em>beta</em> of <em>src2</em>. Both <em>alpha</em> and <em>beta</em> can take values ranging from 0 to 1 and should both add up to 1. A value closer to 0 indicates more transparency. A value closer to 1 indicates more opaqueness. The <em>gamma</em> parameter sets the brightness of the output image. Figure 3 shows the before and after of the image blending operation.</p>



<div class="wp-block-image"><figure class="aligncenter size-large"><img loading="lazy" decoding="async" width="331" height="436" src="https://blog.finxter.com/wp-content/uploads/2021/03/image-75.png" alt="" class="wp-image-26743" srcset="https://blog.finxter.com/wp-content/uploads/2021/03/image-75.png 331w, https://blog.finxter.com/wp-content/uploads/2021/03/image-75-228x300.png 228w" sizes="auto, (max-width: 331px) 100vw, 331px" /><figcaption>Figure 3: (Top left) The background image. (Top right) The foreground image. (Bottom) The blended image.</figcaption></figure></div>



<h2 class="wp-block-heading">Blur Image</h2>



<p>Here, we crop out a smaller section of an image to better notice the image blurring operation. Taking <em>img_RGB</em>, we copy its bottom right part as <em>img_small</em> using NumPy array slicing:</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="">img_small = img_RGB[4000:, 2000:]</pre>



<p>That will create a smaller image of size (1563, 1709, 3). There are various image blurring functions in the OpenCV module. For example, average blurring, median blurring, and Gaussian blurring. They differ in their mathematical operations and outcomes. For the sake of simplicity, we use the basic average blurring function in this tutorial. Enter the following line of code in your notebook:</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="">blurred = cv2.blur(src=img_small, ksize=(100, 100))</pre>



<p>You must have familiarized yourselves with the OpenCV parameters by now. Otherwise, press the SHIFT + TAB buttons to view any function description. The <em>ksize</em> parameter of the <em>blur</em> method defines the dimensions of the filter kernel. A kernel is like a paintbrush or sponge that you use to “smudge” the original image and make it blurry. The <em>ksize</em> parameter is the width and height of the sponge that you want to use – in this case, 100 x 100. Figure 4 shows the cropped image with its blurred after effect.</p>



<div class="wp-block-image"><figure class="aligncenter size-large"><img loading="lazy" decoding="async" width="526" height="238" src="https://blog.finxter.com/wp-content/uploads/2021/03/image-76.png" alt="" class="wp-image-26744" srcset="https://blog.finxter.com/wp-content/uploads/2021/03/image-76.png 526w, https://blog.finxter.com/wp-content/uploads/2021/03/image-76-300x136.png 300w" sizes="auto, (max-width: 526px) 100vw, 526px" /><figcaption><strong>Figure 4:</strong> (Left) A cropped image. (Right) The same image blurred with a kernel sized (100, 100).</figcaption></figure></div>



<h2 class="wp-block-heading">Threshold Image</h2>



<p>Image thresholding turns a greyscale image into either black or white pixels. You might be asking: what’s the need for blurring and thresholding images? The answer is: so that computational models can perceive image data better. Take edge detection as an example: we want to blur or smooth object edges so that there will be less noise. And we want to threshold images so object boundaries can be defined better.</p>



<p>For thresholding, we use <em>img_greyscale </em>instead of the coloured image. Enter the following one-liner in your notebook:</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="">ret, thresh1 = cv2.threshold(src=img_greyscale, thresh=127, maxval=255, type=cv2.THRESH_BINARY)</pre>



<p>The threshold method takes a greyscale image as its <em>src</em> parameter. The <em>thresh</em> parameter is the cutting-point for the black/white pixel decision. Any pixel value lower than the <em>thresh</em> value will be assigned 0. Any pixel value above the <em>thresh</em> value will be assigned 1. That creates the black-or-white contrast. As the image has its values ranged from 0 to 255, we assign the <em>maxval</em> (largest value) parameter as 255. The <em>type</em> parameter defines the kind of threshold we want. THRESH_BINARY converts all shades of grey in the image into either black or white. Figure 5 shows a greyscale image with its outcome after the thresholding operation.</p>



<div class="wp-block-image"><figure class="aligncenter size-large"><img loading="lazy" decoding="async" width="433" height="281" src="https://blog.finxter.com/wp-content/uploads/2021/03/image-77.png" alt="" class="wp-image-26745" srcset="https://blog.finxter.com/wp-content/uploads/2021/03/image-77.png 433w, https://blog.finxter.com/wp-content/uploads/2021/03/image-77-300x195.png 300w" sizes="auto, (max-width: 433px) 100vw, 433px" /><figcaption>Figure 5: (Left) A greyscale image. (Right) The image after thresholding at value 127.</figcaption></figure></div>



<p>You have just learned five useful techniques in computer vision. Well done!</p>



<h2 class="wp-block-heading">Conclusion</h2>



<p>This article elaborates on five basic image processing techniques of OpenCV. They include color conversion, resizing, blending, blurring, and thresholding. It is a step-by-step introductory tutorial to perform computer vision operations in Python.</p>



<h2 class="wp-block-heading">References</h2>



<p>[1] <a href="https://opencv.org/about/">https://opencv.org/about/</a></p>
<p>The post <a href="https://blog.finxter.com/five-useful-image-processing-techniques-in-python-using-opencv/">Python OpenCV Image Processing &#8211; Resize, Blend, Blur, Threshold, Convert</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></content:encoded>
					
		
		
			</item>
	</channel>
</rss>

<!--
Performance optimized by W3 Total Cache. Learn more: https://www.boldgrid.com/w3-total-cache/?utm_source=w3tc&utm_medium=footer_comment&utm_campaign=free_plugin

Page Caching using Disk: Enhanced 
Minified using Disk

Served from: blog.finxter.com @ 2026-06-27 16:54:07 by W3 Total Cache
-->