<?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 Md. Abdullah Al Mamun on Medium]]></title>
        <description><![CDATA[Stories by Md. Abdullah Al Mamun on Medium]]></description>
        <link>https://medium.com/@mamuncseru?source=rss-14125a1764a6------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>Stories by Md. Abdullah Al Mamun on Medium</title>
            <link>https://medium.com/@mamuncseru?source=rss-14125a1764a6------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 20:00:22 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mamuncseru/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[Food Scan Fun with Google Gemini: Building Your Food Recognition App]]></title>
            <link>https://mamuncseru.medium.com/food-scan-fun-with-google-gemini-building-your-food-recognition-app-e3f919fa1c79?source=rss-14125a1764a6------2</link>
            <guid isPermaLink="false">https://medium.com/p/e3f919fa1c79</guid>
            <category><![CDATA[food]]></category>
            <category><![CDATA[google-gemini-pro]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[large-language-models]]></category>
            <category><![CDATA[gemini]]></category>
            <dc:creator><![CDATA[Md. Abdullah Al Mamun]]></dc:creator>
            <pubDate>Sat, 20 Jan 2024 16:01:48 GMT</pubDate>
            <atom:updated>2024-01-20T16:01:48.134Z</atom:updated>
            <content:encoded><![CDATA[<p>Calling all foodies and tech enthusiasts! Imagine whipping out your phone, pointing it at a plate of deliciousness, and instantly having access to a wealth of information about the food you’re about to devour. It sounds like magic, right? Well, with the power of Google Gemini, it’s not just a fantasy—it&#39;s a reality you can build yourself!</p><figure><img alt="Table of foods scanned by AI (Google Gemini)" src="https://cdn-images-1.medium.com/max/1024/1*SaeZvlg7MYOsmTt3Fe8M5A.png" /></figure><p>In this blog post, we’ll embark on a delicious journey, guiding you through the process of creating your very own food scan app using Google Gemini. No core coding experience is needed, just a healthy dose of curiosity and a love for all things food!</p><h3>Step 1: Setup your kitchen (environment!)<br>Create a Python virtual environment</h3><h3>Windows:</h3><p>Creating a Python virtual environment on Windows is a straightforward process. Here are the steps using the built-in venv module, assuming you have Python installed on your system:</p><p>Open a Command Prompt:</p><p>Open the Command Prompt by pressing Win + R, typing cmd, and pressing Enter.</p><p>Navigate to the desired directory:</p><p>Use the cd command to navigate to the directory where you want to create the virtual environment. For example:</p><p><em>cd path\to\your\desired\directory</em></p><p>Create the virtual environment:</p><p>Run the following command to create a virtual environment named “venv” (you can replace “venv” with any name you prefer):</p><p><em>python -m venv venv</em></p><p>Note: Ensure that you have Python added to your system PATH. If not, you might need to provide the full path to the Python executable, like <em>C:\Path\to\python.exe -m venv venv.</em></p><p>Activate the virtual environment:</p><p>To activate the virtual environment, run the following command:</p><p><em>venv\Scripts\activate</em></p><p>After activation, your command prompt should show the virtual environment name in the prompt, indicating that you are now working within the virtual environment.</p><p>Example:</p><p><em>(venv) C:\path\to\your\desired\directory&gt;</em></p><h3>Ubuntu/Mac:</h3><p>Creating a Python virtual environment on Ubuntu is similar to the process on Windows, but the commands are slightly different. Here’s how you can do it:</p><p>Install virtualenv:</p><ul><li>If you haven’t installed virtualenv yet, you can do so using pip. Open a terminal and run:</li></ul><p><em>sudo apt update</em></p><p><em>sudo apt install python3-pip</em></p><p><em>pip3 install virtualenv</em></p><p>Navigate to the desired directory:</p><ul><li>Use the cd command to navigate to the directory where you want to create the virtual environment. For example: <em>cd /path/to/your/desired/directory</em></li></ul><p>Create the virtual environment:</p><ul><li>Run the following command to create a virtual environment named “venv” (you can replace “venv” with any name you prefer):</li></ul><p><em>virtualenv myenv</em></p><p>Activate the virtual environment:</p><ul><li>To activate the virtual environment, run the following command: <em>source venv/bin/activate</em></li><li>After activation, your command prompt should show the virtual environment name in the prompt, indicating that you are now working within the virtual environment.<br>Example: <em>(venv) user@hostname:/path/to/your/desired/directory$</em></li></ul><h3>Step 2: Gather your ingredients (tools, not food!)</h3><ul><li>Google Gemini API Key: This powerful language model from Google AI will be the brains behind your app, identifying and analyzing food images. To get the API key for free, go to <a href="https://makersuite.google.com/">https://makersuite.google.com/</a> login and click on Get API Key on the left. After that, click on Create API Key in the new project. Here you will get the API key. Copy the API key and keep it in the .env file in the project.</li><li>Install the necessary packages</li><li><em>pip install streamlit google-generativeai dotenv pillow</em></li><li>or</li></ul><pre>requirements.txt<br><br>streamlit<br>google-generativeai<br>dotenv<br>pillow<br><br>pip install -r requirements.txt</pre><p>Streamlit:</p><ul><li>Purpose: Streamlines the development and deployment of web applications for data scientists and machine learning engineers.</li><li>Key features:</li><li>Simple API for creating interactive web apps with pure Python code.</li><li>Live updates: apps update as you code.</li><li>Supports a wide range of data visualizations and widgets.</li><li>Deployment options for sharing apps with others.</li></ul><p>google-generativeai:</p><ul><li>Purpose: Provides access to Google’s Generative AI API, enabling text-based AI capabilities like text generation, translation, and question-answering.</li><li>Key features:</li><li>Generates text, translates languages, and answers your questions in an informative way.</li><li>Leverages Google AI’s powerful text-based models.</li></ul><p>python-dotenv:</p><ul><li>Purpose: Loads environment variables from a .env file, keeping sensitive information out of code and version control.</li><li>Key features:</li><li>Simplifies configuration management.</li><li>Protects secrets and API keys.</li></ul><p>Pillow:</p><p>Pillow is a powerful library for manipulating and analyzing images in Python. It supports a wide range of image formats, including JPEG, PNG, GIF, and TIFF.</p><p>It offers numerous features for:</p><ul><li>Opening and saving images: Read and write images in various formats.</li><li>Image manipulation: Resize, rotate, crop, and modify images in various ways.</li><li>Pixel access and manipulation: Access and modify individual pixels within an image.</li><li>Drawing and shapes: Draw on images with lines, rectangles, circles, and other shapes.</li><li>Filters and effects: Apply different filters and effects to your images.</li><li>Conversions: Convert images between different color spaces and formats</li></ul><h3>Step 3: Let’s start Cooking (coding!)</h3><ol><li>Create a Python file name app.py</li></ol><ul><li>Import necessary libraries:</li></ul><pre>import streamlit as st<br>import os<br><br>from PIL import Image<br>import google.generativeai as genai<br>from dotenv import load_dotenv</pre><ul><li>Load the api key:</li></ul><pre>load_dotenv()<br><br>genai.configure(api_key=os.getenv(&quot;GOOGLE_API_KEY&quot;))</pre><ul><li>Creating a GenerativeModel Instance:</li></ul><pre>model = genai.GenerativeModel(&#39;gemini-pro-vision&#39;)</pre><p>model = genai.GenerativeModel(&#39;gemini-pro-vision&#39;) instantiates a GenerativeModel object, representing the &quot;gemini-pro-vision&quot; model.</p><p>This model possesses unique abilities: Multimodal: It accepts and seamlessly combines text and images as input. Versatile: It excels in various tasks, including text generation, translation, question-answering, and visual understanding.</p><ul><li>Create a Function to get the image details:</li></ul><pre>def input_image_details(uploaded_file):<br>    if uploaded_file is not None:<br>        bytes_data = uploaded_file.getvalue()<br><br>        image_parts = [<br>            {<br>                &quot;mime_type&quot;: uploaded_file.type,<br>                &quot;data&quot;: bytes_data<br>            }<br>        ]<br><br>        return image_parts<br>    else:<br>        raise FileNotFoundError(&quot;No file uploaded&quot;)</pre><p>The input_image_details function takes an uploaded file, typically from a Streamlit file uploader, and extracts relevant details such as MIME type and byte data. It checks if the uploaded file is not None, indicating a successful upload. If a file is present, it retrieves its byte data and MIME type, encapsulates them in a list of dictionaries representing image parts, and returns this information. If no file is uploaded, it raises a FileNotFoundError with the message &quot;No file uploaded.&quot; The function is designed to be part of an image processing or analysis workflow, providing a structured representation of the uploaded image for further processing within a Streamlit application.</p><ul><li>Create a Function the get the response from Gemini LLM</li></ul><pre>def get_gemini_response(input, image, prompt):<br>    response = model.generate_content([input, image[0], prompt])<br>    return response.text</pre><p>This Python function seamlessly integrates text, images, and prompts to generate creative responses from the Gemini AI model: It takes three inputs — text, an image, and a prompt — and sends them to the model, crafting a response that blends all three elements, demonstrating Gemini’s ability to process multimodal information and create novel text based on diverse inputs.</p><ul><li>Create UI with Streamlit</li></ul><p>This code snippet lays the foundation for an interactive food scanning app using Streamlit and Gemini, crafting a user-friendly interface for image uploads and prompt input, setting the stage for food analysis and exploration.</p><pre><br>st.set_page_config(page_title=&quot;Food Scan&quot;)<br><br>st.header(&#39;Food Scan with Google Gemini&#39;)<br>input = st.text_input(&quot;Input prompt: &quot;, key=&#39;input&#39;)<br>uploaded_file = st.file_uploader(&quot;Choose an image of the food or food table&quot;, type=[&quot;jpg&quot;, &#39;jpeg&#39;, &#39;png&#39;])<br>image = &quot;&quot;<br>if uploaded_file is not None:<br>    image = Image.open(uploaded_file)<br>    st.image(image, caption=&quot;Uploaded Image&quot;, use_column_width=True)<br><br>submit = st.button(&quot;Scan the Food(s)&quot;)</pre><p>The code configures the Streamlit page with the title “Food Scan” using st.set_page_config. It then adds a header to the page, displaying &quot;Food Scan with Google Gemini.&quot; The code includes a text input widget for users to enter a prompt related to food, a file uploader for selecting an image file of food or a food table, and an area to display the uploaded image. The image, if uploaded, is opened using the Image module from the Python Imaging Library (PIL) and displayed using st.image. Finally, a button labeled &quot;Scan the Food(s)&quot; is provided for users to initiate a food scanning action. The code suggests an interactive interface for users to input prompts, upload images, and trigger the scanning process, involving the Google Gemini model for content generation or analysis related to food.</p><ul><li>Let’s create the prompt. For example, I created this one for this app. You can change according to your needs.</li></ul><pre>input_prompt = &quot;&quot;&quot;<br>You have to identify different types of food in images. <br>The system should accurately detect and label various foods displayed in the image, providing the name <br>of the food and its location within the image (e.g., bottom left, right corner, etc.). Additionally, <br>the system should extract nutritional information and categorize the type of food (e.g., fruits, vegetables, grains, etc.) <br>based on the detected items. The output should include a comprehensive report or display showing the<br>identified foods, their positions, names, and corresponding nutritional details.<br>&quot;&quot;&quot;</pre><ul><li>Submit to Gemini Vision API:</li></ul><pre>if submit:<br>    image_data = input_image_details(uploaded_file)<br>    response = get_gemini_response(input_prompt, image_data, input)<br>    st.subheader(&quot;Food Scan report: &quot;)<br>    st.write(response)</pre><p>This code block orchestrates the food scanning process, expertly blending user input, image analysis, and Gemini’s insights to generate a comprehensive food scan report, effortlessly bridging user interaction and AI-powered exploration.</p><ul><li>Here is the complete code</li></ul><pre>import streamlit as st<br>import os<br><br>from PIL import Image<br>import google.generativeai as genai<br>from dotenv import load_dotenv<br><br>load_dotenv()<br><br>genai.configure(api_key=os.getenv(&quot;GOOGLE_API_KEY&quot;))<br><br>model = genai.GenerativeModel(&#39;gemini-pro-vision&#39;)<br><br>def get_gemini_response(input, image, prompt):<br>    response = model.generate_content([input, image[0], prompt])<br>    return response.text<br><br>def input_image_details(uploaded_file):<br>    if uploaded_file is not None:<br>        bytes_data = uploaded_file.getvalue()<br><br>        image_parts = [<br>            {<br>                &quot;mime_type&quot;: uploaded_file.type,<br>                &quot;data&quot;: bytes_data<br>            }<br>        ]<br><br>        return image_parts<br>    else:<br>        raise FileNotFoundError(&quot;No file uploaded&quot;)<br>    <br>st.set_page_config(page_title=&quot;Food Scan&quot;)<br><br>st.header(&#39;Food Scan with Google Gemini&#39;)<br>input = st.text_input(&quot;Input prompt: &quot;, key=&#39;input&#39;)<br>uploaded_file = st.file_uploader(&quot;Choose an image of the food or food table&quot;, type=[&quot;jpg&quot;, &#39;jpeg&#39;, &#39;png&#39;])<br>image = &quot;&quot;<br>if uploaded_file is not None:<br>    image = Image.open(uploaded_file)<br>    st.image(image, caption=&quot;Uploaded Image&quot;, use_column_width=True)<br><br>submit = st.button(&quot;Scan the Food(s)&quot;)<br><br>input_prompt = &quot;&quot;&quot;<br>You have to identify different types of food in images. <br>The system should accurately detect and label various foods displayed in the image, providing the name <br>of the food and its location within the image (e.g., bottom left, right corner, etc.). Additionally, <br>the system should extract nutritional information and categorize the type of food (e.g., fruits, vegetables, grains, etc.) <br>based on the detected items. The output should include a comprehensive report or display showing the<br>identified foods, their positions, names, and corresponding nutritional details.<br>&quot;&quot;&quot;<br><br>if submit:<br>    image_data = input_image_details(uploaded_file)<br>    response = get_gemini_response(input_prompt, image_data, input)<br>    st.subheader(&quot;Food Scan report: &quot;)<br>    st.write(response)</pre><h3>Step 4: Let’s Try the dish (App!)</h3><pre>streamlit run app.py</pre><p>Run the above command, you will be able to see such a screen in your web browser.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_yd7VSBgvr3EchK_8htMew.png" /></figure><p>Try with food Table image, for example,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/761/1*i--siOpuJiTqggFDMMg8yQ.png" /></figure><p>Even if you don’t write anything in the input prompt it will run and provide accurate results. You can use the input prompt for example to separate liquid food or seafood etc. Upload the image, click the scan the Food(s), and see the magic.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5uNikb66besce6vEASR3bQ.png" /></figure><p>Remember: This is just a basic recipe, feel free to experiment and add your personal touches. With Google Gemini as your sous-chef, the possibilities are endless! So grab your phone, fire up your creativity, and get ready to build your food scan app — the tastiest tech project you’ll ever cook up!</p><p>Bonus tips:</p><ul><li>Use Gemini’s question-answering capabilities to let users ask questions about the food, like “Is this dish gluten-free?” or “What are some good wine pairings?”</li><li>Integrate food databases like FoodDB or Edamam for even more detailed information and recipe suggestions.</li><li>Get creative with your app’s design and branding — make it visually appealing and fun to use!</li></ul><p>With a dash of code and a sprinkle of imagination, you can turn your love for food and technology into a delicious app that’s both informative and entertaining. So, go forth and create your food scan masterpiece — the world (and your taste buds) will thank you!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e3f919fa1c79" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A brief discussion on Morphological operators using OpenCV]]></title>
            <link>https://mamuncseru.medium.com/a-brief-discussion-on-morphological-operators-using-opencv-ccf6be076896?source=rss-14125a1764a6------2</link>
            <guid isPermaLink="false">https://medium.com/p/ccf6be076896</guid>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[erosion]]></category>
            <category><![CDATA[image-processing]]></category>
            <category><![CDATA[opencv]]></category>
            <category><![CDATA[morphological-operations]]></category>
            <dc:creator><![CDATA[Md. Abdullah Al Mamun]]></dc:creator>
            <pubDate>Fri, 20 Jan 2023 16:59:30 GMT</pubDate>
            <atom:updated>2023-01-20T16:59:30.678Z</atom:updated>
            <content:encoded><![CDATA[<p>Morphology is a broad range of image processing techniques that manipulate images according to their shapes. A structuring element is added by morphological processes to an input image to produce an output image of the same size. When performing a morphological operation, each output pixel’s value is determined by comparing it to its neighbors in the input image. In this lesson, I’m going to use my three favorite structural elements to demonstrate the impact of morphological operations on my favorite binary image.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*J03Wta8biAKSQfihCUm_cQ.jpeg" /><figcaption>Figure: Smile (binary image)</figcaption></figure><p>This is the binary image I’ll be using to show the effect of morphological operations. This image is already in black and white. The text, however, is black and the background is white. So I’ll need to use inverse binary to make the background black and the foreground white. I chose inverse binary because it will make it simpler to see the effect after morphological operations.</p><pre># import libraries<br>import cv2<br>import matplotlib.pyplot as plt<br><br>img = cv2.imread(&#39;smile.jpg&#39;)<br># transforming to inverse binary<br>ret, binary_img = cv2.threshold(img, 127, 255, type=cv2.THRESH_BINARY_INV)<br><br># plotting the binary image<br>plt.figure(figsize=(14, 6))<br>plt.imshow(binary_img, cmap=&#39;gray&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/584/1*QbK4xQTmynleHVvscXhvlg.png" /><figcaption>Figure: Smile(Inverse Binary Image)</figcaption></figure><p>Using the OpenCV built-in method “cv2.getStructuringElement(),” I produced three structuring elements.<br>and these are MORPH RECT, an element with a rectangle shape; MORPH ELLIPSE, an element with an elliptic shape; and MORPH CROSS, an element with a cross shape.</p><pre>morph_rect = cv2.getStructuringElement(shape=cv2.MORPH_RECT, ksize=(5, 5))<br>morph_ellipse = cv2.getStructuringElement(shape=cv2.MORPH_ELLIPSE, ksize=(5, 5))<br>morph_cross = cv2.getStructuringElement(shape=cv2.MORPH_CROSS, ksize=(5, 5))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/245/1*xH9WWdBWuvbsoB44kmqLow.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/245/1*ciQyLjns6ozcjt86Vh-q7Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/245/1*UEqCe5XUbFAHSA-z3BmCIQ.png" /><figcaption>Figure: Morph Rectangle, Morph Ellipse, Morph Cross</figcaption></figure><p>Morphological Operators</p><ol><li>Dilation<br>I used the built-in OpenCV function to dilate my favorite inverse binary image on three various structuring elements.</li></ol><pre>iterations = 1<br>dilation_img = cv2.dilate(binary_img, kernel=morph_rect, iterations=iterations)<br>plt.imshow(dilation_img)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/821/1*mIWweZGvKJJITbjYysCAMg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/821/1*ZDbzAFoUWplsN6-j_bPgCA.png" /><figcaption>Figure: Dilation using Morph_rect as a structuring element</figcaption></figure><p>The text “Smile” changed after seeing the above images. Following the deletion operations, more white pixels were added. In addition, I used a morph rectangle as the kernel in this case. Additionally, increasing the number of iterations will result in more white pixels.</p><pre>iterations = 1<br>dilation_img = cv2.dilate(binary_img, kernel=morph_ellipse, iterations=iterations)<br>plt.imshow(dilation_img)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/821/1*L270DQ-_qo-W0bPsO1g8tw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/821/1*m3NXHzRM3JMSTTs1QxJC6Q.png" /><figcaption>Figure: Dilation using Morph_ellipse as a structuring element</figcaption></figure><p>The text “Smile” was altered. Following the deletion operations, more white pixels were added. In addition, I used a morph ellipse as the kernel in this case. Please consider the “m” character to understand the effect of this kernel. It curves slightly above the first leg. It was not present in the previous kernel. Additionally, increasing the number of iterations will result in more white pixels.</p><pre>iterations = 1<br>dilation_img = cv2.dilate(binary_img, kernel=morph_cross, iterations=iterations)<br>plt.imshow(dilation_img)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/821/1*kUIma3NTXHIzAYTJSY0bTQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/821/1*696R5PmP9uPdYKZ7BIyPCw.png" /><figcaption>Figure: Dilation using Morph_cross as a structuring element</figcaption></figure><p>The text “Smile” changed after seeing the above images. Following the deletion operations, more white pixels were added. In addition, I used a morph cross as the kernel in this case. Please consider the ‘I’ character to comprehend the impact of this kernel. It rounded the letter ‘i’s hat. It was not present in previous kernels. Additionally, increasing the number of iterations will result in more white pixels.</p><p>2. Erosion<br>I utilized OpenCV’s built-in function to operate erosion on three different structuring elements using my favorite inverse binary image.</p><pre>iterations = 1<br>erosion_img = cv2.erode(binary_img, kernel=morph_rect, iterations=iterations)<br>plt.imshow(erosion_img)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/821/1*6nHVV_s8uQZ5nBQmA61alw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/821/1*Fd-Vm36jIJNj6_Mi1FRCjA.png" /><figcaption>Figure: Erosion using Morph_rect as a structuring element</figcaption></figure><p>The text “Smile” has changed, as seen in the figures above. Following the erosion operations, white pixels were reduced. In addition, I used a morph rectangle as the kernel in this case. Additionally, increasing the number of iterations reduces the number of white pixels.</p><pre>iterations = 1<br>erosion_img = cv2.erode(binary_img, kernel=morph_ellipse, iterations=iterations)<br>plt.imshow(erosion_img)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/821/1*8ikRziAPeMQ8Kj1QdKHRyw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/821/1*rgJ0L06rAf3Qrd-EzPM9zg.png" /><figcaption>Figure: Erosion using Morph_ellipse as a structuring element</figcaption></figure><p>Following the erosion operations, white pixels were reduced. In addition, I used a morph ellipse as the kernel in this case. To demonstrate the effect of this kernel, notice how it reduced the white pixels slightly less than the previous kernel. Additionally, increasing the number of iterations reduces the number of white pixels.</p><pre>iterations = 1<br>erosion_img = cv2.erode(binary_img, kernel=morph_cross, iterations=iterations)<br>plt.imshow(erosion_img)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/821/1*wB5vY-uvwoX8_42aqI_d1Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/821/1*wB5vY-uvwoX8_42aqI_d1Q.png" /><figcaption>Figure: Erosion using Morph_cross as a structuring element</figcaption></figure><p>Following the erosion operations, white pixels were reduced. In addition, I used a morph cross as the kernel in this case. It has a lower sensitivity than the previous two. To understand the effect of this kernel, consider that it reduced the number of white pixels slightly less than the previous kernels. Additionally, increasing the number of iterations reduces the number of white pixels.</p><p>3. Opening<br>I performed the opening operation on my preferred inverted binary image using three different structuring elements using OpenCV’s built-in function. I’ll add some background noise to help you understand how the opening morph effect works.</p><pre>white_noise = (np.random.randint(low=0, high=2, size=binary_img.shape) * 255)\<br>                .astype(&#39;uint8&#39;)<br>binary_with_noise_img = binary_img + white_noise<br>opening_img = cv2.morphologyEx(binary_with_noise_img, cv2.MORPH_OPEN,\ <br>                morph_rect)<br>plt.imshow(opening_img)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/821/1*_qGPlEpJxtZqSUw5A-5mCA.png" /><figcaption>Figure: Opening using morph_rect as a structuring element</figcaption></figure><p>White noise was used in the background here. We can conclude from the preceding figure that the background was perfectly de-noised using a morph rectangle kernel.</p><pre>white_noise = (np.random.randint(low=0, high=2, size=binary_img.shape) * 255)\<br>                .astype(&#39;uint8&#39;)<br>binary_with_noise_img = binary_img + white_noise<br>opening_img = cv2.morphologyEx(binary_with_noise_img, cv2.MORPH_OPEN,\ <br>                morph_ellipse)<br>plt.imshow(opening_img)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/821/1*Avw4ldnqm8ziZB0ob03vmg.png" /><figcaption>Figure: Opening using morph_ellipse as a structuring element</figcaption></figure><p>White noise was used in the background here. We can state that it used a morph ellipse kernel to reduce background noise. However, some background noises remained because of this.</p><pre>white_noise = (np.random.randint(low=0, high=2, size=binary_img.shape) * 255)\<br>                .astype(&#39;uint8&#39;)<br>binary_with_noise_img = binary_img + white_noise<br>opening_img = cv2.morphologyEx(binary_with_noise_img, cv2.MORPH_OPEN,\ <br>                morph_cross)<br>plt.imshow(opening_img)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/821/1*h38OXu9C5-E7qhul3SgAkQ.png" /><figcaption>Figure: Opening using morph_cross as a structuring element</figcaption></figure><p>We may say that it used a morph cross kernel to reduce background noise. But in this instance, there are just too many background noises, making it far from flawless. It is less sensitive, therefore.</p><p>4. Closing<br>The closing operation on my favorite inverse binary image was applied to three separate structuring parts using the built-in function of OpenCV. I’m going to introduce some noise in the foreground to help you comprehend the closing morph effect.</p><pre>black_noise = (np.random.randint(low=0, high=2, size=binary_img.shape))<br>black_noise = black_noise * -255<br>black_noise_img = binary_img + black_noise<br>black_noise_img[black_noise_img == -255] = 0<br>black_noise_img = black_noise_img.astype(&#39;uint8&#39;)<br>clossing_img = cv2.morphologyEx(black_noise_img, cv2.MORPH_CLOSE, morph_rect)<br>plt.imshow(clossing_img)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/821/1*GXvsiAM9GnolL1nVOcfNfA.png" /><figcaption>Figure: Closing using morph_rect as a structuring element</figcaption></figure><p>In the background, I used black noise here. Upon seeing the figure, we can conclude that the text was perfectly de-noised using a morph rectangle kernel. Even if there is a small amount of noise there, it is tolerable. But it can’t be completely silent.</p><pre>black_noise = (np.random.randint(low=0, high=2, size=binary_img.shape))<br>black_noise = black_noise * -255<br>black_noise_img = binary_img + black_noise<br>black_noise_img[black_noise_img == -255] = 0<br>black_noise_img = black_noise_img.astype(&#39;uint8&#39;)<br>clossing_img = cv2.morphologyEx(black_noise_img, cv2.MORPH_CLOSE, morph_ellipse)<br>plt.imshow(clossing_img)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/821/1*fmb0Ddpyjche8_9-9mfHFg.png" /><figcaption>Figure: Closing using morph_ellipse as a structuring element</figcaption></figure><p>We may say that it used a morph ellipse kernel to de-noise the text. However, there are some noises in the text here, so it’s not flawless.</p><pre>black_noise = (np.random.randint(low=0, high=2, size=binary_img.shape))<br>black_noise = black_noise * -255<br>black_noise_img = binary_img + black_noise<br>black_noise_img[black_noise_img == -255] = 0<br>black_noise_img = black_noise_img.astype(&#39;uint8&#39;)<br>clossing_img = cv2.morphologyEx(black_noise_img, cv2.MORPH_CLOSE, morph_cross)<br>plt.imshow(clossing_img)</pre><p>It used a morph cross kernel to de-noise the text. However, there is a lot of noise in the text here, so it’s far from ideal. It is less sensitive, therefore.</p><p>A wide range of image processing techniques known as &quot;morphology&quot; process images based on forms. We can confidently state that morphological operators are excellent image-processing techniques after observing their impact in this research study.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ccf6be076896" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>