Spaces:
Sleeping
Sleeping
| import streamlit as st | |
| import pandas as pd | |
| import matplotlib.pyplot as plt | |
| # Define functions for individual pages | |
| # Structured Data - Excel Page | |
| def excel_details_page(): | |
| st.title("Structured Data - Excel Details") | |
| st.markdown("<h3 style='text-align:; color: #4a90e2;'>1. Handling Excel Files (.xlsx)</h3>", unsafe_allow_html=True) | |
| st.markdown(""" | |
| <ul style="font-family: Arial; line-height: 1.6;"> | |
| <li>Excel Files are (XLSX) Created using the Microsoft Excel application.</li> | |
| <li>Structured data format.</li> | |
| <li>Excel files automatically handle encoding during creation, so no encoding issues arise.</li> | |
| <li>If there are extra values in a row, Excel creates a new column and fills it with <b>null values</b> instead of throwing a <b>parsing error</b>.</li> | |
| </ul> | |
| """, unsafe_allow_html=True) | |
| st.markdown("<h3 style='text-align:; color: #ffa500;'>2. Reading Excel Files (.xlsx)</h3>", unsafe_allow_html=True) | |
| st.markdown(""" | |
| <ul style="font-family: Arial; line-height: 1.6;"> | |
| <li>Use the <b>pandas</b> function, <b>pd.read_excel("path")</b>, to read an Excel file.</li> | |
| <li>By default, it reads only one sheet.</li> | |
| <li>To read multiple sheets, specify the <b>sheet_name</b> parameter with a list of sheet indices.</li> | |
| </ul>""", unsafe_allow_html=True) | |
| st.code('df = pd.read_excel("path", sheet_name=[0, 1, 2])', language="python") | |
| st.markdown(""" | |
| <ul style="font-family: Arial; line-height: 1.6;"> | |
| <li><b>The Result is a Dictionary</b></li> | |
| <li>Keys: Sheet names.</li> | |
| <li>Values: DataFrames corresponding to each sheet.</li> | |
| </ul>""", unsafe_allow_html=True) | |
| st.code('df_first_sheet = df[0] # First sheet\n' | |
| 'df_second_sheet = df[1] # Second sheet\n' | |
| 'df_third_sheet = df[2] # Third sheet', language="python") | |
| st.markdown("<h3 style='text-align:; color: #dda0dd;'>3. Converting Data to Excel Files (.xlsx)</h3>", unsafe_allow_html=True) | |
| st.markdown(""" | |
| <ul style="font-family: Arial; line-height: 1.6;"> | |
| <li>To save a single DataFrame to an Excel file</li> | |
| </ul>""", unsafe_allow_html=True) | |
| st.code('df[0].to_excel("path")', language="python") | |
| st.markdown(""" | |
| <ul style="font-family: Arial; line-height: 1.6;"> | |
| <li>To save multiple sheets, use <b>pd.ExcelWriter</b></li> | |
| </ul>""", unsafe_allow_html=True) | |
| st.code("""with pd.ExcelWriter("path") as writer: | |
| df[0].to_excel(writer, sheet_name="Sheet1") | |
| df[1].to_excel(writer, sheet_name="Sheet2")""", language="python") | |
| st.markdown("<h5 style='color:black;'>Download Jupyter Notebook or PDF with Code Examples</h5>", unsafe_allow_html=True) | |
| notebook_url = "https://colab.research.google.com/drive/1gkwpP7dFNXwQ7EgmXw-Mh9ifENAMVg8I" | |
| st.write("Click below for Jupyter notebook:") | |
| st.markdown(f"[Open Jupyter Notebook in Google Colab]({notebook_url})") | |
| if st.button("Back to Home"): | |
| st.session_state['page'] = "home" | |
| # Semi-Structured Data - CSV Page | |
| def csv_details_page(): | |
| # Display the content about semi-structured data | |
| st.header("1. What is Semi-Structured Data?") | |
| st.markdown(""" | |
| <ul style="font-family: Arial; line-height: 1.6;"> | |
| <li>Semi-structured data does not follow a strict tabular format but still has some organizational properties.</li> | |
| <li>Examples include CSV files, JSON, and XML.</li> | |
| </ul> | |
| """, unsafe_allow_html=True) | |
| st.header("2. Working with CSV Files") | |
| st.subheader("a) Reading a CSV File") | |
| st.markdown(""" | |
| <ul style="font-family: Arial; line-height: 1.6;"> | |
| <li>Use the <b>pandas</b> function, <code>pd.read_csv("file.csv")</code>, to read a CSV file.</li> | |
| <li>This function loads the file into a DataFrame.</li> | |
| </ul> | |
| """, unsafe_allow_html=True) | |
| # Code example for reading CSV | |
| st.code(""" | |
| import pandas as pd | |
| df = pd.read_csv("file.csv") | |
| print(df.head()) | |
| """, language="python") | |
| st.subheader("b) Handling Parse Errors") | |
| st.markdown(""" | |
| <ul style="font-family: Arial; line-height: 1.6;"> | |
| <li>If extra value is added to a row a <code> Parsing Error </code> </li> | |
| <li>It happens when we create csv with the help of <code> text editors </code> .</li> | |
| <li>If we add extra value to row it don't throw error instead it creates the new column for extra value it fills with <b> null</b> when converted from excel to csv.</li> | |
| </ul> | |
| """, unsafe_allow_html=True) | |
| st.markdown(""" | |
| <p><b>Solution:</b> Use the <code>on_bad_lines</code> parameter in pandas:</p> | |
| <ul style="font-family: Arial; line-height: 1.6;"> | |
| <li><code>"error"</code>: Stops the program and raises an error.</li> | |
| <li><code>"skip"</code>: Skips rows with errors.</li> | |
| <li><code>"warn"</code>: Skips rows with errors and shows the line numbers.</li> | |
| </ul> | |
| """, unsafe_allow_html=True) | |
| # Code example for handling parse errors | |
| st.code(""" | |
| # Skip bad lines | |
| df = pd.read_csv("file.csv", on_bad_lines="skip") | |
| # Warn about bad lines | |
| df = pd.read_csv("file.csv", on_bad_lines="warn") | |
| """, language="python") | |
| st.subheader("c) Unicode Decode Error") | |
| st.markdown(""" | |
| <ul style="font-family: Arial; line-height: 1.6;"> | |
| <li>Each character, when saved, is represented by a unique number (ASCII/Unicode code point).</li> | |
| <li> ord("a") → 97 , bin(97) → 0b1100001 (Binary representation of 'a') </li> | |
| <li>Characters are saved in memory using a specific encoding, typically UTF-8 by default.</li> | |
| <li>Unicode Decode Error: Occurs when the system is unable to decode a file due to an incorrect or incompatible encoding.To solve this, you need to find the appropriate encoding for the file.</li> | |
| <li>Python uses utf-8 by default for encoding, but files may be saved with other encodings.</li> | |
| <li><code>Using the encodings module</code>: To explore the available encodings, you can import encodings in Python</li> | |
| <li> There are <code>326</code> different encoding aliases available in Python, which can be accessed via <code>encodings.aliases.aliases.,/code></li> | |
| </ul> | |
| """, unsafe_allow_html=True) | |
| # Code example for trying multiple encodings | |
| st.code(""" | |
| import encodings | |
| # Get all encodings | |
| encodings_list = list(encodings.aliases.aliases.keys()) | |
| # Try reading the file with different encodings | |
| for encoding in encodings_list: | |
| try: | |
| df = pd.read_csv("file.csv", encoding=encoding) | |
| print(f"Success with encoding: {encoding}") | |
| break | |
| except: | |
| pass # Skip to the next encoding | |
| """, language="python") | |
| st.subheader("Lookup Error:") | |
| st.markdown(""" | |
| <ul style="font-family: Arial; line-height: 1.6;"> | |
| <li>Occurs if you try to access an encoding that is not available or supported.</li> | |
| <li>Use a try-except block to handle it gracefully</li> | |
| </ul> | |
| """, unsafe_allow_html=True) | |
| st.code(''' | |
| except LookupError: | |
| print("Incorrect Encoding".format(y)) | |
| ''') | |
| st.markdown(""" | |
| <ul style="font-family: Arial; line-height: 1.6;"> | |
| <li>After this when we get <code> Parse error </code> to solve that error add <code> on_badlines = "skip" parametre </code> .</li> | |
| </ul> | |
| """, unsafe_allow_html=True) | |
| st.subheader("d) Handling Large CSV Files") | |
| st.markdown(""" | |
| <ul style="font-family: Arial; line-height: 1.6;"> | |
| <li>When working with large CSV files, the file might not fit into memory, leading to a <code>MemoryError</code>.</li> | |
| <li><code>Solution: Use chunksize to break the file into smaller chunks.</code></li> | |
| <li>: To handle each chunk, you can iterate through the chunks and process them as needed.</li> | |
| </ul> | |
| """, unsafe_allow_html=True) | |
| # Code example for handling large files | |
| st.code(""" | |
| chunk_size = 100 | |
| chunks = pd.read_csv("large_file.csv", chunksize=chunk_size) | |
| for i, chunk in enumerate(chunks): | |
| print(f"Processing chunk {i + 1} with {chunk.shape[0]} rows") | |
| """, language="python") | |
| st.header("3. Summary") | |
| st.markdown(""" | |
| <ul style="font-family: Arial; line-height: 1.6;"> | |
| <li><b>Parse Errors:</b> Use <code>on_bad_lines</code> to handle them (<code>skip</code> or <code>warn</code>).</li> | |
| <li><b>Encoding Issues:</b> Try different encodings to fix <b>UnicodeDecodeError</b>.</li> | |
| <li><b>Large Files:</b> Use <code>chunksize</code> to process files in smaller parts.</li> | |
| </ul> | |
| """, unsafe_allow_html=True) | |
| st.markdown("<h5 style='color:black;'>Download Jupyter Notebook or PDF with Code Examples</h5>", unsafe_allow_html=True) | |
| notebook_url = "https://colab.research.google.com/drive/1pXrfcADbDzHzB-Q_oOBZyi7_97uZgRG7#scrollTo=b8491518" | |
| st.write("Click below for Jupyter notebook:") | |
| st.markdown(f"[Open Jupyter Notebook in Google Colab]({notebook_url})") | |
| # Button to go back to the main page | |
| if st.button("Back to Home"): | |
| st.session_state['page'] = "home" | |
| # Semi-Structured Data - JSON Page | |
| def json_details_page(): | |
| import pandas as pd | |
| import requests | |
| # Page configuration | |
| st.set_page_config(page_title="JSON & API Tutorial", layout="wide") | |
| # Define colors | |
| main_heading_color = "blue" | |
| sub_heading_color = "green" | |
| bullet_point_color = "black" | |
| # Main Title | |
| st.markdown(f"<h1 style='color:{main_heading_color};'>JSON and API Tutorial</h1>", unsafe_allow_html=True) | |
| # Section 1: Handling JSON Files | |
| st.markdown(f"<h2 style='color:{sub_heading_color};'>Handling JSON Files</h2>", unsafe_allow_html=True) | |
| st.markdown(f"<h3 style='color:{sub_heading_color};'>Introduction</h3>", unsafe_allow_html=True) | |
| st.markdown( | |
| f"<ul style='color:{bullet_point_color};'>" | |
| f"<li>JSON (JavaScript Object Notation) is the second most commonly used data format after CSV.</li>" | |
| f"<li>It is widely used, especially in APIs.</li>" | |
| f"<li>JSON data can be either structured or semi-structured.</li>" | |
| f"</ul>", | |
| unsafe_allow_html=True, | |
| ) | |
| st.markdown(f"<h3 style='color:{sub_heading_color};'>Default JSON Format</h3>", unsafe_allow_html=True) | |
| st.code('{"Name": ["P1", "P2"], "Age": [23, 24]}', language="json") | |
| # Code example for reading JSON | |
| st.markdown(f"<h3 style='color:{sub_heading_color};'>Reading JSON Files in Python</h3>", unsafe_allow_html=True) | |
| st.code( | |
| """ | |
| import pandas as pd | |
| data = '{"Name": ["P1", "P2"], "Age": [23, 24]}' | |
| df = pd.read_json(data) | |
| print(df) | |
| """, | |
| language="python", | |
| ) | |
| # Section 2: JSON Formats in Pandas | |
| st.markdown(f"<h2 style='color:{sub_heading_color};'>JSON Formats in Pandas</h2>", unsafe_allow_html=True) | |
| st.markdown( | |
| f"<ul style='color:{bullet_point_color};'>" | |
| f"<li><b>Orient = 'index':</b> Indices become main keys and column names become subkeys.</li>" | |
| f"<li><b>Orient = 'columns':</b> Column names become main keys and indices become subkeys.</li>" | |
| f"<li><b>Orient = 'values':</b> JSON is converted as a list of values.</li>" | |
| f"<li><b>Orient = 'split':</b> Stores data along with columns and indices.</li>" | |
| f"</ul>", | |
| unsafe_allow_html=True, | |
| ) | |
| # Section 3: Collecting Data from APIs | |
| st.markdown(f"<h2 style='color:{sub_heading_color};'>Collecting Data from APIs</h2>", unsafe_allow_html=True) | |
| st.markdown( | |
| f"<ul style='color:{bullet_point_color};'>" | |
| f"<li>API (Application Programming Interface) is a bridge that enables communication between two applications.</li>" | |
| f"<li>It uses HTTP protocols to exchange data securely.</li>" | |
| f"<li>If the response code is <b>200</b>, the request was successful.</li>" | |
| f"<li>For accessing secure data, you may need an API key.</li>" | |
| f"</ul>", | |
| unsafe_allow_html=True, | |
| ) | |
| # Code example for using an API | |
| st.markdown(f"<h3 style='color:{sub_heading_color};'>Example: Fetching Data from an API</h3>", unsafe_allow_html=True) | |
| st.code( | |
| """ | |
| import requests | |
| import pandas as pd | |
| url = "https://api.example.com/data" | |
| response = requests.get(url) | |
| if response.status_code == 200: | |
| data = response.json() | |
| df = pd.json_normalize(data) | |
| print(df) | |
| else: | |
| print(f"Failed to fetch data. Status code: {response.status_code}") | |
| """, | |
| language="python", | |
| ) | |
| # Google Colab Link | |
| st.markdown("<h5 style='color:black;'>Download Jupyter Notebook or PDF with Code Examples</h5>", unsafe_allow_html=True) | |
| notebook_url = "https://colab.research.google.com/drive/1pIg_zmj04lVmPTdiTU2bU9BLAR2mS5wi?usp=sharing" | |
| st.write("Click below for Jupyter notebook:") | |
| st.markdown(f"[Open Jupyter Notebook in Google Colab]({notebook_url})") | |
| if st.button("Back to Home"): | |
| st.session_state['page'] = "home" | |
| # Semi-Structured Data - XML Page | |
| def xml_details_page(): | |
| st.title("Semi Structured Data - XML Details") | |
| st.markdown("<h1 style='text-align:; color: blue;'>Handling XML Files(.xlsx)</h1>", unsafe_allow_html=True) | |
| st.markdown("<h2 style='color: green;'>What is XML?</h2>", unsafe_allow_html=True) | |
| st.markdown(""" | |
| <ul style="font-family: Arial; line-height: 1.6;"> | |
| <li>XML (Extensible Markup Language) is a markup language used for storing and transporting semi-structured data.</li> | |
| <li><code>XML</code> is a markup language, meaning it uses tags to define the structure and content of data.</li> | |
| <li> It is semi-structured, meaning it has a flexible structure that can be defined by the user.</li> | |
| <li>Tags are not predefined, allowing users to create their own custom tags.</li> | |
| </ul> | |
| """, unsafe_allow_html=True) | |
| st.markdown("<h3 style='text-align:; color: #ffa500;'>Basic Structure of XML(.xlsx)</h3>", unsafe_allow_html=True) | |
| st.markdown(""" | |
| <ul style="font-family: Arial; line-height: 1.6;"> | |
| <li> XML documents consist of elements, which are represented by <b>tags</b>.</li> | |
| <li> Tags have an opening and closing tag, with the content enclosed within.</li> | |
| <li>The basic structure of an XML tag is: `<openingtag>content</closingtag>`</li> | |
| </ul>""", unsafe_allow_html=True) | |
| st.markdown("<h2 style='color: orange;'>Example of XML Data</h2>", unsafe_allow_html=True) | |
| st.code("""<persons> | |
| <person> | |
| <name>HARI </name> | |
| <age>22</age> | |
| <gender>Male</gender> | |
| </person> | |
| <person> | |
| <name>CHANDAN</name> | |
| <age>21</age> | |
| <gender>Male</gender> | |
| </person> | |
| </persons> | |
| """, language="xml") | |
| # Google Colab Link | |
| st.markdown("<h5 style='color:blue;'>Download Jupyter Notebook or PDF with Code Examples</h5>", unsafe_allow_html=True) | |
| notebook_url = "https://colab.research.google.com/drive/14xGAxu_rKAl_eslODfQXoTEpN7NU4lk6" | |
| st.write("Click below for Jupyter notebook:") | |
| st.markdown(f"[Open Jupyter Notebook in Google Colab]({notebook_url})") | |
| if st.button("Back to Home"): | |
| st.session_state['page'] = "home" | |
| # Semi-Structured Data - HTML Page | |
| def html_details_page(): | |
| st.title("Semi-Structured Data - HTML Details") | |
| st.markdown(""" | |
| **HTML** (HyperText Markup Language) is used to structure web pages. | |
| - Semi-structured data with nested tags. | |
| """) | |
| # App title | |
| st.title("Working with HTML Data in Python") | |
| # Section: HTML and DataFrames | |
| st.header("HTML and DataFrames") | |
| st.write(""" | |
| - **HTML** stands for HyperText Markup Language and is a semi-structured format. | |
| - HTML uses tags like `<table>`, `<tr>`, `<th>`, and `<td>` to show table data. | |
| - Unlike XML, HTML doesn’t let you create any custom tags. | |
| - Not all HTML can be changed into dataframes, especially plain text like paragraphs. | |
| - Usually, only table-related tags (`<table>`, `<tr>`, `<th>`, `<td>`) can be converted into dataframes. | |
| """) | |
| # Section: Reading HTML Files | |
| st.write("**How to Read HTML Files:**") | |
| st.code(""" | |
| import pandas as pd | |
| tables = pd.read_html("path_or_url") | |
| """, language="python") | |
| st.write(""" | |
| - Use `pd.read_html()` to read tables from an HTML file or a website. | |
| - This function collects all tables and gives them as a list of dataframes. | |
| """) | |
| st.write("**How to Get Specific Tables:**") | |
| st.code(""" | |
| # Select the first table from the list | |
| table = tables[0] | |
| """, language="python") | |
| st.write(""" | |
| - The tables are stored as a list, and you can access them using their index number. | |
| """) | |
| st.write("**Limitations:**") | |
| st.write(""" | |
| - Some HTML files or websites cannot be read, even if they have tables. | |
| - Issues like file permissions or restrictions may stop reading. | |
| """) | |
| st.write("**Using `match` to Find Specific Tables:**") | |
| st.code(""" | |
| # Read a specific table by searching for a keyword | |
| tables = pd.read_html("path_or_url", match="keyword") | |
| """, language="python") | |
| st.write(""" | |
| - The `match` parameter lets you find tables with specific keywords. | |
| - This is useful to pick the right table when many are present. | |
| """) | |
| # Section: Exporting DataFrames | |
| st.header("Exporting DataFrames to HTML") | |
| st.write("**How to Export a DataFrame to HTML:**") | |
| st.code(""" | |
| # Save a dataframe as an HTML file | |
| df.to_html("output.html") | |
| """, language="python") | |
| st.write(""" | |
| - This converts your dataframe into an HTML file. | |
| - You can save the HTML file at a specified location. | |
| """) | |
| # Google Colab Link | |
| st.markdown("<h5 style='color:red;'>Download Jupyter Notebook or PDF with Code Examples</h5>", unsafe_allow_html=True) | |
| notebook_url = "https://colab.research.google.com/drive/1IgIEoWqw-pHSSMjuWzY2FlFJVIoNwL3C" | |
| st.write("Click below for Jupyter notebook:") | |
| st.markdown(f"[Open Jupyter Notebook in Google Colab]({notebook_url})") | |
| if st.button("Back to Home"): | |
| st.session_state['page'] = "home" | |
| # Unstructured Data - Image Page | |
| def image_details_page(): | |
| st.title("Unstructured Data - Image Details") | |
| st.markdown(""" | |
| **Images** are unstructured data represented in pixel values. | |
| - Formats include JPEG, PNG, BMP, etc. | |
| - Libraries like OpenCV and PIL are used for image processing. | |
| """) | |
| import numpy as np | |
| # Helper function for subheadings | |
| def subheading(text): | |
| """Displays a subheader with consistent styling.""" | |
| st.markdown(f"<h3 style='color:teal;'>{text}</h3>", unsafe_allow_html=True) | |
| # Sidebar for navigation | |
| st.sidebar.title("Navigation") | |
| page = st.sidebar.radio("Go to", ["Introduction", "Basic Operations","Image Conversions"]) | |
| # App Title and Description | |
| st.title("Image Processing Fundamentals") | |
| st.write(""" | |
| This app introduces the basics of image processing, helping you understand how images are formed, represented, and handled programmatically. | |
| It's designed for beginners exploring computer vision concepts. | |
| """) | |
| # Introduction Section | |
| if page == "Introduction": | |
| st.header("Introduction") | |
| st.write(""" | |
| Images play a crucial role in various fields, including art, science, and technology. | |
| In this app, you will learn: | |
| - How images are captured and represented. | |
| - Different color spaces and their applications. | |
| - Basic operations on images using Python libraries. | |
| """) | |
| st.header("Understanding Images") | |
| # Subsections | |
| subheading("What is an Image?") | |
| st.write(""" | |
| An image is a **2D representation of light**, created when light reflects off an object and is captured by a camera or our eyes. | |
| """) | |
| subheading("How is an Image Formed?") | |
| st.write(""" | |
| - **Light Source**: Light from sources like the sun or a bulb hits an object. | |
| - **Reflection**: Light bounces off the object's surface. | |
| - **Capture**: The reflected light is recorded by a camera sensor or the human eye. | |
| - In images pixels are the **feautures** and these pixels contains **information** as shape,color,patterns.No of pixels = height*width these both decides the resolution.More no of pixels more clarity more information gained. | |
| """) | |
| subheading("Why is an Image Represented as a Grid?") | |
| st.write(""" | |
| - Pixels in an image are arranged in a grid-like structure.Each **row** in the grid corresponds to a **data point** (a group of pixels).Each **column** in the grid represents a **feature** of those data points. | |
| - Both image data and tabular data can be visualized as grids.This concept aligns with tabular data, where the structure is similar, but the interpretation differs: | |
| - **In images**: Each row represents a set of data points (pixels), and the columns represent their features. | |
| - **In tables**:Each row represents an individual data point, and each column corresponds to a feature of that data point. | |
| """) | |
| st.subheader("Interactive Pixel Grid") | |
| # User Input for Height and Width | |
| height = st.number_input("Enter Image Height (pixels):", min_value=1, max_value=50, value=10, step=1) | |
| width = st.number_input("Enter Image Width (pixels):", min_value=1, max_value=50, value=10, step=1) | |
| # Display Resolution | |
| resolution = height * width | |
| st.write(f"**Image Resolution**: {resolution} pixels") | |
| # Generate and Display Pixel Grid | |
| st.write("**Pixel Grid Visualization:**") | |
| grid = np.random.rand(int(height), int(width)) # Generate random grid values | |
| fig, ax = plt.subplots() | |
| cax = ax.imshow(grid, cmap="magma") | |
| plt.colorbar(cax, ax=ax) # Add color bar for context | |
| ax.set_title("Pixel Grid") | |
| ax.set_xlabel("Width(pixels)", fontsize=8) # Set smaller font size | |
| ax.set_ylabel("Height(pixels)", fontsize=8) # Set smaller font size | |
| # Render the Plot | |
| st.pyplot(fig) | |
| st.header("Color Spaces") | |
| # Explanation for Color Spaces | |
| st.write(""" | |
| Color space is a technique used to represent the colors of an image. This technique helps us preserve the colors while converting them into numerical values, which machine learning models can understand. | |
| For example, in image classification tasks like differentiating between dogs and cats: | |
| - The first step is to collect a bunch of dog and cat images. These images may be in formats such as PNG, JPG, or JPEG. | |
| - However, machine learning models can only understand numbers, so color spaces are used to convert the image colors into numerical representations. | |
| """) | |
| # Subheading for Black and White color space | |
| st.markdown("<h3 style='text-align:; color: #4a90e2;'>1. Black and White</h3>", unsafe_allow_html=True) | |
| st.write(""" | |
| - Represents only two colors: **Black (0) Pixels** and **White (255) Pixels**. | |
| - **Limitation**: It only preserves black and white. | |
| """) | |
| st.image("https://huggingface.co/spaces/hari3485/DiveIntoML/resolve/main/Images/blackwhite.jpg") | |
| # Subheading for Grayscale color space | |
| st.markdown("<h3 style='text-align:; color: #4169E1;'>2. Grayscale</h3>", unsafe_allow_html=True) | |
| st.write(""" | |
| - 0 pixel value means Black: It represents the darkest shade in a grayscale image. | |
| - 1 piexel value means White: It represents the brightest shade in a grayscale image. | |
| - Pixel Values between 1 and 254: These Pixel values represent various shades of gray, with increasing brightness as the value approaches 254. | |
| - **Limitation**: | |
| - Gray Scale images cannot preserve coloured images as it is having only gray shades | |
| """) | |
| st.image("https://huggingface.co/spaces/hari3485/DiveIntoML/resolve/main/Images/grayscale.jpeg") | |
| # Subheading for RGB color space | |
| st.markdown("<h3 style='text-align:; color: #483D8B;'>3. RGB </h3>", unsafe_allow_html=True) | |
| st.image("https://huggingface.co/spaces/hari3485/DiveIntoML/resolve/main/Images/bunny.jpg") | |
| st.write(""" | |
| - To represent coloured image we have to convert image in 3D array , Mixture of three 2D arrays is **RGB**. | |
| - The value in each array ranges from R(0,255) ,G(0,255) ,B(0,255) | |
| - By mixing different intensities of red, green, and blue,we can create over **16 million possible colors**. | |
| - The **Red channel** has pixel values with red set to 255, and green and blue to 0. | |
| - The **Green channel** has pixel values with green set to 255, and red and blue to 0. | |
| - The **Blue channel** has pixel values with blue set to 255, and red and green to 0. | |
| - When merged, these channels form a complete color image. | |
| """) | |
| st.image("https://huggingface.co/spaces/hari3485/DiveIntoML/resolve/main/Images/bunny1.jpg") | |
| # Basic Operations Section | |
| elif page =="Basic Operations": | |
| st.title("What is OpenCV?") | |
| st.header("Understanding Open Source Computer Vision") | |
| # Introduction | |
| st.write(""" | |
| OpenCV (Open Source Computer Vision) is a free and open-source library designed for real-time computer vision tasks. | |
| It is widely used in industries like healthcare, security, robotics, and AI to process images and videos effectively. | |
| """) | |
| st.code(""" | |
| import cv2 | |
| import numpy as np | |
| """) | |
| # Features Section | |
| st.subheader("Key Features of OpenCV:") | |
| st.markdown(""" | |
| - **Image Processing**: Resize, crop, filter, and manipulate images easily. | |
| - **Object Detection**: Detect faces, objects, and track their movements in real-time. | |
| - **Video Analysis**: Perform video stabilization, motion detection, and frame-by-frame analysis. | |
| - **Machine Learning Integration**: Combine with AI frameworks for advanced tasks like face recognition and augmented reality. | |
| """) | |
| # Theory Section | |
| st.markdown(""" | |
| <h3 style="color: #9400d3;"> Reading an image</h3> | |
| """, unsafe_allow_html=True) | |
| st.markdown(""" | |
| - It converts an 2D image into Machine representation value array. | |
| - **cv2.imread("path)** this method going to convert image to 3D aray as it used default colour space **RGB**. | |
| - The data type of image should be **uint8**. | |
| """) | |
| st.code(""" | |
| # Code to read an image | |
| img = cv2.imread('BGR_image', 1) # by default it considers this as coloured image | |
| print(img) | |
| """) | |
| st.code(""" | |
| img = cv2.imread("gray_scale_image",0) # when we want it in 2D array use parametre `flags=0` it considers as grayscale image | |
| print(img) | |
| """) | |
| # Theory Section | |
| st.markdown(""" | |
| <h3 style="color: #FF7F00;"> imshow()</h3> | |
| """, unsafe_allow_html=True) | |
| st.markdown(""" | |
| - After creating or reading an image, we can display it using OpenCV. Here’s how the key functions work together: | |
| - The `imshow()` function creates a pop-up window to display the image. | |
| - Internally, it converts the numerical array into a visual image. | |
| - **Parameters**: | |
| Window Name: Title of the pop-up window (string). | |
| Image Array: The array representing the image. | |
| """) | |
| # Theory Section | |
| st.markdown(""" | |
| <h3 style="color: #FF7F00;"> waitkey()</h3> | |
| """, unsafe_allow_html=True) | |
| st.markdown(""" | |
| - The main purpose Waits for a key press and adds a delay before closing the pop-up window. | |
| - `waitKey(0)` or `waitKey()` Keeps the window open indefinitely until a key is pressed. | |
| - `waitkey(10)` After 10 milli seconds the pop up window will be closed when we use waitkey(n) after n milliseconds window closes. | |
| """) | |
| # Theory Section | |
| st.markdown(""" | |
| <h3 style="color: #FF7F00;"> destroyAllWindows()</h3> | |
| """, unsafe_allow_html=True) | |
| st.markdown(""" | |
| - **Purpose**: Closes all OpenCV-created windows. | |
| - **Usage**:This makes sure that memory is cleared and helps avoid crashes by getting rid of resources when the image is no longer needed. | |
| """) | |
| st.code(""" | |
| cv2.destroyAllWindows() # When we give this all temporary windows will be closed | |
| """) | |
| st.markdown(""" | |
| <h5 style='color: green;'>These three functions must work together to display and manage images effectively. /h5> | |
| """, unsafe_allow_html=True) | |
| st.code(""" | |
| img = cv2.imshow("Window name",image) | |
| # Window name : Name of the window | |
| # image : The image we created | |
| # Code to wait for a key press | |
| cv2.waitKey() # Wait indefinitely until key press | |
| # Code to close all windows | |
| cv2.destroyAllWindows() # Close all OpenCV windows | |
| """) | |
| st.markdown(""" | |
| ### Additional Notes | |
| - **Why Use `cv2.waitKey`?** | |
| Without this, the image display window will close immediately after the program finishes execution. | |
| - **Handling Pop-Up Windows** | |
| - Use `cv2.destroyAllWindows()` to close all pop-up windows and release system resources properly. | |
| """) | |
| st.markdown(""" | |
| <h3 style="color: #9400d3;">Saving an Image</h3> | |
| """, unsafe_allow_html=True) | |
| # About imwrite() function | |
| st.write(""" | |
| To save an image file in OpenCV, we use the **imwrite()** function. | |
| It converts the numerical array (image data) back into an image file format, such as `.jpg`, `.png`, or `.bmp`. | |
| """) | |
| # Code example | |
| st.code(""" | |
| cv2.imwrite('image.jpg', image_array) # 'image.jpg' it is the name of the output file | |
| print("Wow your image is saved!") | |
| """, language="python") | |
| elif page =="Image Conversions": | |
| from PIL import Image | |
| # Title of the app | |
| st.markdown(""" | |
| <h3 style="color: #9400d3;">Creating a Black and White Image</h3> | |
| """, unsafe_allow_html=True) | |
| # Explanation | |
| st.write(""" | |
| In OpenCV, black and white images are created by filling a matrix with pixel values: | |
| - **Black image**: When the pixel values are set to 0. | |
| - **White image**: When the pixel values are set to 255. | |
| """) | |
| # Display the code | |
| st.code(""" | |
| import numpy as np | |
| import streamlit as st | |
| white_img= np.full((500,500),255,dtype=np.uint8) | |
| black_img = np.zeros((500,500),dtype=np.uint8) | |
| cv2.imshow("white",white_img) #white image is displayed | |
| cv2.imshow("black",black_img) #black image is displayed | |
| cv2.waitKey() # until we close the window it displays the image | |
| cv2.destroyAllWindows() # Close all temporary windows | |
| """, language="python") | |
| # Section 1: Grayscale Image | |
| st.markdown(""" | |
| <h3 style="color: #9400d3;">Creating a Grayscale Image</h3> | |
| """, unsafe_allow_html=True) | |
| st.write(""" | |
| In a grayscale image, 0 is black, 255 is white, and pixel values between 1 and 254 represent varying shades of gray | |
| """) | |
| st.code(""" | |
| # Grayscale image creation | |
| gray_img = np.full((500, 500), 155, dtype=np.uint8) #155 is a medium-light gray, closer to white than black. | |
| # Display in OpenCV | |
| cv2.imshow("Gray Image", gray_img) #Gray scale image is created | |
| cv2.waitKey(0) | |
| cv2.destroyAllWindows() | |
| """, language="python") | |
| st.markdown(""" | |
| <h3 style="color: #9400d3;">Creating a BGR image</h3> | |
| """, unsafe_allow_html=True) | |
| st.write(""" | |
| - The **Red channel** has pixel values with red set to 255, and green and blue to 0. | |
| - The **Green channel** has pixel values with green set to 255, and red and blue to 0. | |
| - The **Blue channel** has pixel values with blue set to 255, and red and green to 0. | |
| - When merged, these channels form a complete color image. | |
| """) | |
| st.markdown(""" | |
| <p style="color: #FF6347;">To represent a coloured image, we have to convert the image into a 3D array. The mixture of three 2D arrays is <strong style="color: #1E90FF;">RGB</strong>.</p> | |
| """, unsafe_allow_html=True) | |
| st.code(""" | |
| # Create individual color channels | |
| b = np.full((200, 200), 255, dtype=np.uint8) # Blue channel | |
| g = np.zeros((200, 200), dtype=np.uint8) # Green channel | |
| r = np.zeros((200, 200), dtype=np.uint8) # Red channel | |
| # Merge the color channels to create RGB images | |
| b_img = cv2.merge([b, g, r]) # Blue image | |
| g_img = cv2.merge([g, b, r]) # Green image | |
| r_img = cv2.merge([r, g, b]) # Red image | |
| # Display the images | |
| cv2.imshow("Blue", b_img) | |
| cv2.imshow("Green", g_img) | |
| cv2.imshow("Red", r_img) | |
| cv2.waitKey(0) # Wait until a key is pressed | |
| cv2.destroyAllWindows() # Close all OpenCV windows | |
| """, language="python") | |
| st.markdown(""" | |
| <h3 style="color: #e25822;">Channel Splitting</h3> | |
| """, unsafe_allow_html=True) | |
| # About cv2.split() function | |
| st.write(""" | |
| The `cv2.split()` function in OpenCV is used to separate an image into its individual color channels. | |
| It generates separate single-channel arrays for each color, which can then be manipulated independently. | |
| For example, it can divide an RGB image into its Red, Green, and Blue components. | |
| """) | |
| # Syntax for cv2.split() function | |
| st.code(""" | |
| # Syntax for cv2.split() | |
| channels = cv2.split(image) | |
| # image: The input image (e.g., an RGB image). | |
| # channels: A list of single-channel images (e.g., Blue, Green, Red). | |
| """, language="python") | |
| # Heading for the section | |
| st.markdown(""" | |
| <h3 style="color: #9400d3;">Splitting Channels </h3> | |
| """, unsafe_allow_html=True) | |
| # Code Example for Splitting and Merging Color Channels | |
| st.code(""" | |
| img = cv2.imread("path of the image") # Load the image | |
| b, g, r = cv2.split(img) # Separate the image into Blue, Green, and Red channels | |
| zeros = np.zeros(img.shape[:-1], dtype=np.uint8) # Create a blank array for the empty channels | |
| blue_channel = cv2.merge([b, zeros, zeros]) # The Blue channel has blue set to 255, and red and green to 0 | |
| green_channel = cv2.merge([zeros, g, zeros]) # The Green channel has green set to 255, and red and blue to 0 | |
| red_channel = cv2.merge([zeros, zeros, r]) # The Red channel has red set to 255, and green and blue to 0 | |
| # Show the separate color channels and the original image | |
| cv2.imshow("Blue_channel", blue_channel) | |
| cv2.imshow("Green_channel", green_channel) | |
| cv2.imshow("Red_channel", red_channel) | |
| cv2.waitKey(0) | |
| cv2.destroyAllWindows() | |
| """, language="python") | |
| st.image("https://huggingface.co/spaces/hari3485/DiveIntoML/resolve/main/Images/BGR%20to%20Split.jpg") | |
| st.markdown(""" | |
| <h3 style="color: #9400d3;">Combining Channels </h3> | |
| """, unsafe_allow_html=True) | |
| st.write(""" | |
| To create a full color image from separate single-channel images (such as Red, Green, and Blue), the **cv2.merge()** function is used. | |
| It combines individual color channels into a single, complete color image. | |
| """) | |
| # Code Example for Splitting and Merging Color Channels | |
| st.code(""" | |
| img = cv2.imread("path of the image") # Load the image | |
| b, g, r = cv2.split(img) # Separate the image into Blue, Green, and Red channels | |
| zeros = np.zeros(img.shape[:-1], dtype=np.uint8) # Create a blank array for the empty channels | |
| blue_channel = cv2.merge([b, zeros, zeros]) # The Blue channel has blue set to 255, and red and green to 0 | |
| green_channel = cv2.merge([zeros, g, zeros]) # The Green channel has green set to 255, and red and blue to 0 | |
| red_channel = cv2.merge([zeros, zeros, r]) # The Red channel has red set to 255, and green and blue to 0 | |
| # Show the separate color channels and the original image | |
| cv2.imshow("Blue_channel", blue_channel) | |
| cv2.imshow("Green_channel", green_channel) | |
| cv2.imshow("Red_channel", red_channel) | |
| cv2.imshow("merged_image", cv2.merge([blue_channel, green_channel, red_channel])) | |
| cv2.waitKey(0) | |
| cv2.destroyAllWindows() | |
| """, language="python") | |
| st.image("https://huggingface.co/spaces/hari3485/DiveIntoML/resolve/main/Images/merging%20BGR.jpg") | |
| # Title of the app | |
| st.markdown(""" | |
| <h3 style="color: #9400d3;">Converting colour spaces</h3> | |
| """, unsafe_allow_html=True) | |
| st.write(""" | |
| When working with image arrays, we might need to convert or modify their color spaces. | |
| OpenCV provides the `cv2.cvtColor()` method to achieve this. It allows us to change an image's color space to a desired format **BGR to Grayscale**. | |
| """) | |
| st.code(""" | |
| # Convert from BGR to Grayscale | |
| img_gray = cv2.cvtColor(BGR_img, cv2.COLOR_BGR2GRAY) | |
| """) | |
| st.image("https://huggingface.co/spaces/hari3485/DiveIntoML/resolve/main/Images/BGR2Gray.jpg") | |
| if st.button("Go Back"): | |
| st.experimental_set_query_params(page="Introduction") | |
| if st.button("Back to Home"): | |
| st.session_state['page'] = "home" | |
| # Unstructured Data - Video Page | |
| def video_details_page(): | |
| # Definition of Video | |
| st.markdown("<h3 style='text-align: left; color: #FF00FF;'>What is video?</h3>", unsafe_allow_html=True) | |
| st.write(""" | |
| A video is essentially a series of images, called frames, played quickly one after another to create the illusion of motion. | |
| For example, a sequence of images like I1, I2, I3, ..., In transitions so rapidly that the individual frames aren't noticeable to our eyes. | |
| This rapid switching between frames creates the appearance of continuous motion. | |
| **The smoothness of a video depends on how many frames are shown per second, measured in frames per second (fps)** | |
| - **30 fps**: 30 frames are displayed every second, which gives decent smoothness. | |
| - **60 fps**: 60 frames are displayed every second, making the video smoother. | |
| """) | |
| st.markdown("<h3 style='text-align: left; color: #FF00FF;'>Understanding Video Processing with OpenCV</h3>", unsafe_allow_html=True) | |
| st.write(""" | |
| **Load the Video** | |
| - Load Video: Use `cv2.VideoCapture()` with the video file path to load and open the video. | |
| **Read Frames** | |
| - Read Frames: OpenCV reads each video frame in a loop using the read() function until the video ends. | |
| **Display Frames** | |
| - Frames are displayed sequentially with cv2.imshow(), simulating video playback. | |
| **Exit Playback** | |
| - Press a key (e.g., 'q') to stop playback and exit the loop. | |
| """) | |
| st.code(""" | |
| # Reading the video | |
| vid = cv2.VideoCapture("Here give the path of the vedio") | |
| # Dividing the video into frames and looping each and very frame by suing while loop as we dont how many frames | |
| while True: | |
| succ,img = vid.read() | |
| if succ == False: # here if the frame doesnot exist break | |
| break | |
| cv2.imshow("Window name",img) # display the video | |
| if cv2.waitKey(1)& 255 == ord("q"): # to interupt the vedio or to come out of video in the middle use ascii value | |
| break | |
| cv2.destroyAllWindows() # removing all the tempory memory RAM | |
| """, language = "python") | |
| # Use st.markdown to display the explanation | |
| st.markdown("<h3 style='text-align: left; color: #FF00FF;'>Understanding vid.read()</h3>", unsafe_allow_html=True) | |
| st.markdown(""" | |
| - `vid.read()` is used to grab one frame (image) at a time from a video. | |
| - It gives back two things: | |
| 1. **`succ`**: A `True` or `False` value. | |
| - **`True`** means the frame was successfully loaded. | |
| - **`False`** means the frame could not be loaded (usually because the video has ended). | |
| 2. **`img`**: The actual frame (image) from the video, which is in the form of a NumPy array. This image can then be processed just like any regular picture. | |
| """) | |
| st.markdown("<h3 style='text-align: left; color: #FF00FF;'>Understanding cv2.waitkey()</h3>", unsafe_allow_html=True) | |
| st.markdown(""" | |
| - **`cv2.waitKey(1)`**: | |
| - This function waits for a key to be pressed for 1 millisecond. | |
| - If a key is pressed, it returns the code of that key. If no key is pressed, it returns `-1`. | |
| - **`& 255`**: | |
| - This part ensures the key code is correctly interpreted across different systems. | |
| - It keeps only the last 8 bits of the code (the actual key code). | |
| - **`ord('q')`**: | |
| - This gets the ASCII value of the letter `'q'`. | |
| - The ASCII value for `'q'` is 113. | |
| - This is used to check if the user pressed the `'q'` key to stop the program. | |
| """) | |
| st.code(""" | |
| if cv2.waitKey(1)& 255 == ord("q"): | |
| break | |
| """,language="python") | |
| st.markdown("<h3 style='text-align: left; color: #FF00FF;'>Converting BGR Video to Grayscale</h3>", unsafe_allow_html=True) | |
| # Use st.markdown to display the explanation | |
| st.markdown(""" | |
| You can process video frames one by one and convert them as needed. In this example, we will: | |
| - Convert each frame of a video from BGR (Blue, Green, Red) color format to grayscale (a black-and-white image). | |
| - Display both the original video frames and the grayscale frames side by side. | |
| """) | |
| # Use st.code to display the OpenCV code | |
| st.code(""" | |
| import cv2 | |
| # Load the video | |
| vid = cv2.VideoCapture("path of the video") | |
| while True: | |
| succ, img = vid.read() # Reading the video | |
| # Dividing the video into frames and looping through each frame as we don't know how many frames | |
| if succ == False: # If the frame does not exist, break | |
| break | |
| img1 = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # Converting BGR image to Grayscale | |
| cv2.imshow("video_color", img) # Display the original video | |
| cv2.imshow("video_gray", img1) # Display the grayscale video | |
| if cv2.waitKey(1) & 255 == ord("q"): # To interrupt the video or stop in the middle using ASCII value | |
| break | |
| cv2.destroyAllWindows() # Removing all the temporary memory (RAM) | |
| """, language="python") | |
| st.markdown("<h3 style='text-align: left; color: #FF00FF;'>Splitting video into 3 Different channels (B,G,R)</h3>", unsafe_allow_html=True) | |
| # Use st.markdown to display the explanation | |
| st.markdown(""" | |
| Each frame of a colored video consists of three channels: Blue, Green, and Red (BGR). In this example, we will: | |
| - Split each frame of the video into separate Blue, Green, and Red color channels. | |
| - Display the original video alongside each individual color channel. | |
| """) | |
| # Use st.code to display the OpenCV code | |
| st.code(""" | |
| import cv2 | |
| import numpy as np | |
| # Load the video | |
| vid = cv2.VideoCapture("path of the video") | |
| while True: | |
| succ, img = vid.read() | |
| if succ == False: | |
| break | |
| # Split the image into Blue, Green, and Red channels | |
| b, g, r = cv2.split(img) | |
| z = np.zeros(b.shape, dtype=np.uint8) # Create a blank channel | |
| # Convert the image to grayscale | |
| img1 = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) | |
| # Display the individual color channels | |
| cv2.imshow("bluechannel", cv2.merge([b, z, z])) | |
| cv2.imshow("green_channel", cv2.merge([z, g, z])) | |
| cv2.imshow("red_channel", cv2.merge([z, z, r])) | |
| # Display the grayscale video | |
| cv2.imshow("video_gray", img1) | |
| if cv2.waitKey(100) & 255 == ord("q"): | |
| break | |
| cv2.destroyAllWindows() # Remove temporary windows | |
| """, language="python") | |
| st.markdown("<h3 style='text-align: left; color: #ffa500;'>Live Streaming with Webcam</h3>", unsafe_allow_html=True) | |
| # Display the explanation in markdown | |
| st.markdown(""" | |
| OpenCV allows you to use your webcam for live video streaming. The `cv2.VideoCapture()` function is used to activate the webcam. Here's how it works: | |
| - `cv2.VideoCapture(0)`: The `0` tells OpenCV to use the default webcam on your computer. If you have multiple cameras, you can use other numbers (like 1, 2) to access those cameras. | |
| - This function establishes a connection with the webcam and begins capturing video frames in real time. | |
| The following example demonstrates how to: | |
| - Activate the webcam. | |
| - Display the live stream. | |
| - Close the webcam window by pressing the 'p' key. | |
| """) | |
| # Display the OpenCV code | |
| st.code(""" | |
| import cv2 | |
| # Capture video from the default webcam (ID = 0) | |
| vid = cv2.VideoCapture(0) | |
| while True: | |
| suc, img = vid.read() | |
| if suc == False: | |
| print("Web Camera is not working") | |
| break | |
| cv2.imshow("live stream", img) | |
| # Exit the loop when 'p' key is pressed | |
| if cv2.waitKey(1) & 255 == ord('p'): | |
| break | |
| cv2.destroyAllWindows() | |
| """, language="python") | |
| st.markdown("<h3 style='text-align: left; color: #ffa500;'>Dual Webcam Stream Color vs Grayscale Capture</h3>", unsafe_allow_html=True) | |
| st.markdown(""" | |
| - 1. The first webcam displays the original video feed from the camera. | |
| - 2. The second webcam shows the same video feed, but converted to grayscale, where the color information is removed, leaving only varying shades of gray. | |
| """) | |
| st.code(""" | |
| vid = cv2.VideoCapture(0) # default id = 0 | |
| while True: | |
| suc,img=vid.read() | |
| if suc == False: | |
| print("Web Camera is not working") | |
| break | |
| img1 = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) | |
| cv2.imshow("live stream",img) # orginal stream | |
| cv2.imshow("Grayscale live stream",img1) # Gray Scale stream | |
| if cv2.waitKey(1) & (255) == ord("q"): | |
| break | |
| cv2.destroyAllWindows() | |
| """,language = "python") | |
| st.markdown("<h3 style='text-align: center; left: #ffa500;'> Webcam Stream with RGB Channel Separation</h3>", unsafe_allow_html=True) | |
| st.markdown(""" | |
| - The image captured by the webcam is divided into three parts: Red, Green, and Blue. This is done using `cv2.split()` | |
| - The separate Red, Green, and Blue images are then combined back into three full-color images using `cv2.merge()`. | |
| - This lets us see each color channel on its own, but in full color. | |
| """) | |
| st.code(""" | |
| vid = cv2.VideoCapture(0) # default id = 0 | |
| while True: | |
| suc,img=vid.read() | |
| if suc == False: | |
| print("Web Camera is not working") | |
| break | |
| b,g,r=cv2.split(img) | |
| z = np.zeros(b.shape,dtype=np.uint8) | |
| cv2.imshow("live stream",img) | |
| cv2.imshow("livestream1",cv2.merge([b,z,z])) # Blue channel | |
| cv2.imshow("livestream2",cv2.merge([z,g,z])) # Green channel | |
| cv2.imshow("livestream3",cv2.merge([z,z,r])) # Red channel | |
| if cv2.waitKey(1) & (255) == ord("q"): | |
| break | |
| cv2.destroyAllWindows() | |
| """,language="python") | |
| st.markdown("<h3 style='text-align: left; color: #ffa500;'>Webcam Frame Capture and Save</h3>", unsafe_allow_html=True) | |
| st.markdown(""" | |
| - **Activate Webcam**: The webcam is activated automatically when the application starts. | |
| - **Capture Frames**: Press the 's' key to capture and save the current frame to the 'captured_frames' folder. | |
| - **Stop Webcam Feed**: Press the 'p' key to stop the webcam and close the application. | |
| """) | |
| st.code(""" | |
| vid = cv2.VideoCapture(0) # default id = 0 | |
| c=0 | |
| while True: | |
| suc,img=vid.read() | |
| if suc == False: | |
| print("Web Camera is not working") | |
| break | |
| cv2.imshow("video",img) | |
| if cv2.waitKey(1)& (255) == ord("s"): | |
| cv2.imwrite("Path to save".format(c),img) #path to save the images | |
| print("image have been captured") | |
| c+=1 | |
| if cv2.waitKey(1)& (255) == ord("q"): | |
| break | |
| cv2.destroyAllWindows() | |
| """,language = "python") | |
| if st.button("Back to Home"): | |
| st.session_state['page'] = "home" | |
| # Main Page | |
| def main_page(): | |
| # Title and Introduction | |
| st.title("📊 What is Data?") | |
| st.write("Data is information we collect to understand or learn something. It can be numbers, words, pictures, or even videos. For example, counting the number of students in a class gives us data.") | |
| # Types of Data | |
| st.header("📂 Types of Data") | |
| st.write("Data is divided into three types based on how it is organized: **Structured Data**, **Semi-Structured Data**, and **Unstructured Data**.") | |
| data_type = st.radio("Select Data Type:", ["Structured", "Semi-Structured", "Unstructured"]) | |
| if data_type == "Structured": | |
| if st.button("Excel"): | |
| st.session_state['page'] = "excel" | |
| elif data_type == "Semi-Structured": | |
| st.write("Semi-Structured Data includes formats like CSV, JSON, XML, and HTML.") | |
| if st.button("CSV"): | |
| st.session_state['page'] = "csv" | |
| if st.button("JSON"): | |
| st.session_state['page'] = "json" | |
| if st.button("XML"): | |
| st.session_state['page'] = "xml" | |
| if st.button("HTML"): | |
| st.session_state['page'] = "html" | |
| elif data_type == "Unstructured": | |
| st.write("Unstructured Data includes formats like Images and Videos.") | |
| if st.button("Image"): | |
| st.session_state['page'] = "image" | |
| if st.button("Video"): | |
| st.session_state['page'] = "video" | |
| # Structured Data | |
| st.subheader("1️⃣ Structured Data 🗂️") | |
| st.write(""" | |
| This type of data is well-organized, like in a table with rows and columns. It's easy to store and analyze. | |
| - **Examples:** | |
| - Names, phone numbers, and addresses in a spreadsheet. | |
| - Sales records in a database. | |
| """) | |
| st.write("**💡 Simple Story:** Think of a grocery store where every item has its price, category, and stock neatly listed on a computer.") | |
| # Semi-Structured Data | |
| st.subheader("2️⃣ Semi-Structured Data 📜") | |
| st.write(""" | |
| This type of data is somewhat organized but not as strict as tables. It has a format but doesn’t fit perfectly into rows and columns. | |
| - **Examples:** | |
| - Emails (with subject, sender, and message). | |
| - JSON or XML files used in apps and websites. | |
| """) | |
| st.write("**💡 Simple Story:** Imagine writing a letter that has a date, sender’s name, and the main message. It’s structured in parts but not as fixed as a table.") | |
| # Unstructured Data | |
| st.subheader("3️⃣ Unstructured Data 📷") | |
| st.write(""" | |
| This is data without any specific organization. It’s harder to analyze directly. | |
| - **Examples:** | |
| - Photos and videos. | |
| - Social media posts or text messages. | |
| """) | |
| st.write("**💡 Simple Story:** Think of a messy drawer with random papers, photos, and tools. It’s useful, but you need to sort it out to find what you need.") | |
| # Conclusion | |
| st.header("🔍 Conclusion") | |
| st.write("Understanding the types of data helps us decide how to use it. Structured data is like a neat file cabinet, semi-structured is like a stack of papers with labels, and unstructured is like a box of random items.") | |
| # Initialize session state | |
| if 'page' not in st.session_state: | |
| st.session_state['page'] = "home" | |
| # Route to appropriate page | |
| if st.session_state['page'] == "home": | |
| main_page() | |
| elif st.session_state['page'] == "excel": | |
| excel_details_page() | |
| elif st.session_state['page'] == "csv": | |
| csv_details_page() | |
| elif st.session_state['page'] == "json": | |
| json_details_page() | |
| elif st.session_state['page'] == "xml": | |
| xml_details_page() | |
| elif st.session_state['page'] == "html": | |
| html_details_page() | |
| elif st.session_state['page'] == "image": | |
| image_details_page() | |
| elif st.session_state['page'] == "video": | |
| video_details_page() | |