<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Madhavaraju on Medium]]></title>
        <description><![CDATA[Stories by Madhavaraju on Medium]]></description>
        <link>https://medium.com/@madhavarajumaddimani?source=rss-2ad559209b31------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*s2qH3ItUf_YSCLfK</url>
            <title>Stories by Madhavaraju on Medium</title>
            <link>https://medium.com/@madhavarajumaddimani?source=rss-2ad559209b31------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 04:54:51 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@madhavarajumaddimani/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Morphological Transformations Using OpenCV]]></title>
            <link>https://medium.com/@madhavarajumaddimani/morphological-transformations-using-opencv-ef2a0f46b74b?source=rss-2ad559209b31------2</link>
            <guid isPermaLink="false">https://medium.com/p/ef2a0f46b74b</guid>
            <dc:creator><![CDATA[Madhavaraju]]></dc:creator>
            <pubDate>Mon, 25 May 2026 09:11:38 GMT</pubDate>
            <atom:updated>2026-05-25T09:11:38.070Z</atom:updated>
            <content:encoded><![CDATA[<h3>What is Morphological transformation</h3><p>Morphological transformations are a set of image processing techniques based on the <strong>shape </strong>or <strong>structure</strong> of objects in an image.<br> They are mainly used on <strong>binary or grayscale images</strong> and help in tasks like <strong>noise removal</strong>, <strong>object extraction</strong>, <strong>edge detection</strong>, and <strong>image enhancement</strong>.</p><p>These operations use a small matrix called a<strong> kernel</strong> (or structuring element), which slides over the image and modifies pixel values based on the shape of the kernel and the surrounding pixels.</p><p>In simple terms, morphological transformations help you <strong>refine the structure of objects</strong> — either to <strong>remove unwanted parts (noise)</strong> or to <strong>highlight key features</strong> like edges and boundaries.</p><h3>2. Types of Morphological Transformations</h3><p>The main types of morphological transformations in OpenCV are:</p><ol><li><em>Erosion</em></li><li><em>Dilation</em></li><li><em>Opening</em></li><li><em>Closing</em></li><li><em>Morphological Gradient</em></li><li><em>Top Hat</em></li><li><em>Black Hat</em></li></ol><p><strong><em>1.Erosion</em></strong></p><p>Erosion erodes away the boundaries of foreground (Always try to keep foreground in white) objects. The kernel slides over the image and keeps a pixel only if <em>all</em> pixels under the kernel are 1.<br>So, small white noises are removed, and object boundaries become thinner.</p><p><em>Use:</em></p><ul><li>Removes small white noises</li><li>Detaches two connected objects</li></ul><pre>import cv2<br>import numpy as np<br><br>img = cv2.imread(&#39;image.jpg&#39;, 0)<br>erosion = cv2.erode(img, (3,3), iterations=1)<br># cv2.erode(image, kernel, iterations)<br>cv2.imshow(&#39;Original&#39;, img)<br>cv2.imshow(&#39;Erosion&#39;, erosion)<br>cv2.waitKey(0)<br>cv2.destroyAllWindows()</pre><p><strong><em>2. Dilation</em></strong><br> Dilation is the opposite of erosion. It adds pixels to object boundaries, making white regions larger(increases White region).</p><p><em>Use:</em></p><ul><li>Increases object area (increases White region)</li><li>Fills small holes and gaps</li></ul><pre>import cv2<br>import numpy as np<br><br>img = cv2.imread(&#39;image.jpg&#39;, 0)<br>dilation = cv2.dilate(img, (3,3), iterations=1)<br><br>cv2.imshow(&#39;Dilation&#39;, dilation)<br>cv2.waitKey(0)<br>cv2.destroyAllWindows()</pre><p><strong><em>3. Opening (Erosion → Dilation)</em></strong><br> Opening is simply <em>erosion followed by dilation</em>.<br> It helps remove small white noise from the image while keeping the shape and size of objects.</p><p><em>Use:</em></p><ul><li>Noise removal</li><li>Smoothens object outlines</li></ul><pre>import cv2<br>import numpy as np<br><br>img = cv2.imread(&#39;image.jpg&#39;, 0)<br>opening = cv2.morphologyEx(img, cv2.MORPH_OPEN, (3,3))<br><br># cv2.morphologyEx(image, morph_transform_type, kernel)<br><br>cv2.imshow(&#39;Opening&#39;, opening)<br>cv2.waitKey(0)<br>cv2.destroyAllWindows()</pre><p><strong><em>4. Closing (Dilation → Erosion)</em></strong><br> Closing is the reverse of opening — <em>dilation followed by erosion.</em><br> It helps fill small black holes inside the objects.</p><p><em>Use:</em></p><ul><li>Fill small holes in objects</li><li>Connect small gaps</li></ul><pre>import cv2<br>import numpy as np<br><br>img = cv2.imread(&#39;image.jpg&#39;, 0)<br>closing = cv2.morphologyEx(img, cv2.MORPH_CLOSE, (3,3))<br><br>cv2.imshow(&#39;Closing&#39;, closing)<br>cv2.waitKey(0)<br>cv2.destroyAllWindows()</pre><p><strong><em>5.Morphological Gradient</em></strong><br> The morphological gradient is the <em>difference between dilation and erosion.</em></p><p><em>Morphological Gradient = Dilation — Erosion</em><br> It highlights the edges or boundaries of objects.</p><p><em>Use:</em></p><ul><li>Object boundary detection</li><li>Edge enhancement</li></ul><pre>import cv2<br>import numpy as np<br><br>img = cv2.imread(&#39;image.jpg&#39;, 0)<br>gradient = cv2.morphologyEx(img, cv2.MORPH_GRADIENT, (3,3))<br><br>cv2.imshow(&#39;Gradient&#39;, gradient)<br>cv2.waitKey(0)<br>cv2.destroyAllWindows()</pre><p><strong><em>6. Top Hat (White Hat)</em></strong><br> Top Hat = <em>Original Image — Opening (substraction)</em><br> It extracts small bright regions on a dark background.</p><p><em>Use:</em></p><ul><li>Highlight small bright objects</li><li>Light spot detection</li></ul><pre>import cv2<br>import numpy as np<br><br>img = cv2.imread(&#39;image.jpg&#39;, 0)<br>tophat = cv2.morphologyEx(img, cv2.MORPH_TOPHAT, (3,3))<br><br>cv2.imshow(&#39;Top Hat&#39;, tophat)<br>cv2.waitKey(0)<br>cv2.destroyAllWindows()</pre><p><strong><em>7. Black Hat</em></strong><br> Black Hat = <em>Closing — Original Image</em><br> It extracts small dark regions on a bright background.</p><p><em>Use:</em></p><ul><li>Detect small dark spots or shadows</li><li>Enhance background contrast</li></ul><pre>import cv2<br>import numpy as np<br><br>img = cv2.imread(&#39;image.jpg&#39;, 0)<br>blackhat = cv2.morphologyEx(img, cv2.MORPH_BLACKHAT, kernel)<br><br>cv2.imshow(&#39;Black Hat&#39;, blackhat)<br>cv2.waitKey(0)<br>cv2.destroyAllWindows()</pre><h4>Conclusion :</h4><p>Morphological transformations are powerful tools in image preprocessing.<br> They help refine shapes, remove noise, fill gaps, and detect object boundaries — forming the foundation for many computer vision applications like <strong>OCR</strong>, <strong>medical imaging</strong>, and <strong>object segmentation</strong>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ef2a0f46b74b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Exploring Thresholding Techniques in OpenCV]]></title>
            <link>https://medium.com/@madhavarajumaddimani/exploring-thresholding-techniques-in-opencv-7e92dcb70502?source=rss-2ad559209b31------2</link>
            <guid isPermaLink="false">https://medium.com/p/7e92dcb70502</guid>
            <dc:creator><![CDATA[Madhavaraju]]></dc:creator>
            <pubDate>Mon, 27 Oct 2025 05:56:40 GMT</pubDate>
            <atom:updated>2025-10-27T05:56:40.484Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Thresholding in OpenCV</strong></h3><p>Thresholding is a fundamental technique in image processing that converts a grayscale image into a binary image, simplifying the analysis by distinguishing objects from the background. This process is essential for tasks like object detection, image segmentation, and preprocessing for optical character recognition (OCR).</p><h4>What is Thresholding?</h4><p>Thresholding involves setting a specific pixel intensity value, known as the threshold, and classifying all pixels in the image as either foreground or background based on their intensity. The basic idea is:</p><ul><li><strong>Foreground (object):</strong> Pixels with intensity greater than the threshold.</li><li><strong>Background:</strong> Pixels with intensity less than or equal to the threshold.</li></ul><p>This classification results in a binary image where the foreground is typically white (255) and the background is black (0).</p><h4>Global Thresholding</h4><p>In global thresholding, a single threshold value is applied uniformly across the entire image. While simple and computationally efficient, this method may not perform well in images with varying lighting conditions, as a fixed threshold might not adequately separate the foreground from the background.</p><p><strong><em>Syntax:</em></strong></p><pre>retval, dst = cv2.threshold(src, thresh, maxval, type)</pre><ul><li>src: Input grayscale image.</li><li>thresh: Threshold value.</li><li>maxval: Maximum intensity value to use with the thresholding types.</li><li>type: Type of thresholding to apply (e.g., cv2.THRESH_BINARY).</li></ul><p><strong><em>Types of Global Thresholding:</em></strong></p><ol><li><strong>cv2.THRESH_BINARY:</strong>Sets pixels greater than the threshold to maxval and all others to 0.</li><li><strong>cv2.THRESH_BINARY_INV:</strong>Inverse of THRESH_BINARY; sets pixels greater than the threshold to 0 and all others to maxval.</li><li><strong>cv2.THRESH_TRUNC:</strong>Sets pixels greater than the threshold to the threshold value and all others remain unchanged.</li><li><strong>cv2.THRESH_TOZERO:</strong>Sets pixels less than or equal to the threshold to 0 and all others remain unchanged.</li><li><strong>cv2.THRESH_TOZERO_INV:</strong>Inverse of THRESH_TOZERO; sets pixels greater than the threshold to 0 and all others remain unchanged.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QparjPO6iGQYlhBoVZuxiQ.png" /></figure><ul><li><strong><em>Binary</em> (</strong><strong>THRESH_BINARY)</strong> – Pixels above threshold → 255, below → 0</li><li><strong><em>Binary Inverse</em> (</strong><strong>THRESH_BINARY_INV)</strong> – Pixels above threshold → 0, below → 255</li><li><strong><em>Truncate</em> (</strong><strong>THRESH_TRUNC)</strong> – Pixels above threshold → threshold value, below → unchanged</li><li><strong><em>To Zero</em> (</strong><strong>THRESH_TOZERO)</strong> – Pixels above threshold → unchanged, below → 0</li><li><strong><em>To Zero Inverse</em> (</strong><strong>THRESH_TOZERO_INV)</strong> – Pixels above threshold → 0, below → unchanged</li></ul><blockquote><strong><em>Otsu’s Binarization</em></strong></blockquote><blockquote>Otsu’s method is an automatic thresholding technique that calculates the optimal threshold value by maximizing the between-class variance. It is particularly effective for bimodal images (images with two distinct pixel value distributions).</blockquote><p><strong>Syntax:</strong></p><pre>retval, dst = cv2.threshold(src, 0, 255, type + cv2.THRESH_OTSU)</pre><ul><li>src: Input grayscale image.</li><li>0: Initial threshold value (ignored by Otsu&#39;s method).</li><li>255: Maximum intensity value to use with the thresholding types.</li><li>type: Type of thresholding to apply (e.g., cv2.THRESH_BINARY).</li></ul><pre>import cv2<br><br># Read image in grayscale<br>img = cv2.imread(&quot;grayscale.jpg&quot;, cv2.IMREAD_GRAYSCALE)<br><br># Apply Otsu&#39;s thresholding<br>ret_otsu, th_otsu = cv2.threshold(img, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)<br><br># Display<br>cv2.imshow(&quot;Original&quot;, img)<br>cv2.imshow(&quot;Otsu Thresholding&quot;, th_otsu)<br><br>cv2.waitKey(0)<br>cv2.destroyAllWindows()</pre><ul><li>cv2.THRESH_OTSU automatically computes the optimal threshold.</li><li>Combined here with THRESH_BINARY to produce the final binary image.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/776/1*Pb5UMCTBibjuU_MMc8bSpQ.png" /></figure><h4>Triangle Thresholding</h4><p>Triangle thresholding is a <strong>histogram-based method</strong> that automatically finds the threshold value by forming a <strong>triangle</strong> between the histogram peak (usually background) and the farthest end of the histogram. It then selects the point on the histogram that maximizes the distance to this line as the threshold.</p><ul><li>Works well for images where foreground is much darker or lighter than the background.</li><li>Automatic and does not require prior knowledge of pixel intensity ranges.</li><li>Implemented in OpenCV as:</li></ul><pre>retval, dst = cv2.threshold(src, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_TRIANGLE)</pre><p><strong>Use Case:</strong></p><ul><li>Object detection in images with <strong>one dominant foreground</strong></li><li>Simple segmentation for images with <strong>unimodal histograms</strong></li></ul><pre>import cv2<br><br># Read image in grayscale<br>img = cv2.imread(&quot;grayscale.jpg&quot;, cv2.IMREAD_GRAYSCALE)<br><br># Apply Triangle thresholding<br>ret_triangle, th_triangle = cv2.threshold(img, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_TRIANGLE)<br><br># Display<br>cv2.imshow(&quot;Original&quot;, img)<br>cv2.imshow(&quot;Triangle Thresholding&quot;, th_triangle)<br><br>cv2.waitKey(0)<br>cv2.destroyAllWindows()</pre><ul><li>cv2.THRESH_TRIANGLE automatically finds a threshold based on the histogram shape.</li><li>Combined with THRESH_BINARY to create the binary output.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/776/1*O8HaVrmjs-s-5HU1yCEOrQ.png" /></figure><p>These techniques in OpenCV, like <strong>Otsu’s Binarization</strong> and <strong>Triangle Thresholding</strong>, are primarily used to <strong>automatically determine the optimal threshold value</strong> for an image.</p><ul><li><strong>Otsu’s Method:</strong> Analyzes the image histogram to find the threshold that <strong>maximizes the separation between background and foreground</strong>. Best suited for <strong>bimodal histograms</strong>.</li><li><strong>Triangle Thresholding:</strong> Uses the histogram to form a triangle and selects the point that <strong>maximizes the distance from the line</strong> connecting the peak to the end of the histogram. Ideal for images with <strong>one dominant foreground</strong>.</li></ul><p><strong><em>Note:</em></strong><br>These techniques do not perform thresholding on their own. They only compute the threshold value. Once the threshold is found, it is combined with global thresholding types (THRESH_BINARY, THRESH_BINARY_INV, etc.) to produce the final binary image.</p><h4>Adaptive (Local) Thresholding</h4><p>Adaptive thresholding addresses the limitations of global thresholding by calculating the threshold for each pixel based on the local neighborhood. This method is particularly useful for images with varying lighting conditions.</p><p><strong>Syntax:</strong></p><pre>dst = cv2.adaptiveThreshold(src, maxValue, adaptiveMethod, thresholdType, blockSize, C)</pre><ul><li>src: Input grayscale image.</li><li>maxValue: Maximum intensity value to use with the thresholding types.</li><li>adaptiveMethod: Adaptive method to use (cv2.ADAPTIVE_THRESH_MEAN_C or cv2.ADAPTIVE_THRESH_GAUSSIAN_C).</li><li>thresholdType: Type of thresholding to apply (cv2.THRESH_BINARY or cv2.THRESH_BINARY_INV).</li><li>blockSize: Size of the local region to calculate the threshold.</li><li>C: Constant subtracted from the calculated mean or weighted mean.</li></ul><p><em>Adaptive Methods:</em></p><ul><li><strong>cv2.ADAPTIVE_THRESH_MEAN_C:</strong>Calculates the threshold as the mean of the local neighborhood minus a constant C.</li><li><strong>cv2.ADAPTIVE_THRESH_GAUSSIAN_C:</strong>Calculates the threshold as a weighted sum of the local neighborhood values minus a constant C, with weights being a Gaussian window.</li></ul><pre>import cv2<br><br># Read image in grayscale<br>img = cv2.imread(&quot;grayscale.jpg&quot;, cv2.IMREAD_GRAYSCALE)<br><br># Adaptive Mean Thresholding<br>th_adapt_mean = cv2.adaptiveThreshold(img, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, 11, 1)<br><br># Adaptive Gaussian Thresholding<br>th_adapt_gauss = cv2.adaptiveThreshold(img, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 11, 1)<br><br># Display results<br>cv2.imshow(&quot;Original&quot;, img)<br>cv2.imshow(&quot;Adaptive Mean&quot;, th_adapt_mean)<br>cv2.imshow(&quot;Adaptive Gaussian&quot;, th_adapt_gauss)<br><br>cv2.waitKey(0)<br>cv2.destroyAllWindows()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*C_oRzFJ1phIvNhjbv1gFcw.png" /></figure><h3>Conclusion</h3><p>Thresholding is an essential image segmentation technique in computer vision that simplifies image analysis by converting grayscale images into binary form. In this experiment, we implemented different thresholding methods — <strong>Global Thresholding</strong>, <strong>Otsu’s Thresholding</strong>, <strong>Triangle Thresholding</strong>, and <strong>Adaptive Thresholding</strong> — using OpenCV.<br> Among them, <strong>Global Thresholding</strong> uses a fixed threshold, which works well for uniformly illuminated images. <strong>Otsu’s method</strong> automatically determines the optimal threshold based on image histogram variance, making it effective for bimodal images. <strong>Triangle Thresholding</strong> is suitable for skewed histograms and provides reliable results in certain cases. <strong>Adaptive Thresholding</strong> dynamically adjusts the threshold for each pixel based on its neighborhood, performing best for images with varying lighting conditions.Overall, Adaptive and Otsu’s methods generally provide the most accurate segmentation results, while global thresholding is faster but less adaptable.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7e92dcb70502" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Masking and Blurring in OpenCV: Focus, Filter, and Transform Images]]></title>
            <link>https://medium.com/@madhavarajumaddimani/masking-and-blurring-in-opencv-focus-filter-and-transform-images-cf888eef294d?source=rss-2ad559209b31------2</link>
            <guid isPermaLink="false">https://medium.com/p/cf888eef294d</guid>
            <dc:creator><![CDATA[Madhavaraju]]></dc:creator>
            <pubDate>Sun, 26 Oct 2025 05:46:16 GMT</pubDate>
            <atom:updated>2025-10-26T05:46:16.276Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>Masking and blurring are fundamental techniques in image processing:</p><ul><li><strong>Masking:</strong> Lets you <strong>focus on a specific region</strong> of an image and ignore the rest. It’s often used in object detection, segmentation, or highlighting areas of interest.</li><li><strong>Blurring:</strong> Smooths images or reduces noise using <strong>convolution filters</strong>. It’s commonly used in image preprocessing, artistic effects, and edge detection.</li><li>These operations can be combined to create <strong>powerful visual effects and pre-processing pipelines</strong>.</li></ul><h3><strong>Image Masking in OpenCV</strong></h3><p><strong><em>Step 1: Load the Image</em></strong></p><p>Before masking, you need an image to work with.</p><pre>import cv2<br>import numpy as np<br># Load the image<br>img = cv2.imread(&quot;games.jpg&quot;)<br>cv2.imshow(&quot;Original Image&quot;, img)<br>cv2.waitKey(0)<br>cv2.destroyAllWindows()</pre><ul><li>img is now a NumPy array representing the image.</li><li>cv2.imshow() lets you preview it.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/808/1*qHBZ92f4sbLfFnSuJJ2A3Q.png" /></figure><p><strong><em>Step 2: Create a Blank Mask</em></strong></p><p>The mask must have the <strong>same height and width</strong> as the original image but can be single-channel (grayscale).</p><pre># Create a black mask (all zeros)<br>mask = np.zeros(img.shape[:2], dtype=np.uint8)<br>cv2.imshow(&quot;Blank Mask&quot;, mask)<br>cv2.waitKey(0)<br>cv2.destroyAllWindows()</pre><ul><li>All zeros → completely black mask.</li><li>Only the white regions added later will reveal parts of the image.</li></ul><p><strong><em>Step 3: Define the Region of Interest (ROI)</em></strong></p><p>You can use <strong>shapes</strong> to define the ROI. Common shapes include circles, rectangles, or polygons.</p><p><em>Example 1: Circular Mask</em></p><pre># Draw a white filled circle on the mask<br>cv2.circle(mask, (200, 200), 100, 255, -1)<br>cv2.imshow(&quot;Circular Mask&quot;, mask)<br>cv2.waitKey(0)<br>cv2.destroyAllWindows()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/805/1*T4X-ln_LI102_Ro2DHC8KQ.png" /></figure><p><em>Example 2: Rectangular Mask</em></p><pre>cv2.rectangle(mask, (50, 50), (350, 300), 255, -1)<br>cv2.imshow(&quot;Rectangular Mask&quot;, mask)<br>cv2.waitKey(0)<br>cv2.destroyAllWindows()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/794/1*deWkUWFrzJO70Q_ug5TE4w.png" /></figure><p><strong><em>Step 4: Apply the Mask</em></strong></p><p>Use cv2.bitwise_and() to combine the image and the mask.</p><pre>masked_img = cv2.bitwise_and(img, img, mask=mask)<br>cv2.imshow(&quot;Masked Image&quot;, masked_img)<br>cv2.waitKey(0)<br>cv2.destroyAllWindows()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/801/1*iVW8L7D8nC4nbSLm0MEzgQ.png" /></figure><p><strong>Explanation:</strong></p><ul><li>The <strong>white region of the mask</strong> allows the original image pixels to pass through.</li><li>The <strong>black region</strong> blocks the image pixels (they become black).</li></ul><p><strong><em>Step 5: Combining Multiple Masks</em></strong></p><p>You can combine masks to extract <strong>complex regions</strong>:</p><pre>mask1 = np.zeros(img.shape[:2], dtype=np.uint8)<br>cv2.circle(mask1, (150,150), 50, 255, -1)<br>mask2 = np.zeros(img.shape[:2], dtype=np.uint8)<br>cv2.rectangle(mask2, (200,200), (350,350), 255, -1)<br><br># Combine masks using bitwise OR<br><br>combined_mask = cv2.bitwise_or(mask1, mask2)<br>masked_img = cv2.bitwise_and(img, img, mask=combined_mask)<br>cv2.imshow(&quot;Combined Mask&quot;, masked_img)<br>cv2.waitKey(0)<br>cv2.destroyAllWindows()</pre><ul><li>cv2.bitwise_or() merges multiple masks.</li><li>This allows <strong>flexible selection of multiple regions</strong>.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/805/1*xw-QsNDJchK07zgbYeiTKA.png" /></figure><p><strong><em>Step 6: Summary of Masking Steps</em></strong></p><ol><li><strong>Load Image</strong> → cv2.imread()</li><li><strong>Create Blank Mask</strong> → np.zeros()</li><li><strong>Define ROI</strong> → cv2.circle(), cv2.rectangle(), or cv2.fillPoly()</li><li><strong>Apply Mask</strong> → cv2.bitwise_and()</li><li><strong>Combine Masks (Optional)</strong> → cv2.bitwise_or()</li></ol><h3>Color-Based Masking in OpenCV</h3><p><strong><em>Steps for Color-Based Masking:</em></strong></p><ol><li><strong>Load the image</strong> in BGR format.</li><li><strong>Convert the image</strong> from BGR to HSV color space.</li><li><strong>Define the lower and upper HSV range</strong> for the color to detect.</li><li><strong>Create a binary mask</strong> where pixels within the range are white, others black.</li><li><strong>Apply the mask</strong> to the original image using a bitwise operation.</li><li><strong>Display the images</strong>: original, mask, and masked result.</li><li><strong>Adjust HSV values</strong> if needed to select different colors.</li><li><strong>Combine multiple masks</strong> if selecting multiple color ranges.</li></ol><pre>import cv2<br>import numpy as np<br><br>cv2.namedWindow(&quot;Original&quot;,cv2.WINDOW_FREERATIO)<br>cv2.namedWindow(&quot;masking&quot;,cv2.WINDOW_FREERATIO)<br>cv2.namedWindow(&quot;masked image&quot;,cv2.WINDOW_FREERATIO)<br><br>img = cv2.imread(&quot;games.jpg&quot;)<br>img_hsv = cv2.cvtColor(img,cv2.COLOR_BGR2HSV)<br>mask1 = cv2.inRange(img_hsv,np.array([162,200,200]),np.array([179,255,255]))<br>#cv2.inRange(img_hsv,lower_value,upper_value)<br><br>masked_img = cv2.bitwise_and(img,img,mask=mask1)<br><br>cv2.imshow(&quot;Original&quot;,img)<br>cv2.imshow(&quot;masking&quot;,mask1)<br>cv2.imshow(&quot;masked image&quot;,masked_img)<br><br>cv2.waitKey(0)<br>cv2.destroyAllWindows()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8RWGjm9HFE8ehGCbdYaUDg.png" /></figure><h3>Blurring Images in OpenCV: Smoothing, Noise Reduction, and Convolution</h3><p>Blurring is a <strong>technique to smooth an image</strong> by averaging or weighting pixels with their neighbors. It’s widely used in:</p><ul><li>Reducing noise</li><li>Removing small details</li><li>Preprocessing before edge detection or segmentation</li><li>Creating artistic effects</li></ul><p>Blurring works through <strong>convolution</strong>, where a <strong>kernel (filter matrix)</strong> slides over the image and computes a new pixel value based on neighboring pixels.</p><h4>Types of Blurring Filters</h4><p><strong><em>1 . Average (Mean) Blurring :</em></strong></p><ul><li>Each pixel is replaced by the <strong>average of its neighboring pixels</strong> in a kernel (e.g., 5x5).</li><li>Smooths the image uniformly but can reduce edge sharpness.</li></ul><p><strong>Use Case:</strong> Basic smoothing, reducing minor noise.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/304/1*y_RlAWoThZFC8WwzvQdMSA.png" /></figure><pre>import cv2<br>import numpy as np<br><br>img = cv2.imread(&quot;kohli.jpg&quot;)<br><br>cv2.imshow(&quot;original&quot;,img)<br>cv2.imshow(&quot;blur&quot;,cv2.blur(img,(5,5),-1))<br>#cv2.blur(img,kernel,distance)<br><br>cv2.waitKey()<br>cv2.destroyAllWindows()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/490/1*hefcQclOMgNw0CVDrL3UrQ.png" /></figure><p><strong><em>2.Median Blurring</em></strong></p><ul><li>Each pixel is replaced by the <strong>median value of neighboring pixels</strong>.</li><li>Excellent for removing <strong>salt-and-pepper noise.</strong></li></ul><p><strong>Use Case:</strong> Cleaning noisy images with discrete pixel spikes</p><pre>import cv2<br>import numpy as np<br><br>img = cv2.imread(&quot;kohli.jpg&quot;)<br>cv2.imshow(&quot;original&quot;,img)<br>cv2.imshow(&quot;median_blur&quot;,cv2.medianBlur(img,3,-1))   #rows= columns == square matrix<br><br>cv2.waitKey()<br>cv2.destroyAllWindows()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/482/1*AsvAknkqyK4bXJC6n_UO4Q.png" /></figure><p><strong><em>3.Gaussian Blurring</em></strong></p><ul><li>Each pixel is replaced by a <strong>weighted average</strong> using a Gaussian kernel.</li><li><strong>Central pixels have higher weight</strong>, preserving edges better than mean blur.</li><li><strong>Use Case:</strong> Preprocessing for edge detection or noise reduction in photography.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*R1EcKA30UavylDuUFeRleQ.png" /></figure><pre>import cv2<br>import numpy as np<br>img = cv2.imread(r&quot;C:\Users\madha\Pictures\Saved Pictures\kohli.jpg&quot;)<br>gausimg = cv2.GaussianBlur(img,(3,3),sigmaX=1,sigmaY=1)<br><br>cv2.imshow(&quot;original&quot;,img)<br>cv2.imshow(&#39;gauss&#39;,gausimg)<br><br>cv2.waitKey()<br>cv2.destroyAllWindows()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/486/1*oF2PF8q2pzorwNs5brmeOw.png" /></figure><p><strong><em>4.Bilateral Filtering</em></strong></p><ul><li>Smooths the image while <strong>preserving edges</strong>.</li><li>Works by considering <strong>both spatial distance and color difference</strong>.</li><li>Bilateral filtering <strong>smooths similar colors within a spatial neighborhood</strong> while <strong>preserving edges</strong>, unlike Gaussian blur which only considers distance.</li></ul><p><strong>Use Case:</strong> Artistic effects, cartoon-like filters, and edge-preserving smoothing.</p><pre>import cv2<br>import numpy as np<br>img = cv2.imread(&quot;kohli.jpg&quot;)<br><br>bi_img=cv2.bilateralFilter(img,-1,75,75)<br>cv2.imshow(&quot;Original&quot;,img)<br>cv2.imshow(&quot;bilateral&quot;,bi_img)<br><br>cv2.waitKey(0)<br>cv2.destroyAllWindows()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/483/1*gU0HK2AUbnjTEovTSVVE6w.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cf888eef294d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From Colors to Calculations: Exploring cvtColor, Arithmetic, and Bitwise Operations in OpenCV]]></title>
            <link>https://medium.com/@madhavarajumaddimani/from-colors-to-calculations-exploring-cvtcolor-arithmetic-and-bitwise-operations-in-opencv-36043a5fde67?source=rss-2ad559209b31------2</link>
            <guid isPermaLink="false">https://medium.com/p/36043a5fde67</guid>
            <dc:creator><![CDATA[Madhavaraju]]></dc:creator>
            <pubDate>Sun, 26 Oct 2025 05:45:47 GMT</pubDate>
            <atom:updated>2025-10-26T05:45:47.522Z</atom:updated>
            <content:encoded><![CDATA[<h3>Converting Colors with cvtColor</h3><p>Before performing arithmetic or bitwise operations, it’s often useful to <strong>convert the image to a suitable color space</strong>. OpenCV provides the cv2.cvtColor() function for this.</p><p><strong><em>Why Use </em></strong><strong><em>cvtColor?</em></strong></p><ul><li>OpenCV loads images in <strong>BGR</strong> format by default.</li><li>Certain operations (like masking, edge detection, or color-based blending) are easier in <strong>other color spaces</strong> such as:</li><li><strong>Grayscale (</strong><strong>GRAY)</strong> → simplifies processing, reduces computational load</li><li><strong>HSV (</strong><strong>HSV)</strong> → separates hue, saturation, and value, ideal for color-based operations</li><li><strong>RGB (</strong><strong>RGB)</strong> → standard color representation for visualization</li></ul><p><strong><em>How </em></strong><strong><em>cvtColor Works:</em></strong></p><ul><li>cv2.cvtColor(image, conversion_code) converts an image from one color space to another.</li><li>Common conversion codes:</li><li>cv2.COLOR_BGR2GRAY → BGR to Grayscale</li><li>cv2.COLOR_BGR2RGB → BGR to RGB</li><li>cv2.COLOR_BGR2HSV → BGR to HSV</li></ul><pre>import cv2<br>import numpy as np<br>img = cv2.imread(&quot;kohli.jpg&quot;)<br><br>gr=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)<br><br>cv2.imshow(&quot;Original&quot;,img)<br>cv2.imshow(&quot;gray&quot;,gr)<br>cv2.waitKey()<br>cv2.destroyAllWindows()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/483/1*v91ABiE2QWb5moG5SqWlDg.png" /></figure><p><strong><em>Example Use Case:</em></strong></p><ul><li>Convert a BGR image to HSV for <strong>color masking</strong> before applying bitwise operations.</li><li>Convert to Grayscale before performing <strong>arithmetic operations</strong> like adding or subtracting brightness values</li></ul><p>Arithmetic and bitwise operations are <strong>fundamental image processing tools</strong> in OpenCV. They allow you to:</p><ul><li>Modify brightness or contrast</li><li>Combine or overlay images</li><li>Perform logical operations for masking and segmentation</li></ul><p>These operations treat images as <strong>matrices of pixel values</strong> and perform calculations <strong>element-wise</strong>.</p><h3>Arithmetic Operations in OpenCV</h3><p>Arithmetic operations are <strong>mathematical operations</strong> applied to pixel values.</p><p>🔹<strong><em>1. Addition — </em></strong><strong><em>cv2.add()</em></strong></p><ul><li>Adds pixel values of two images or adds a constant brightness value.</li><li>Used for <strong>brightening images</strong> or <strong>blending two images</strong>.</li><li>OpenCV handles overflow (values &gt; 255 are clipped to 255).</li></ul><p><strong><em>🔹 2. Subtraction — </em></strong><strong><em>cv2.subtract()</em></strong></p><ul><li>Subtracts pixel values of one image from another.</li><li>Highlights <strong>differences between two images</strong> or reduces brightness.</li><li>Pixel values below 0 are clipped to 0.</li></ul><p><strong><em>🔹 3. Multiplication — </em></strong><strong><em>cv2.multiply()</em></strong></p><ul><li>Multiplies pixel values by a constant or another image.</li><li>Changes <strong>contrast</strong> — values &gt;1 increase contrast, &lt;1 decrease contrast.</li><li>Does not clip by default, but can scale intensity.</li></ul><p><strong><em>🔹 4. Division — </em></strong><strong><em>cv2.divide()</em></strong></p><ul><li>Divides pixel values by a constant or another image’s values.</li><li>Used for <strong>normalization</strong> or <strong>reducing brightness</strong>.</li><li>Helps balance lighting differences across frames.</li></ul><pre>import cv2<br>import numpy as np<br><br>cv2.namedWindow(&quot;Original&quot;,cv2.WINDOW_FREERATIO)<br>cv2.namedWindow(&quot;Addition&quot;,cv2.WINDOW_FREERATIO)<br>cv2.namedWindow(&quot;Substraction&quot;,cv2.WINDOW_FREERATIO)<br>cv2.namedWindow(&quot;Multiplication&quot;,cv2.WINDOW_FREERATIO)<br>cv2.namedWindow(&quot;Division&quot;,cv2.WINDOW_FREERATIO)<br><br><br><br>img = cv2.imread(&quot;kohli.jpg&quot;)<br>add = cv2.add(img,100)<br>sub = cv2.subtract(img,50)<br>mul = cv2.multiply(img,0.2)<br>div = cv2.divide(img,25)<br><br>cv2.imshow(&quot;Original&quot;,img)<br>cv2.imshow(&quot;Addition&quot;,add)<br>cv2.imshow(&quot;Substraction&quot;,sub)<br>cv2.imshow(&quot;Multiplication&quot;,mul)<br>cv2.imshow(&quot;Division&quot;,div)<br>cv2.waitKey()<br>cv2.destroyAllWindows()</pre><ul><li>cv2.add(img, 100) increases pixel intensity, making the image <strong>brighter</strong>.</li><li>cv2.subtract(img, 50) decreases pixel intensity, making the image <strong>darker</strong>.</li><li>cv2.multiply(img, 0.2) scales pixel values to <strong>reduce contrast and brightness</strong>.</li><li>cv2.divide(img, 25) normalizes pixel intensity, producing a <strong>dimmed effect</strong>.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6jbKtDH-UE3XfYe7k5Nq2g.png" /></figure><h3>Bitwise Operations in OpenCV</h3><p>Bitwise operations work at the <strong>binary level</strong> of pixels — each color channel value (0–255) is converted into 8-bit binary and logical operations are applied bit-by-bit.They’re mainly used in <strong>masking, segmentation, and combining shapes or ROIs</strong>.</p><p><strong><em>🔹 1. Bitwise AND — </em></strong><strong><em>cv2.bitwise_and()</em></strong></p><ul><li>Keeps only the pixels that are <strong>non-zero in both images</strong>.</li><li>Ideal for <strong>masking</strong> — selecting specific parts of an image using a binary mask.</li></ul><p><strong><em>🔹 2. Bitwise OR — </em></strong><strong><em>cv2.bitwise_or()</em></strong></p><ul><li>Keeps pixels that are <strong>non-zero in either image</strong>.</li><li>Combines two images or shapes.</li></ul><p><strong><em>🔹 3. Bitwise XOR — </em></strong><strong><em>cv2.bitwise_xor()</em></strong></p><ul><li>Keeps pixels that are <strong>non-zero in only one image (not both)</strong>.</li><li>Highlights differences between two binary images or masks.</li></ul><p><strong><em>🔹 4. Bitwise NOT — </em></strong><strong><em>cv2.bitwise_not()</em></strong></p><ul><li>Inverts pixel values (black ↔ white).</li><li>Converts a mask to its opposite — useful for background extraction.</li></ul><pre>import cv2<br>import numpy as np<br><br>img1 = np.zeros((350,350),dtype=np.uint8)<br>img2 = np.zeros((350,350),dtype=np.uint8)<br><br>shape1=cv2.circle(img1,(200,200),130,255,-1)<br>shape2=cv2.rectangle(img2,(100,50),(300,100),255,-1)<br><br><br>bit_and = cv2.bitwise_and(shape1, shape2)<br><br>bit_or = cv2.bitwise_or(shape1, shape2)<br><br>bit_xor = cv2.bitwise_xor(shape1, shape2)<br><br>bit_not = cv2.bitwise_not(shape1)<br><br>cv2.imshow(&quot;Shape 1&quot;, shape1)<br>cv2.imshow(&quot;Shape 2&quot;, shape2)<br>cv2.imshow(&quot;Bitwise AND&quot;, bit_and)<br>cv2.imshow(&quot;Bitwise OR&quot;, bit_or)<br>cv2.imshow(&quot;Bitwise XOR&quot;, bit_xor)<br>cv2.imshow(&quot;Bitwise NOT&quot;, bit_not)<br><br>cv2.waitKey(0)<br>cv2.destroyAllWindows()</pre><ul><li>cv2.bitwise_and shows the overlapping region between the two shapes.</li><li>cv2.bitwise_or combines both shapes, displaying all white regions from either image.</li><li>cv2.bitwise_xor highlights the non-overlapping parts of both shapes.</li><li>cv2.bitwise_not inverts the colors of the first shape, turning black to white and vice versa.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tucUQ1bRyA3JRgMYA6n-Ow.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/908/1*Yiz7AO-nO_Vue66IkCJjsA.png" /><figcaption>Summary</figcaption></figure><h3>Conclusion:</h3><p>In this blog, we explored some of the most fundamental yet powerful operations in OpenCV — including <strong>color conversion (</strong><strong>cvtColor)</strong>, <strong>blurring</strong>, <strong>arithmetic operations</strong>, and <strong>bitwise operations</strong>. Each of these plays a vital role in different stages of image processing.</p><ul><li><strong>Color conversion</strong> helps in transforming images between color spaces for analysis or filtering.</li><li><strong>Blurring</strong> smoothens images and reduces noise for better visual quality and preprocessing.</li><li><strong>Arithmetic operations</strong> modify image brightness and contrast.</li><li><strong>Bitwise operations</strong> enable masking, combining, and isolating specific image regions.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=36043a5fde67" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Image Augmentation with Affine Transformations in OpenCV — Making Your Dataset Smarter]]></title>
            <link>https://medium.com/@madhavarajumaddimani/image-augmentation-with-affine-transformations-in-opencv-making-your-dataset-smarter-aa25c187c91d?source=rss-2ad559209b31------2</link>
            <guid isPermaLink="false">https://medium.com/p/aa25c187c91d</guid>
            <dc:creator><![CDATA[Madhavaraju]]></dc:creator>
            <pubDate>Sun, 26 Oct 2025 05:45:13 GMT</pubDate>
            <atom:updated>2026-05-30T12:15:47.104Z</atom:updated>
            <content:encoded><![CDATA[<h3>Image Augmentation with Affine Transformations in OpenCV — Making Your Dataset Smarter</h3><h3>🌟 Introduction</h3><p>In the world of computer vision and deep learning, <strong>more data means better models</strong>.But collecting new images for training isn’t always easy — that’s where <strong>image augmentation</strong> comes in.</p><p><strong>Image Augmentation</strong> means <strong>creating new variations</strong> of existing images by applying transformations like rotation, shifting, scaling, and shearing — all while keeping the main features intact.</p><p>In this post, we’ll explore how to perform <strong>Affine Transformations</strong> in OpenCV, a powerful technique for realistic image augmentation.</p><h3>🧩 What is an Affine Transformation?</h3><p>An <strong>Affine Transformation</strong> is a <strong>linear mapping</strong> that preserves:</p><ul><li><strong>Parallelism</strong> (parallel lines remain parallel)</li><li><strong>Straightness</strong> (lines remain straight)</li><li><strong>Ratios of distances</strong></li></ul><p>In simple terms — it <strong>moves, rotates, scales, or shears an image</strong> without distorting the shapes.</p><p>Affine transformations use a <strong>2×3 matrix</strong> to define how pixels move.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/282/1*HvihEOLK7vgwj5S-dE0w0g.png" /><figcaption>Affine Transformation Matrix</figcaption></figure><p>Where:</p><ul><li>(x, y) are original coordinates</li><li>(x&#39;, y&#39;) are new coordinates</li><li>a, b, c, d → rotation/scaling/shear parameters</li><li>t_x, t_y → translation (shifting)</li></ul><h3>1️⃣ Translation using Affine Matrix</h3><p>Translation means <strong>moving an image</strong> in x and y directions.</p><pre>import cv2<br>import numpy as np<br><br>img = cv2.imread(&quot;games.jpg&quot;)<br><br>tm = np.array([[1,0,100],[0,1,50]],dtype=np.float32)<br>a = cv2.warpAffine(img,tm,dsize=(650,324))<br><br># cv2.warpAffine(image,translation matrix,dsize)<br><br>cv2.imshow(&quot;normal&quot;,img)<br>cv2.imshow(&quot;ai&quot;,a)<br>cv2.waitKey(0)<br>cv2.destroyAllWindows()</pre><ul><li>The first row [0, 1, 100] → move 100 pixels on the x-axis.</li><li>The second row [0, 1, 50] → move 50 pixels on the y-axis.</li><li>cv2.warpAffine() applies the transformation.</li></ul><p><em>Transformation Matrix:</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/193/1*Fi_fVrDYuqtZYjMj72HIGw.png" /></figure><ul><li><strong>tx</strong> → shift along X-axis (right if +ve, left if -ve)</li><li><strong>ty</strong> → shift along Y-axis (down if +ve, up if -ve)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zYJKZ16nihDu7tGuwMRBzA.png" /></figure><h3><strong>2️⃣ Rotation using Affine Transformation</strong></h3><p>We can rotate an image using OpenCV’s built-in function cv2.getRotationMatrix2D()</p><pre>import cv2<br>import numpy as np<br><br>img = cv2.imread(&quot;games.jpg&quot;)<br><br>rm = cv2.getRotationMatrix2D((650//2,324//2),45,1)<br># cv2.getRotationMatrix2D(Center,degree,scale)<br>rot = cv2.warpAffine(img,rm,(650,324))<br>cv2.imshow(&quot;Original&quot;,img)<br>cv2.imshow(&quot;Rotated Image&quot;,rot)<br><br>cv2.waitKey(0)<br>cv2.destroyAllWindows()</pre><ul><li>45 → rotation angle in degrees (positive = counterclockwise).</li><li>1.0 → scale factor (use &lt;1 to shrink, &gt;1 to enlarge).</li><li>This is a special case of an affine transform that keeps parallelism.</li></ul><p><em>Transformation Matrix:</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/295/1*T1CQK4vuux4dBTWXGsQ7FA.png" /></figure><ul><li><strong>θ (theta)</strong> → rotation angle (in degrees or radians)</li><li><strong>tx, ty</strong> → translation to reposition after rotation</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ex7kE4y_Z98kgG28qBuVjQ.png" /></figure><h3>3️⃣ Scaling (Zoom In / Out)</h3><p>Scaling increases or decreases the image size using affine matrices.</p><pre>import cv2<br>import numpy as np<br><br>tm1 = np.array([[4,0,0],[0,1,0]],dtype=np.float32)<br>tm2 = np.array([[0.5,0,0],[0,1,0]],dtype=np.float32)<br>img = cv2.imread(&quot;games.jpg&quot;)<br><br>zoom_out = cv2.warpAffine(img,tm1,dsize=(650, 324))<br>zoom_in = cv2.warpAffine(img,tm2,dsize=(650, 324))<br><br>cv2.imshow(&quot;out&quot;,zoom_in)<br>cv2.imshow(&quot;in&quot;,zoom_out)<br>cv2.waitKey(0)<br>cv2.destroyAllWindows()</pre><ul><li>Multiplying coordinates by &gt;1 enlarges the image.</li><li>Multiplying by &lt;1 shrinks it.</li></ul><p><em>Transformation Matrix:</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/229/1*IOcQ3GZ3ICAP3v7UFmq27w.png" /></figure><ul><li><strong>Sx</strong> → scale factor along X-axis</li><li><strong>Sy</strong> → scale factor along Y-axis</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Jzc1saQCZJVy1WwKo_rBXg.png" /><figcaption>i)zoom in ii) zoom out</figcaption></figure><h3>4️⃣ Shearing (Tilting the Image)</h3><p>Shearing skews the image, as if it’s slanted or stretched diagonally.</p><pre>import cv2<br>import numpy as np<br><br>img = cv2.imread(&quot;games.jpg&quot;)<br>M = np.float32([[1, 0.3, 0],<br>                [0, 1, 0]])<br>shear = cv2.warpAffine(img, M,dsize=(650, 324))<br><br>cv2.imshow(&quot;Original Image&quot;, img)<br>cv2.imshow(&quot;Sheared Image&quot;, shear)<br>cv2.waitKey(0)<br>cv2.destroyAllWindows()</pre><p><em>Transformation Matrix:</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/246/1*D-xPtFpu7JgXLbOMiHHGQg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QVl_B-C6ARxvmJgQ9ClYGg.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aa25c187c91d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[OpenCV Basics: Split, Merge, and Adjust with Trackbars]]></title>
            <link>https://medium.com/@madhavarajumaddimani/opencv-basics-split-merge-and-adjust-with-trackbars-d0a3561d6430?source=rss-2ad559209b31------2</link>
            <guid isPermaLink="false">https://medium.com/p/d0a3561d6430</guid>
            <dc:creator><![CDATA[Madhavaraju]]></dc:creator>
            <pubDate>Fri, 24 Oct 2025 04:55:50 GMT</pubDate>
            <atom:updated>2025-10-24T04:55:50.846Z</atom:updated>
            <content:encoded><![CDATA[<h3>Splitting and Merging in OpenCV</h3><p>In digital image processing, color images are typically represented using three color channels — <strong>Blue, Green, and Red (BGR)</strong> in OpenCV. Each channel contains intensity values ranging from 0 to 255 for every pixel. Understanding how to <strong>split</strong> and <strong>merge</strong> these channels is essential for color manipulation, filtering, and enhancement tasks.</p><h4>Splitting</h4><blockquote>The <strong>splitting</strong> process separates an image into its individual color channels. For example, when we split an RGB image, we obtain three grayscale images representing the intensity of the Blue, Green, and Red components respectively.</blockquote><blockquote>This helps us analyze or modify a specific channel independently — such as increasing brightness in only the red channel or applying filters to a single color layer.</blockquote><pre>import cv2<br><br>img = cv2.imread(&quot;games.jpg&quot;)<br><br># Splitting the image into its Blue, Green, and Red channels<br>blue, green, red = cv2.split(img)<br><br>cv2.imshow(&quot;Original&quot;,img)<br>cv2.imshow(&quot;Blue Channel&quot;, blue)<br>#cv2.imshow(&quot;Green Channel&quot;, green)<br>#cv2.imshow(&quot;Red Channel&quot;, red)<br><br>cv2.waitKey(0)<br>cv2.destroyAllWindows()</pre><ol><li><strong>cv2.imread(&quot;games.jpg&quot;)</strong><br> Loads the image named <em>games.jpg</em> into a variable called img.<br> The image is read in <strong>BGR format</strong> by default (Blue, Green, Red).</li><li><strong>cv2.split(img)</strong><br> This function separates the image into its <strong>individual color channels</strong> —</li></ol><ul><li>blue: stores intensity values of the blue channel</li><li>green: stores intensity values of the green channel</li><li>red: stores intensity values of the red channel</li></ul><p>3. Each channel is now a <strong>grayscale image</strong>, representing how much of that color is present at every pixel.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b5R53g0GR-loJfKXyHdKHg.png" /></figure><h4>Merging</h4><blockquote>After performing operations on individual channels, the <strong>merging</strong> process combines them back into a single color image. This allows us to visualize the effects of modifications made to each channel.Merging is commonly used after image enhancement, feature extraction, or custom color manipulation to reconstruct the final output.</blockquote><pre>import cv2<br><br>img = cv2.imread(&quot;games.jpg&quot;)<br><br># Splitting channels first<br>blue, green, red = cv2.split(img)<br><br># Merging them back to form the original image<br>merged = cv2.merge([blue, green, red])<br><br>cv2.imshow(&quot;Original&quot;,img)<br>cv2.imshow(&quot;Merged Image&quot;, merged)<br><br>cv2.waitKey(0)<br>cv2.destroyAllWindows()</pre><p>Merging combines separate color channels back into one full-color image. The function cv2.merge() stacks the channels in the <strong>order [Blue, Green, Red]</strong> to recreate the original.This step is often used after modifying individual channels.It helps visualize how color blending works in digital images.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HNQ-Qr3jRUuNfj7GFjvI-A.png" /></figure><p><strong><em>Visualizing Individual Color Channels</em></strong></p><pre>import cv2<br><br>img = cv2.imread(&quot;games.jpg&quot;)<br><br># Splitting channels first<br>blue, green, red = cv2.split(img)<br><br>z=np.zeros(blue.shape,dtype=np.uint8)  # this is for creating a blank canva<br><br>cv2.imshow(&quot;Original&quot;,img)<br>cv2.imshow(&quot;Blue Channel&quot;, cv2.merge([blue,z,z]))<br>cv2.imshow(&quot;green&quot;,cv2.merge([z,green,z]))<br>cv2.imshow(&quot;red&quot;,cv2.merge([z,z,red]))<br><br>cv2.waitKey(0)<br>cv2.destroyAllWindows()</pre><p>This code separates an image into its <strong>Blue, Green, and Red channels</strong> and allows you to visualize them individually.A <strong>blank canvas (</strong><strong>z)</strong> is used to replace other channels, so each color appears isolated in its original position.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1U-LxdbZkuLdFoqWfDwvvw.png" /></figure><h3>Understanding Window Sizes in OpenCV</h3><p>In OpenCV, <strong>windows are used to display images or videos</strong>, and controlling their size and behavior is essential for interactive image processing.</p><p><strong><em>Types of Window Resizing</em></strong></p><p>OpenCV provides two main flags when creating windows with cv2.namedWindow():</p><p>cv2.namedWindow() creates a window in OpenCV where you can control properties like resizing behavior before displaying an image.</p><pre>cv2.namedWindow(&quot;My Window&quot;, cv2.WINDOW_NORMAL)<br># cv2.namedWindow(&quot;Window name&quot;, flag)</pre><p><strong>1.cv2.WINDOW_NORMAL</strong></p><ul><li>Allows <strong>resizing the window manually</strong>.</li><li>Useful when displaying high-resolution images or when you want the window to be adjustable.</li></ul><p><strong>2.cv2.WINDOW_AUTOSIZE</strong> <em>(default)</em></p><ul><li>The window size is <strong>automatically adjusted</strong> to fit the displayed image.</li><li>You <strong>cannot resize</strong> the window manually.</li></ul><p><strong>3.cv2.WINDOW_FREERATIO</strong></p><ul><li>Lets you <strong>resize the window freely</strong> while maintaining the aspect ratio of the image.</li></ul><p><strong><em>Why Window Sizes Matter</em></strong></p><ul><li>Helps in <strong>better visualization</strong> of images and videos.</li><li>Useful when working with <strong>large images</strong> or multiple windows simultaneously.</li><li>Provides flexibility for <strong>interactive applications</strong>, like using trackbars or real-time video processing.</li></ul><pre>import cv2<br><br>img = cv2.imread(&quot;games.jpg&quot;)<br><br># Create windows with different resizing options<br>cv2.namedWindow(&quot;Normal Window&quot;, cv2.WINDOW_NORMAL)<br>cv2.namedWindow(&quot;Auto-Sized Window&quot;, cv2.WINDOW_AUTOSIZE)<br>cv2.namedWindow(&quot;Free Ratio Window&quot;, cv2.WINDOW_FREERATIO)<br><br>cv2.imshow(&quot;Normal Window&quot;, img)<br>cv2.imshow(&quot;Auto-Sized Window&quot;, img)<br>cv2.imshow(&quot;Free Ratio Window&quot;, img)<br><br>cv2.waitKey(0)<br>cv2.destroyAllWindows()</pre><ul><li><strong><em>Normal Window:</em></strong><em> </em>You can resize the window manually.</li><li><strong><em>Auto-Sized Window:</em></strong> Window adjusts automatically to image size.</li><li><strong><em>Free Ratio Window:</em></strong><em> </em>Window can be resized freely without distortion.</li></ul><h3>Trackbars in OpenCV</h3><p>Trackbars allow users to <strong>interactively adjust values</strong> in real-time, which is useful for <strong>tuning thresholds, color ranges, or filter parameters</strong>.</p><p><strong>1. cv2.createTrackbar()</strong></p><ul><li>Creates a trackbar (slider) in a window.</li></ul><p><strong><em>Syntax:</em></strong></p><pre>cv2.createTrackbar(trackbar_name, window_name, default_value, max_value, callback_function)</pre><ul><li>trackbar_name → Name of the trackbar</li><li>window_name → Window to attach the trackbar</li><li>default_value → Starting position of the slider</li><li>max_value → Maximum slider value</li><li>callback_function → Function called when trackbar value changes</li></ul><p><strong>2. cv2.getTrackbarPos()</strong></p><ul><li>Reads the <strong>current value</strong> of a trackbar.</li><li>Useful for <strong>real-time adjustments</strong>, like changing brightness or thresholds.</li><li><strong>Syntax:</strong></li></ul><pre>value = cv2.getTrackbarPos(trackbar_name, window_name)</pre><h4>Mouse Callback (cv2.setMouseCallback())</h4><p>Mouse callbacks allow interaction with the image using <strong>mouse events</strong> such as clicks, movement, or dragging.</p><ul><li><strong>Syntax:</strong></li></ul><pre>cv2.setMouseCallback(window_name, callback_function)</pre><ul><li>The callback function receives events like cv2.EVENT_LBUTTONDOWN, cv2.EVENT_MOUSEMOVE, etc., allowing you to draw, select regions, or capture coordinates.</li><li><strong>Trackbars</strong> → Slider to change values dynamically</li><li><strong>getTrackbarPos()</strong> → Read slider value in real-time</li><li><strong>Mouse callback</strong> → Detect mouse events and interact with images</li></ul><pre>import numpy as np<br>import cv2<br><br>def f1(x):<br>    pass<br><br>cv2.namedWindow(&quot;canva&quot;)<br><br>cv2.createTrackbar(&quot;blue&quot;,&quot;canva&quot;,0,255,f1)<br>cv2.createTrackbar(&quot;green&quot;,&quot;canva&quot;,0,255,f1)<br>cv2.createTrackbar(&quot;red&quot;,&quot;canva&quot;,0,255,f1)<br><br><br>while True:<br>    bl=cv2.getTrackbarPos(&quot;blue&quot;,&quot;canva&quot;)<br>    gr=cv2.getTrackbarPos(&quot;green&quot;,&quot;canva&quot;)<br>    re=cv2.getTrackbarPos(&quot;red&quot;,&quot;canva&quot;)<br><br>    bl_c = np.full((400,400),bl,dtype=np.uint8)<br>    gr_c = np.full((400,400),gr,dtype=np.uint8)<br>    re_c = np.full((400,400),re,dtype=np.uint8)<br><br>    cv2.imshow(&quot;canva&quot;,cv2.merge([bl_c,gr_c,re_c]))<br><br>    if cv2.waitKey(1) == ord(&quot;q&quot;):<br>        break<br>cv2.destroyAllWindows()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/497/1*7jt9VaA34h4jpAkzb1bRUw.png" /></figure><p>This code creates a <strong>window with three trackbars</strong> for <strong>Blue, Green, and Red</strong>. Users can <strong>adjust each color channel interactively</strong>, and the window updates in real-time to reflect the combined color.<br>cv2.getTrackbarPos() reads the current value of each slider, and cv2.merge() combines the individual channel arrays into a full-color image.Pressing <strong>“q”</strong> closes the window.</p><p><strong><em>Drawing on Images Using Mouse Callback :</em></strong></p><p>This code allows you to draw on a blank canvas interactively using the mouse.</p><ul><li>cv2.setMouseCallback() attaches the function f2 to the window &quot;canva&quot;, which handles <strong>mouse events</strong> like clicks and movement.</li><li>When the <strong>left mouse button is pressed and moved</strong>, lines are drawn in real-time from the previous point to the current cursor position.</li><li>Releasing the mouse stops drawing, and the canvas remains updated.</li><li>Press <strong>“q”</strong> to close the window.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/494/1*Nl8LxI0S9WUlmQbRLXb8xQ.png" /></figure><h3>Conclusion</h3><p>In this blog, we explored <strong>interactive image manipulation</strong> in OpenCV, covering essential tools like <strong>splitting and merging channels, window management, trackbars, and mouse callbacks</strong>.</p><ul><li><strong>Splitting and merging</strong> helps understand and manipulate individual color channels.</li><li><strong>Window management</strong> allows us to control how images and videos are displayed.</li><li><strong>Trackbars</strong> provide real-time, interactive control over image parameters like color intensity.</li><li><strong>Mouse callbacks</strong> enable direct interaction with images, such as drawing or selecting regions.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d0a3561d6430" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From Pixels to Motion: The Beginner’s Guide to Images and Videos in OpenCV]]></title>
            <link>https://medium.com/@madhavarajumaddimani/from-pixels-to-motion-the-beginners-guide-to-images-and-videos-in-opencv-b5dfcde60229?source=rss-2ad559209b31------2</link>
            <guid isPermaLink="false">https://medium.com/p/b5dfcde60229</guid>
            <dc:creator><![CDATA[Madhavaraju]]></dc:creator>
            <pubDate>Thu, 23 Oct 2025 15:43:28 GMT</pubDate>
            <atom:updated>2025-10-23T15:43:28.049Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Introduction:</strong></h3><p>Images are everywhere — from the photos we take on our phones to the visuals that help self-driving cars recognize roads. But have you ever wondered <strong>how computers understand these images</strong>? To a computer, an image isn’t a picture — it’s just a collection of numbers representing <strong>colors, brightness, and intensity</strong>.</p><p>In this post, we’ll explore how images work inside a computer and how to use <strong>OpenCV (Open Source Computer Vision Library)</strong> to <strong>read, display, and save images</strong> using Python.</p><h3><strong>How Images Work in Computers:</strong></h3><p><strong><em>Grayscale Images:</em></strong><em><br></em> Grayscale images contain only one channel — intensity — representing brightness levels from <strong>0 (black)</strong> to <strong>255 (white)</strong>. They are useful for edge detection and pattern recognition.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/310/1*RlgiS4WdPQDe6QwFLHz_ZQ.jpeg" /></figure><p><strong><em>RGB:</em></strong></p><p>Every digital image is made up of small dots called <strong>pixels</strong> (picture elements).Each pixel holds <strong>color information</strong> — usually in the form of <strong>RGB values</strong> (Red, Green, Blue).</p><p><strong><em>Let’s break it down:</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/840/1*BA09ApIssgzGTNMWgE1PjA.png" /><figcaption>RGB Color Model Information</figcaption></figure><p>For example:<br> A pixel value [255, 0, 0] means <strong>pure red</strong>,<br> [0, 255, 0] means <strong>pure green</strong>,<br> [0, 0, 255] means <strong>pure blue</strong>, and<br> [255, 255, 255] means <strong>white</strong>.</p><p>So, an image is just a <strong>3D NumPy array</strong> (rows × columns × 3 channels).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/891/1*SwW7F5l1Du8WCuhMqAuYZQ.png" /><figcaption><strong>Color Image Representation</strong>.</figcaption></figure><p><strong><em>RGBA Images:</em></strong><em><br></em> RGBA stands for <strong>Red, Green, Blue, and Alpha</strong>. The <strong>Alpha channel</strong> defines <strong>transparency</strong> — where 0 means fully transparent and 255 means fully opaque.</p><h3>Getting Started with OpenCV</h3><h4>Installing OpenCV</h4><p>Before using OpenCV, make sure it’s installed:</p><pre>pip install opencv-python<br><br># Once installed, you can import it in your Python script:<br>import cv2</pre><h3>Reading an Image</h3><p>You can read an image using <em>cv2.imread()</em>:</p><pre>import cv2<br><br># Reading an image from a file<br>img = cv2.imread(&quot;games.jpg&quot;)<br><br># Display the image in a new window<br>cv2.imshow(&quot;picture&quot;, img)<br><br># Wait until a key is pressed, then close the window<br>cv2.waitKey(0)<br>cv2.destroyAllWindows()</pre><p><strong>Explanation:</strong></p><ul><li>cv2.imread() → loads the image into a NumPy array.</li><li>cv2.imshow() → displays it in a window.</li><li>cv2.waitKey(0) → waits until you press any key.</li><li>cv2.destroyAllWindows() → closes all image windows.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/810/1*sc1qCGc1pgxDJ_wTSHuRWg.png" /><figcaption>Output Window</figcaption></figure><h3>💾 Saving an Image</h3><p>Once you process or modify an image, you can save it using <em>cv2.imwrite()</em>:</p><pre>cv2.imwrite(&quot;games2.jpg&quot;, img)</pre><h3>Checking Image Information</h3><p>Let’s print out some image properties:</p><pre>print(&quot;Shape:&quot;, img.shape)<br>print(&quot;Height:&quot;, img.shape[0])<br>print(&quot;Width:&quot;, img.shape[1])<br>print(&quot;Channels:&quot;, img.shape[2])</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/169/1*b6GDNEhzNc4RTmi3V-mlDw.png" /></figure><p>That means your image has <strong>324</strong> <strong>rows, 650 columns</strong>, and <strong>3 color channels</strong> (B, G, R).</p><h3>OpenCV Uses BGR, Not RGB</h3><p>This is an important detail — OpenCV stores color images in <strong>BGR format</strong> (Blue, Green, Red), not RGB.</p><p>OpenCV stores images in BGR format instead of RGB.So, the blue channel comes first, then green, then red.If you access pixel values, you’ll find color order as [Blue, Green, Red]. Red objects may look blue in other libraries if used directly from OpenCV.Always check channel order when working across different image tools.</p><h3><strong>Using OpenCV Functions to Draw Lines, Shapes, and Text</strong></h3><p>1️⃣ <em>Drawing a Line:</em></p><pre>import cv2<br>import numpy as np<br><br># Load an image or create a blank one<br># img = cv2.imread(&quot;games.jpg&quot;)<br># If you want a blank white canvas:<br>img = np.full((400, 600, 3), 255, dtype=np.uint8)<br><br>cv2.line(img, (50, 100), (300, 100), (0, 0, 255), 3)<br># cv2.line(img, st point, end point, color, thickness)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*ZyDhrsQNRnXHEd5g542Fpw.png" /></figure><p>2️⃣ <em>Drawing a Square , Rectangle , Circle , Ellipse:</em></p><pre>import cv2<br>import numpy as np<br><br>img1 = np.full((400, 400, 3), 255, dtype=np.uint8)<br>img2 = np.full((400, 400, 3), 255, dtype=np.uint8)<br>img3 = np.full((400, 400, 3), 255, dtype=np.uint8)<br>img4 = np.full((400, 400, 3), 255, dtype=np.uint8)<br><br>cv2.imshow(&quot;Square&quot;,cv2.rectangle(img1,(50,50),(100,100),(0,0,255),1))<br>cv2.imshow(&quot;rectangle&quot;,cv2.rectangle(img2,(50,50),(150,100),(0,0,255),1))<br># Top-left corner → (50, 50)<br># Bottom-right corner → (150, 100)<br># Color → (0,0,255) (Red)<br># Thickness → 2 (use -1 to fill the rectangle)<br><br>cv2.imshow(&quot;Circle&quot;,cv2.circle(img3,(250,250),150,(0,0,255),4))<br># Center → (400, 200)<br># Radius → 150<br># Color → (0, 0, 255) (Red)<br><br>cv2.imshow(&quot;Ellipse&quot;,cv2.ellipse(img4, (300, 300), (100, 50), 45, 0, 360, (0, 255, 255), 3))<br>#Center → (300, 300)<br>#Axes → (100, 50) (major, minor)<br>#Angle → 45° (rotation of ellipse)<br>#Start &amp; End Angle → 0 to 360 (full ellipse)<br>#Color → (0, 255, 255) (Yellow)<br><br>cv2.waitKey(0)<br>cv2.destroyAllWindows()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/997/1*qNW0r83YHpUJLmSXoeZ9Eg.png" /></figure><p>3️⃣ <strong><em>Adding Text to an Image:</em></strong></p><pre>import cv2<br>import numpy as np<br>img = np.full((400, 600, 3), 255, dtype=np.uint8)<br>cv2.putText(img, &quot;OpenCV Drawing Demo&quot;, (50, 50), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 0), 2)<br><br># OpenCV Drawing Demo → Text to display<br>#(50, 50) → Bottom-left corner of text<br>#cv2.FONT_HERSHEY_SIMPLEX → Font type<br>#1 → Font scale<br>#(0, 0, 0) → Black color<br>#2 → Thickness<br><br>cv2.imshow(&quot;Text&quot;, img)<br>cv2.waitKey(0)<br>cv2.destroyAllWindows()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/752/1*aFmqw1Zz15z50GIEpbV3vQ.png" /></figure><h3><strong>🎥 Handling Videos in OpenCV</strong></h3><p>OpenCV allows us to handle videos just like images — frame by frame.<br>We can <strong>read videos from files</strong>, <strong>count frames</strong>, or even <strong>capture live video </strong>from a webcam in real time.<br>All of this is done using the cv2.VideoCapture() function.</p><p><em>1️⃣ Reading and Displaying a Video File:</em></p><pre>import cv2<br><br>vid = cv2.VideoCapture(r&quot;C:\Users\madha\Videos\raj\video.mp4&quot;)<br><br>while True:<br>    succ, img = vid.read()   # Read frame by frame<br><br>    if succ == False:        # If no frame left, stop<br>        break<br><br>    cv2.imshow(&quot;Video Window&quot;, img)<br><br>    # Press &#39;a&#39; to stop the video<br>    if cv2.waitKey(10) &amp; 255 == ord(&quot;a&quot;):<br>        break<br>        <br>cv2.destroyAllWindows()</pre><ul><li>cv2.VideoCapture() opens the video file.</li><li>.read() reads one frame at a time (returns succ and img).</li><li>succ → returns True while frames exist, False when video ends.</li><li>cv2.imshow() displays each frame like an image.</li><li>cv2.waitKey(10) waits for 10 ms between frames (controls playback speed).</li></ul><p><em>2️⃣ Counting Total Frames in a Video:</em></p><pre>import cv2<br><br>vid = cv2.VideoCapture(r&quot;C:\Users\madha\Videos\raj\video.mp4&quot;)<br>n_f = 0<br><br>while True:<br>    succ, img = vid.read()<br><br>    if succ == False:<br>        break<br>    n_f += 1<br><br>cv2.destroyAllWindows()<br>print(&quot;Total number of frames:&quot;, n_f)</pre><ul><li>Reads each frame but doesn’t display it.</li><li>Increments n_f for every successful frame read.</li><li>When succ == False, loop ends.</li><li>The total frame count gives an idea of video duration and FPS analysis.</li></ul><p><em>3️⃣ Capturing Live Video from Webcam:</em></p><pre>import cv2<br><br>vid = cv2.VideoCapture(0)   # 0 for default webcam<br><br>while True:<br>    succ, img = vid.read()<br><br>    if succ == False:<br>        break<br><br>    cv2.imshow(&quot;Live Video&quot;, img)<br><br>    # Press &#39;a&#39; to exit live feed<br>    if cv2.waitKey(1) &amp; 255 == ord(&quot;a&quot;):<br>        break<br>        <br>cv2.destroyAllWindows()</pre><ul><li>cv2.VideoCapture(0) starts capturing video from your <strong>default webcam</strong>.</li><li>Displays live feed frame by frame using cv2.imshow().</li><li>cv2.waitKey(1) ensures a smooth real-time display.</li><li>Press &#39;a&#39; anytime to stop live capturing.</li></ul><h3><strong>Creating Simple Animations in OpenCV</strong></h3><p>OpenCV isn’t just for processing images and videos — you can also create <strong>frame-by-frame animations</strong>.Animations in OpenCV are made by <strong>updating image frames continuously in a loop</strong>, just like how videos work.</p><p>Let’s see a simple example of creating a <strong>bouncing ball animation</strong> using NumPy and OpenCV.</p><p>Example: <em>Moving Ball Animation</em></p><pre>import cv2<br>import numpy as np<br><br>cv2.namedWindow(&quot;ball&quot;)<br><br>points = [<br>    (50,50),(60,60),(70,80),(80,90),(90,105),(100,120),(110,105),<br>    (120,90),(135,75),(150,50),(160,70),(170,80),(180,90),(200,80),<br>    (210,70),(220,60),(240,55),(250,50),(260,60),(270,65),(280,70),<br>    (300,75),(320,65),(330,60),(340,50),(350,50),(370,50),(390,50),(400,50)<br>]<br><br>for (x, y) in points:<br>    frame = np.full((300, 500, 3), 255, dtype=np.uint8)  <br>    cv2.circle(frame, (x, y), 10, (0, 0, 255), -1)         <br>    cv2.imshow(&quot;ball&quot;, frame)<br>    if cv2.waitKey(200) &amp; 255 == ord(&#39;a&#39;): <br>        break<br><br>cv2.destroyAllWindows()</pre><ul><li><strong>Custom Path Points:</strong>The list points defines the (x, y) coordinates of the ball at each frame. This creates a <strong>complex movement path</strong> rather than a straight line.</li><li><strong>Frame-by-Frame Drawing:</strong>For each point, a new blank frame is created and the ball is drawn at the current position using cv2.circle().</li><li><strong>Animation Timing:</strong>cv2.waitKey(200) controls the speed of animation. Smaller value → faster movement; larger value → slower movement.</li><li><strong>Interactive Exit:</strong>Press &#39;a&#39; at any time to stop the animation.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b5dfcde60229" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Automation: The Invisible Partner Behind Everyday Tasks]]></title>
            <link>https://medium.com/@madhavarajumaddimani/automation-the-invisible-partner-behind-everyday-tasks-bb6e366116ff?source=rss-2ad559209b31------2</link>
            <guid isPermaLink="false">https://medium.com/p/bb6e366116ff</guid>
            <dc:creator><![CDATA[Madhavaraju]]></dc:creator>
            <pubDate>Tue, 14 Oct 2025 14:36:08 GMT</pubDate>
            <atom:updated>2025-10-14T14:36:08.472Z</atom:updated>
            <content:encoded><![CDATA[<p>Automation is everywhere — from the moment your alarm syncs with your calendar to the instant your online order arrives at your doorstep. Yet, most of us rarely notice it working behind the scenes. This invisible technology quietly shapes how we live, work, and connect, making our lives smoother, faster, and more efficient than ever before.</p><h3>🔹 What is Automation?</h3><p>In simple terms, <strong>automation</strong> means using technology to perform tasks with minimal or no human intervention.</p><p>The term <em>“automation”</em> was first introduced in <strong>1946</strong> by <strong>General Motors</strong> to describe the use of automatic machinery in manufacturing. However, today it extends far beyond factories — it powers industries like <strong>finance, healthcare, agriculture, IT, and even retail</strong>.</p><p>Automation helps:</p><ul><li>Save time and labor costs</li><li>Improve accuracy and consistency</li><li>Increase productivity</li><li>Allow humans to focus on creative and strategic work</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ECCpEksH-yv-4dCcdTJMyg.jpeg" /></figure><h3>⚙️ What is Tech Automation?</h3><p><strong>Tech Automation</strong> refers to the use of advanced technologies like <strong>Artificial Intelligence (AI)</strong>, <strong>Machine Learning (ML)</strong>, and <strong>Robotic Process Automation (RPA)</strong> to perform digital tasks automatically.</p><p>For example:</p><ul><li>AI algorithms predict failures before they occur.</li><li>RPA bots handle data entry and invoice processing.</li><li>Cloud tools manage system monitoring and backups automatically.</li></ul><p>In short, tech automation allows businesses to run smarter, faster, and with fewer errors.</p><h3>🧩 Types of Automation</h3><p>Automation is not “one-size-fits-all.” Depending on flexibility, scale, and complexity, it can be categorized into several types.</p><h3>1. Fixed Automation</h3><p>Used mainly in <strong>mass production</strong>, fixed automation involves machines designed for specific, repetitive tasks.<br> Once set up, the system runs continuously with high efficiency — but changing it later is costly.</p><p><strong>Example:</strong><br> Automobile assembly lines where robots perform welding, painting, or assembly tasks repeatedly.</p><h3>2. Programmable Automation</h3><p>This type of automation allows flexibility by <strong>reprogramming machines</strong> for different products or batches. It’s common in <strong>batch production</strong> environments.</p><p><strong>Example:</strong><br> <strong>CNC machines</strong> that can cut, engrave, or drill materials based on customized digital instructions.</p><h3>3. Flexible Automation</h3><p>Flexible automation can quickly switch between different tasks with minimal setup. It’s ideal for industries where products frequently change.</p><p><strong>Example:</strong><br> In automotive factories, <strong>robotic arms</strong> perform multiple operations — from assembling to painting — with minimal downtime.</p><h3>4. Software Automation</h3><p>Software automation uses digital tools to perform repetitive computer-based tasks automatically — like managing files, processing data, or sending emails.</p><p><strong>Example:</strong><br> Tools like <strong>Zapier</strong>, <strong>UiPath</strong>, or <strong>Microsoft Power Automate</strong> can automate workflows such as updating spreadsheets, sending notifications, or generating reports.</p><h3>5. Robotic Process Automation (RPA)</h3><p>RPA uses <strong>software robots</strong> to mimic human actions on computers. It’s best for repetitive, rule-based tasks that don’t require decision-making.</p><p><strong>Example:</strong><br> Processing invoices, managing payroll, or updating customer databases automatically — saving hours of manual work.</p><h3>6. AI-Powered Automation</h3><p>AI automation takes things to the next level. Using <strong>machine learning</strong> and <strong>natural language processing</strong>, it can make decisions, analyze data, and even interact with humans.</p><p><strong>Examples:</strong></p><ul><li>Predictive maintenance in factories (AI predicts equipment failure).</li><li>Smart assistants and chatbots like <strong>ChatGPT</strong> or <strong>Alexa</strong>.</li><li>Personalized recommendations on platforms like Netflix or Amazon.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jBxj0WxnbDhW46KJFbFR-w.png" /></figure><h3>Conclusion</h3><p>Automation isn’t about replacing humans — it’s about empowering us to do more with less effort.<br> From factories to finance, automation is driving a new era of innovation, efficiency, and growth.</p><p>As technology continues to evolve, the world will rely increasingly on smart, self-operating systems — and those who understand automation will shape the future.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bb6e366116ff" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Regex in Python]]></title>
            <link>https://medium.com/@madhavarajumaddimani/regex-in-python-ee1d4959b58e?source=rss-2ad559209b31------2</link>
            <guid isPermaLink="false">https://medium.com/p/ee1d4959b58e</guid>
            <dc:creator><![CDATA[Madhavaraju]]></dc:creator>
            <pubDate>Wed, 30 Jul 2025 05:33:09 GMT</pubDate>
            <atom:updated>2025-07-30T05:33:09.057Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>What is Regex / Regular Expression?</strong></h3><p>Regular Expressions, or <strong>regex</strong>, are a powerful tool used to search, match, and manipulate strings based on specific patterns. Think of regex as a <strong>mini-language inside Python</strong> (and many other languages), built especially for <strong>pattern recognition</strong> in text.</p><p>In Python, regex is powered by the built-in re module.</p><p><strong>Example:</strong></p><pre>import re<br>pattern = r&quot;\d+&quot;<br>text = &quot;There are 123 apples&quot;<br>match = re.findall(pattern, text)<br>print(match)  # [&#39;123&#39;]</pre><p>💡 <strong>Regex in Action: Practical Use Cases for Data Extraction, Validation, and More</strong></p><p><em>1.📤 </em><strong><em>Data Extraction:</em></strong>Regex helps us pull out specific pieces of information from large text data.</p><pre># Extracting dates<br>text = &quot;Order placed on 2025-07-29 and delivered on 2025-08-01&quot;<br>dates = re.findall(r&quot;\d{4}-\d{2}-\d{2}&quot;, text)</pre><p><strong><em>2. </em></strong><em>✅ </em><strong><em>Data Validation: </em></strong>Regex is useful for checking if a piece of data is in the correct format.</p><pre># Validating a PIN code<br>re.match(r&quot;^\d{6}$&quot;, &quot;600042&quot;)  # True if valid 6-digit PIN</pre><p><strong><em>3.</em></strong><em>🔎 </em><strong><em>Search and Replace:</em> </strong>Regex can find certain patterns in text and replace them with something else.</p><pre># Replace all digits with X<br>re.sub(r&quot;\d&quot;, &quot;X&quot;, &quot;My ID is 123456&quot;)  # Output: My ID is XXXXXX</pre><p><strong><em>4.</em></strong><em>🌐 </em><strong><em>Web Scraping Support: </em></strong>When scraping websites using tools like BeautifulSoup or requests, regex can help pick out the needed text.</p><pre># Extract prices like ₹999 from HTML<br>re.findall(r&quot;₹\d+&quot;, html_text)</pre><p><em>5. 🧠 </em><strong><em>Natural Language Processing (NLP): </em></strong>in<strong><em> </em></strong>NLP, regex helps clean and prepare text data for analysis.</p><pre># Remove URLs from text<br>re.sub(r&quot;http\S+&quot;, &quot;&quot;, text)</pre><p><strong>Key Benefits of Regex:</strong></p><ul><li><strong>Compact &amp; Powerful</strong>: One line of regex can replace multiple lines of string manipulation code.</li><li><strong>Highly Flexible</strong>: You can create custom patterns for very specific use cases.</li><li><strong>Cross-Language Portability</strong>: Regex works similarly in many languages (JavaScript, Java, PHP, etc.).</li><li><strong>Efficient Searching</strong>: Much faster than traditional string searching in large texts.</li><li><strong>Cleaner Code</strong>: Avoids complicated loops and if-else structures.</li></ul><p><strong>Components of Regex:</strong></p><p><em>1️⃣ </em><strong><em>Literal Characters:</em> Literals</strong> are the most basic form of regex — they match exactly what they look like.</p><pre># cat matches only the word “cat”<br># 123 matches only “123”<br><br>import re<br>re.search(r&quot;apple&quot;, &quot;apple pie&quot;)  # Match found</pre><p><em>2️⃣ </em><strong><em>Meta characters:</em> Metacharacters</strong> have special meanings in regex. They <strong>do not represent themselves</strong>, but perform pattern-related functions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3vgjMwLkSDNyakqdksHELg.png" /></figure><pre>re.search(r&quot;c.t&quot;, &quot;cat&quot;)  # Matches because . matches any character</pre><p><em>3️⃣ </em><strong><em>User-Defined / Custom Characters:</em></strong>These are created using square brackets [] to match <strong>any one character from a set</strong> you define.</p><p>✅ <strong>Examples</strong>:</p><ul><li>[aeiou] → match any lowercase vowel</li><li>[A-Za-z] →match any letter (upper or lower case)</li><li>[0-9] or [123] →match any digit from 0–9 or only 1, 2, or 3</li></ul><p>You can also use <strong>ranges and negation</strong>:</p><ul><li>[^0-9] → match anything <em>except</em> a digit</li></ul><pre>re.findall(r&quot;[aeiou]&quot;, &quot;Regex is powerful&quot;)  # Matches all vowels</pre><p><em>4️⃣</em><strong><em>Predefined Characters: </em></strong>These are <strong>shorthand notations</strong> that represent commonly used groups of characters.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/775/1*Axp3VVCdRGzfwXl4ENd_Tw.png" /></figure><p><strong><em>5️⃣ Groups and Capturing: </em>Parentheses </strong><strong>()</strong> are used to group parts of a regex. Groups let you:</p><ul><li>Apply quantifiers to the whole group</li><li>Extract specific matched sections (capturing groups)</li></ul><pre>match = re.search(r&quot;(\d{4})-(\d{2})-(\d{2})&quot;, &quot;Date: 2025-07-29&quot;)<br>print(match.group(1))  # &#39;2025&#39;<br>print(match.group(2))  # &#39;07&#39;<br>print(match.group(3))  # &#39;29&#39;</pre><p><strong><em>6️⃣ Quantifiers: </em>Quantifiers</strong> control how many times a character or group should repeat.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/927/1*K8X-3ml_PWUlva_2qWkx9Q.jpeg" /></figure><pre>re.findall(r&quot;a{2,3}&quot;, &quot;caaat&quot;)  # [&#39;aaa&#39;]</pre><h3>Regex Functions:</h3><p>The re module in Python provides various functions that help search, match, and manipulate strings using regular expressions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/702/1*sT007AmyM8v11R1XUrlC1g.png" /></figure><p><em>Example:</em></p><pre>import re<br><br>text = &quot;Contact us at support@example.com or call 987-654-3210.&quot;<br><br># re.findall()<br>emails = re.findall(r&#39;\S+@\S+&#39;, text)<br>print(&quot;findall:&quot;, emails)  # [&#39;support@example.com&#39;]<br><br># re.compile()<br>phone_pattern = re.compile(r&#39;\d{3}-\d{3}-\d{4}&#39;)<br>phones = phone_pattern.findall(text)<br>print(&quot;compile:&quot;, phones)  # [&#39;987-654-3210&#39;]<br><br># re.split()<br>words = re.split(r&#39;\s+&#39;, text)<br>print(&quot;split:&quot;, words)  # [&#39;Contact&#39;, &#39;us&#39;, &#39;at&#39;, &#39;support@example.com&#39;, &#39;or&#39;, &#39;call&#39;, &#39;987-654-3210.&#39;]<br><br># re.sub()<br>masked_text = re.sub(r&#39;\d&#39;, &#39;*&#39;, text)<br>print(&quot;sub:&quot;, masked_text)  # Contact us at support@example.com or call ***-***-****.<br><br># re.subn()<br>new_text, count = re.subn(r&#39;call&#39;, &#39;CALL&#39;, text)<br>print(&quot;subn:&quot;, new_text, &quot;| count:&quot;, count)  # Contact us at support@example.com or CALL 987-654-3210. | count: 1<br><br># re.escape()<br>special = re.escape(&quot;support@example.com (urgent)?&quot;)<br>print(&quot;escape:&quot;, special)  # support@example\.com\ \(urgent\)\?<br><br># re.search()<br>match = re.search(r&#39;\d{3}&#39;, text)<br>print(&quot;search:&quot;, match.group())  # 987</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ee1d4959b58e" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>