Spaces:
Sleeping
Sleeping
File size: 31,732 Bytes
1a9e31e 6d0ac90 1a9e31e 34b9f66 1a9e31e b4054df 40cc5af 711fa2a 110c3a3 f46db3c 71653b0 a6a94f1 de4049a a6a94f1 13df172 d6f17ae 71653b0 2a04c62 71653b0 9fa532e 018926d 5be21f1 018926d 5be21f1 018926d 5be21f1 2a04c62 9fa532e 018926d 9fa532e 71653b0 2a04c62 d1c74b9 24dfcb5 71653b0 13df172 de4049a 14cc6df 2a04c62 14cc6df 3f445a6 de4049a 2a4a68b da86e53 f28943f da86e53 2a4a68b da86e53 f28943f da86e53 2a4a68b f28943f 4826f98 5cb05e2 4fc4601 c64c383 d0d0664 b83453f d0039ea b83453f d0039ea b83453f d0039ea c64c383 9b0b0b5 3518a32 9b0b0b5 1404c5d d0d0664 1404c5d 9f0e3ea 1404c5d d0039ea 658d629 d0039ea 1404c5d d76ba39 3c597a7 d76ba39 8f85fcb 9f0e3ea 8f85fcb 3518a32 658d629 3518a32 8f85fcb 9b0b0b5 3c597a7 9b0b0b5 3518a32 e8808fa 3518a32 e8808fa 3c597a7 e8808fa 3c597a7 e8808fa 3518a32 3c597a7 870387e 5274302 870387e 76802d8 1988541 76802d8 5c4c50c 6e94d09 5c4c50c 6e94d09 5c4c50c 6e94d09 0d54743 13df172 9135c60 6ad52ee |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 |
import streamlit as st
import pandas as pd
from PIL import Image
import numpy as np
st.markdown("""
<style>
/* Set a soft background color */
body {
background-color: #eef2f7;
}
/* Style for main title */
h1 {
color: black;
font-family: 'Roboto', sans-serif;
font-weight: 700;
text-align: center;
margin-bottom: 25px;
}
/* Style for headers */
h2 {
color: black;
font-family: 'Roboto', sans-serif;
font-weight: 600;
margin-top: 30px;
}
/* Style for subheaders */
h3 {
color: red;
font-family: 'Roboto', sans-serif;
font-weight: 500;
margin-top: 20px;
}
.custom-subheader {
color: black;
font-family: 'Roboto', sans-serif;
font-weight: 600;
margin-bottom: 15px;
}
/* Paragraph styling */
p {
font-family: 'Georgia', serif;
line-height: 1.8;
color: black;
margin-bottom: 20px;
}
/* List styling with checkmark bullets */
.icon-bullet {
list-style-type: none;
padding-left: 20px;
}
.icon-bullet li {
font-family: 'Georgia', serif;
font-size: 1.1em;
margin-bottom: 10px;
color: black;
}
.icon-bullet li::before {
content: "◆";
padding-right: 10px;
color: black;
}
/* Sidebar styling */
.sidebar .sidebar-content {
background-color: #ffffff;
border-radius: 10px;
padding: 15px;
}
.sidebar h2 {
color: #495057;
}
/* Custom button style */
.streamlit-button {
background-color: #00FFFF;
color: #000000;
font-weight: bold;
}
</style>
""", unsafe_allow_html=True)
st.subheader("UnStructured Data")
st.markdown("""
Unstructured data refers to information that does not have a predefined format or organizational structure. Examples :
<ul class="icon-bullet">
<li>IMAGE🖼️ </li>
<li>AUDIO🔊 </li>
<li>VIDEO🎥 </li>
<li>TEXT 🖹</li>
</ul>
""", unsafe_allow_html=True)
st.sidebar.title("Navigation 🧭")
file_type = st.sidebar.radio(
"Choose a file type :",
("IMAGE", "AUDIO", "VIDEO", "TEXT"))
if file_type == "IMAGE":
st.title("Image 🖼️")
st.markdown("""
- Image is a 2D representation of a visible light spectrum which is collection of wavelength values
- Image in unstructured data refers to a visual file that lacks a predefined format or schema for its content
- Its information, such as shapes, colors, or objects, is not inherently organized for traditional databases typically requires specialized tools or algorithms (like image processing or machine learning) to extract meaningful insights.
""",unsafe_allow_html=True)
st.sidebar.header("Explore Image Data ✨")
data_type1 = st.sidebar.radio("Select Information", ["Image Information","Basic Operations", "Color Space","Image Augumentation"])
if data_type1 == "Image Information":
st.header("**Image Information**")
st.header('**How an image is formed**')
st.subheader('''**Source of light**''')
st.markdown('''
- 2D grid like structure which is divided by horizontal and vertical lines
- Every grid is pixel
- Every pixel is a feature and the information can be shapes, patterns, color
- Height * width = pixels
''')
st.markdown('''
- As no.of rows , columns or height and width increases --> pixel increases
- As pixel increases there is more information --> gives higher clarity
- As resolution increases --> clarity of pixels increases
- Every single image is considered as a data point and each grid or pixel is a feature
- Tabular structure and grid like structure has similar structure but different in interpretation
''')
if st.button("GitHub Link 🔗 (Image)"):
st.write("**GitHub Repository:** [Provide your GitHub link here]")
elif data_type1 == "Basic Operations":
st.header('**Basic Operations**')
st.markdown("""
- OpenCV offers a variety of tools to work with images, including the ability to load, display, modify, and save them.
- OpenCV handles both images and videos.
- Especially images are handled by pil --> pillow
- These operations are essential for tasks such as image processing, computer vision.
""")
st.subheader('**Image Operations**')
st.markdown("""
- OpenCV allows users to perform basic operations like reading, displaying, and saving images.
- Along with that it also performs resizing, cropping, and filtering of images based on requirements.
- **Key Functions:** `imread()`, `imshow()`, `imwrite()`
- **`imread()`**: Reads an image from the disk, storing it as an array.
- **`imshow()`**: Displays the image in a window, allowing for easy visualization.
- **`imwrite()`**: Saves the image to a specified location on your storage.
```python
# Example Usage of OpenCV Functions
import cv2
image = cv2.imread('path')
# Reads an image - it always converts to 3D array which uses RGB color space
cv2.imshow('Image', array)
# Displays the image - Creates a pop-up window --> give any name in string format - and then take the array and display
cv2.waitKey()
# It adds a delay --> for how many milliseconds the pop-up window should be active in screen
cv2.destroyAllWindows()
# To remove from RAM --> automatically removes from RAM
cv2.imwrite('output.jpg', image)
# Converts array to shape
cv2.resize(image)
# Resizes an image to a given dimension.
""", unsafe_allow_html=True)
st.subheader('**Image to Tabular Data**')
st.markdown('''
- Basically there are 5 steps to convert a iamge into tabular data
- **Image** which is in 2D format converts into array uses color space(gray) using a image operation `imread()`.
- **Array** which can be of any dimension so to make sure that every array having same dimension or (pixels) we use `resize()` operation
- **Resize** which can be done in 2 ways which are `Compression` and `Expansion`
- **`Compression`** - It removes pixels which has a disadvantage of loosing the information
- **`Expansion`** - It adds rows or columns which has a disadvantage of adding noise
- lots of information is lost --> type of features lost are **Spatial Features**
- **Flatten** after resizing the image it converts every nd array to 1D array
- **Concatenation** after flattening the array then concatenate every 1D array
---> So that image is converted into tabular data
- Images ------> Array ------> Resize ------> Flatten ------>Concatenation
- using thse steps images are converted into tabular data
''')
st.subheader('**Conditions for an Array to be considered as Image representation**')
st.markdown('''
- Array can be only thought as image representation if and only if:
- **It should be either 2D or 3D array**
- **Data type of array should be `np.uint8`(unsigned int)**
- Every numpy can be an image which is 2D, 3D
- Where 2D, 3D array data type should be unsigned int8
''')
st.subheader('**Handling Images with OpenCV**')
st.markdown("""
Handling images involves tasks like reading, displaying, resizing, and modifying images.
**Example: Loading and Displaying an Image**
```python
import cv2
img = cv2.imread('image.jpg')
cv2.imshow('Loaded Image', img)
cv2.waitKey()
cv2.destroyAllWindows()
```
""")
st.subheader("**Basic Code**")
st.markdown("""
Below is an example demonstrating fundamental OpenCV operations.
The code reads an image, resizes it and then displays and saves the final image.
""", unsafe_allow_html=True)
st.markdown("""
**1. Read the image**
import cv2
image = cv2.imread('path') # Provide the path to your image
if image is None:
print("Error: Image not found")
exit()
**2. Display the original image**
```python
cv2.imshow('Original Image', image)
cv2.waitKey() # It adds the delay and closes the window when a key is given
cv2.destroyAllWindows()
```
**3. Resize the image to 200x200 pixels**
```python
resized_image = cv2.resize(image, (200, 200))
```
**4. Save the loaded image**
```python
cv2.imwrite('output_image.jpg',image)
print("Image saved successfully!")
```
""", unsafe_allow_html=True)
st.markdown("""
<h4 style='color:#FFA500;'> Code Explanation</h4>
- **Step 1: Reading the Image**: `cv2.imread()` loads the image from the specified file path. If the file is not found, the script will terminate with an error message.
- **Step 2: Displaying the Original Image**: `cv2.imshow()` displays the original image in a window. The window will remain open until a key is pressed.
- **Step 3: Resizing the Image**: `cv2.resize()` resizes the image to specified dimensions (in this case, 200x200 pixels)
- **Step 4: Saving the Loaded Image**: `cv2.imwrite()` saves the final loaded image to a file.
By following these steps, you can perform common image operations
""", unsafe_allow_html=True)
elif data_type1 == "Color Space":
st.header('**Color Space**')
st.markdown("""
There are 3 types of Color Spaces
<ul class="icon-bullet">
<li>Black & White Color Space </li>
<li>Gray Scale Color Space </li>
<li>RGB Color Space </li>
</ul>
""", unsafe_allow_html=True)
st.header('**Black & White Color Space**')
st.markdown('''
- It preserves only two colors which are **black(0) and white(1)**
- For converting image into numerical as the image is 2D format numpy is used
- Here there is no color preservation
- As image is represented in 0's and 1's which will be only in black and white in grid format
- To neglect the color preservation of black and white color space next gray scale is used
''')
st.header('**Gray Scale Color Space**')
st.markdown('''
- It preserves total 256 colors which is [0 - 255]
- Where 0 represent black and 255 represent white , [1 - 255] --> shades of grey color
- If the image is colored then the both gray scale and colorspace are not used
- Gray scale converts to different shades of gray
- Black and white converts to either black or white
''')
st.header('**RGB Color Space**')
st.markdown('''
- While converting image to numerical it can't convert as it has 3 colors --> as it converts to 3D array
- There are 3 channels in RGB Color Space
- *Red Channel*
- *Green Channel*
- *Blue Channel*
''')
st.subheader('**Red Channel**')
st.markdown('''
- It is 2D array which has [0 - 255]
- 0 means black and 255 is red , [0 - 255] between is shades of red
- Red channel is taken and kept at depth of 1 --> depth always represents color
- As it is always constant
''')
st.subheader('**Green Channel**')
st.markdown('''
- It is 2D array which has [0 - 255]
- 0 means black and 255 is green , [0 - 255] between is shades of green
- Red channel is taken and kept at depth of 2 --> depth always represents color
- As it is always constant
''')
st.subheader('**Blue Channel**')
st.markdown('''
- It is 2D array which has [0 - 255]
- 0 means black and 255 is blue , [0 - 255] between is shades of blue
- Red channel is taken and kept at depth of 3 --> depth always represents color
- The combination of 3 chnnels give 3D array where depth represents color and it is always constant
''')
st.subheader("**Color Space Conversion with `cv2.cvtColor()`**")
st.markdown("""
- OpenCV provides the `cv2.cvtColor()` function to converts one colorspace to any colospace.
**Example: Displaying the Grayscale Image**
```python
import cv2
img = cv2.imread('image path')
gray_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
cv2.imwrite('gray_image.jpg', gray_img)
```
- The grayscale image is saved to a file gray_image.jpg.
""")
st.subheader("**Types of Color Space Conversions**")
st.markdown("""
- **RGB to Grayscale**: `cv2.COLOR_RGB2GRAY` converts a color image to grayscale
- **Grayscale to RGB**: `cv2.COLOR_GRAY2RGB` converts a grayscale image back to a 3-channel RGB image
""")
st.subheader('**Splitting and Merging Channels**')
st.markdown("""
- **Splitting Channels**: Use `cv2.split()` to separate the image into individual channels (B, G, R).
```python
import cv2
blue, green, red = cv2.split(image)
```
- **Merging Channels**: Combine individual channels back into a single image using `cv2.merge()`.
```python
import cv2
merged_image = cv2.merge((blue, green, red))
```
""", unsafe_allow_html=True)
st.markdown("""
**1. Read the image**
```python
image = cv2.imread('input_image.jpg')
if image is None:
print("Error: Image not found")
exit()
```
**2. Convert RGB to Grayscale**
```python
gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
```
**3. Convert Grayscale back to RGB**
```python
rgb_image = cv2.cvtColor(gray_image, cv2.COLOR_GRAY2BGR)
```
**4. Split channels (B, G, R)**
```python
blue, green, red = cv2.split(image)
```
**5. Merge channels back**
```python
merged_image = cv2.merge((blue, green, red))
```
**6. Save the processed image**
```python
cv2.imwrite('processed_image.jpg', merged_image)
```
""", unsafe_allow_html=True)
st.markdown("""
- Explanation :
- **Step 1**: Read the image using `cv2.imread()`. Terminates if the image file is not found.
- **Step 2**: Convert the image to Grayscale using `cv2.cvtColor()`. This simplifies the image to a single channel.
- **Step 3**: Convert the Grayscale image back to RGB to enable further processing.
- **Step 4**: Use `cv2.split()` to separate the image into individual color channels.
- **Step 5**: Combine the channels back into a single image using `cv2.merge()`.
- **Step 6**: Save the final loaded image with `cv2.imwrite()`.
""", unsafe_allow_html=True)
elif data_type1 == "Image Augumentation":
st.header('**Image Augumentation**')
st.markdown('''
- Image Augumentation is a technique of creating new data **(augumented image)** from your existing data
- It is used to tranform imbalanced data to balanced data
- When we're using image augumentation imbalanced data is converted into balanced data and lots of new information is added
- **Image Augumentation is on original image when tranformations are applied it changes to transformd image**
- Here transformations are of 2 types:
<ul class="icon-bullet">
<li>Affine Transformations</li>
<li>Non-affine Transformations </li>
</ul>
''', unsafe_allow_html=True)
st.subheader('**Affine Transformation**')
st.markdown('''
- Fffine transformation is a type of geometric transformation that preserves the straightness of lines and the parallelism of edges in an image.
- **Key Characterisistics are:**
- **Preserves Parallelism** : If transformed image and original image parallelism between the lines are preserved
- **Preserves Lines** : Length of the lines are preserved
- **Does Not Preserve Angles** : It doesn't preserve angle and distance but sometimes angle between lines is preserved
- There are 5 types of affine transformations:
<ul class="icon-bullet">
<li>Translation</li>
<li>Rotation</li>
<li>Scaling</li>
<li>Shearing</li>
<li>Cropping</li>
</ul>
''', unsafe_allow_html=True)
st.markdown('''
- **Image Augumentation using Affine Tranformation matrix:**
- Formula:
$$
I'(x',y') = ATM \cdot I(x,y)
- I(x,y) ---> original image
- ATM ---> affine tranformation matrix
- I'(x',y') ---> augumented image
$$
''', unsafe_allow_html=True)
st.header("Affine Transformation Workflow")
st.markdown("""
The general steps for performing affine transformation in OpenCV:
1. Load the Image
2. Define Source and Destination Points
3. Calculate the Transformation Matrix
4. Apply `cv2.warpAffine()`
5. Display or Save the Transformed Image
""", unsafe_allow_html=True)
st.subheader('**Translation**')
st.markdown('''
- Translation is a type of affine transformation matrix used to shift the image
- It shifts the image both in x-axis direction and y-axis direction
- Formula:
$$
I(x,y) \cdot Translation matrix = I'(x',y')
$$
- Formula:
$$
x' = x + t_x \\
y' = y + t_y
$$
- **Translation matrix**:
- [1 0 Tx
0 1 Ty]
- **Tx**
- Tx --> move on x-axis
- Tx --> Right shift in +ve
- Ty --> Left shift in -ve
- **Ty**
- Ty --> move on y-axis
- +ve which is downwards
- -ve which is upwards
''')
st.code('''
import cv2
## creation of translation matrix
tx = 100
ty = 100
t_m = np.array([[1,0,tx],[0,1,ty]],dtype=np.float32)
## applies the translation affine transformation using warpAffine
t_img = cv2.warpAffine(img,t_m,(2560,1600),borderMode=cv2.BORDER_CONSTANT,borderValue=(0,0,0))
## save and display the image
cv2.imshow("org_img",img)
cv2.imshow("trans_img",t_img)
cv2.waitKey()
cv2.destroyAllWindows()
''')
st.subheader('**Rotation**')
st.markdown('''
- Rotation is a affine transformation matrix which rotates the image at one angle
- Formula:
$$
I(x,y) \cdot Rotation matrix = I'(x',y')
$$
- Formula:
$$
x' = x \cdot \cos(θ) - y \cdot \sin(θ) \\
y' = x \cdot \sin(θ) + y \cdot \cos(θ)
$$
- **Rotation matrix:**
- [cos(θ) sin(θ) Tx=0
sin(θ) cos(θ) Ty=0 ]
- θ is angle between image pixel and x-axis
- always rotation is in anti-clockwise direction when angle is +ve
- always rotation is in clockwise direction when angle is -ve
- cos(θ) is anti-clockwise
- Angle is between choosen pixel values
''')
st.code('''
import cv2
## creation of rotation matrix
r_m = cv2.getRotationMatrix2D((800,1280),0,1)
## applies the rotation affine transformation using warpAffine
r_img = cv2.warpAffine(img,r_m,(2560,1600))
## save and display the image
cv2.imshow("org_img",img)
cv2.imshow("rotated_img",r_img)
cv2.waitKey()
cv2.destroyAllWindows()
''')
st.subheader('**Scaling**')
st.markdown('''
- Scaling is a affine transformation matrix used for zoom-in and zoom-out which is **(compression and expansion)**
- Formula:
$$
I(x,y) \cdot Scaling matrix = I'(x',y')
$$
- **Scaling matrix:**
- [Sx 0 Tx
0 Sy Ty]
- Sx is how much we can scale on x-axis
- Sy is how much we can scale on y-axis
- Formula:
$$
x' = x + shearX \cdot y \\
y' = y + shearY \cdot x
$$
''')
st.code('''
import cv2
## creation of scaling matrix
sx = 0.3
sy = 0.3
tx = 0
ty = 0
sc_m = np.array([[sx,0,tx],[0,sy,ty]],dtype=np.float32)
## applies the scaling affine transformation using warpAffine
scale_img = cv2.warpAffine(img,sc_m,(2560,1600))
## save and display the image
cv2.imshow("org_img",img)
cv2.imshow("scaled_img",scale_img)
cv2.waitKey()
cv2.destroyAllWindows()
''')
st.subheader('**Shearing**')
st.markdown('''
- Shearing is a affine transformation matrix which is used for expansion on x-axis and y-axis
- Formula:
$$
I(x,y) \cdot Shearing matrix = I'(x',y')
$$
- **Shearing matrix:**
- [1 Shx Tx
Shy 1 Ty]
- Formula:
$$
x' = x + shearX \cdot y \\
y' = y + shearY \cdot x
$$
''')
st.code('''
import cv2
## creation of shearing matrix
shx = 0.3
shy = 1
tx = 100
ty = 100
sh_m = np.array([[1,shx,tx],[shy,1,ty]],dtype=np.float32)
## applies the shearing affine transformation using warpAffine
shear_img = cv2.warpAffine(img,sh_m,(2560,1600))
## save and display the image
cv2.imshow("org_img",img)
cv2.imshow("shear_img",shear_img)
cv2.waitKey()
cv2.destroyAllWindows()
''')
st.subheader('**Cropping**')
st.markdown('''
- Cropping is a affine transformation matrix used to crop the image in size using indexing
''')
st.code('''
import cv2
## loads the image
img = cv2.imread(path)
## by indexing crop the image
c_m = img[98:408,390:565]
## save and display the image
cv2.imshow("org_img",img)
cv2.imshow("crop_img",c_m)
cv2.waitKey()
cv2.destroyAllWindows()
''')
if file_type == "VIDEO":
st.title("**Video🎥**")
st.markdown('''
- Video refers to a sequence of frames (images) captured or processed over time.
- OpenCV provides robust tools to read, process, and write videos using its VideoCapture class.
''')
st.header('**Video Handling with OpenCV**')
st.markdown('''
In OpenCV, videos are treated as a sequence of images called frames. We can process videos using the `cv2.VideoCapture()` class, which allows you to:
- Read video files from your system.
- Capture live video from a webcam or other video input devices.
- Process each frame in the video stream individually.
''')
st.subheader('**Reading a Video File**')
st.markdown('''
To read a video file, OpenCV uses the `cv2.VideoCapture()` function. It loads the video file and allows you to process each frame sequentially.
The following example demonstrates how to:
- Read frames from a video file.
- Display the video in a window.
''')
st.subheader("**Key Methods in Video Capturing**")
st.markdown("""
Here are some key methods used in video capturing with OpenCV:
- **`cv2.VideoCapture()`**: Opens the video source, either a camera (index 0 for default webcam) or a video file path.
- **`read()`**: Reads frames from the video stream. It returns a boolean value and the frame (`frame`).
- **`release()`**: Releases the video capture object and closes the video stream.
- **`cv2.namedWindow()`**:It actually creates a pop-up window and all the features of pop-up window will be created
- **`cv2.imshow()`**: As it is not creating pop-up window ,it internally calls the namedWindow() where we can create our own pop-up window
- **`cv2.waitKey()`**: It internally creates a po-up window and for that window it is going to add delay.Waits for a key event for a specified amount of time (in milliseconds). It returns the ASCII value of the key pressed.If 0 is passed, it waits indefinitely until a key is pressed.
- **`cv2.destroyAllWindows()`**: Closes all OpenCV windows that were opened during the program's execution.
- **`cv2.MouseCallBack()`**: It is a technique where we can make lot of things automated
- **`cv2.SetMouseCallBack()`**:It will be automatically activated when we hover the mouse inside pop-up window.
- It is going to call user-defined function which tracks the events of mouse
- It contains 5 parameters
- **5 parameters:**
- def fun(event,x,yflags,param):
- **Event**: It is going to track all windows what event has performed inside pop-up window
- **x,y**: x,y are rows and columns
- **flags**: It is used to track an event where we can include additional features
- **param**: It is used to add additional functions
These methods are useful in forming the foundation of real-time video processing in OpenCV,
and also essential for handling the display and closing of images in OpenCV applications.
""")
st.subheader("**Reading and Displaying a Video**")
st.code("""
import cv2
# Open the video file
video = cv2.VideoCapture("path_to_video.mp4")
# Loop to read and display frames
while True:
success, frame = video.read() # Read a frame
if not success:
print("Video Ended")
break
cv2.imshow("Video Playback", frame) # Display the frame
# Break loop on 'q' key press
if cv2.waitKey(1) & 255 == ord('q'):
break
video.release() # Release the video file
cv2.destroyAllWindows() # Close all OpenCV windows
""", language="python")
st.markdown("---")
st.subheader("**Understanding `cv2.waitKey()` and Key Input**")
st.write("""
The line `if cv2.waitKey(1) & 255 == ord('q'):` is used in OpenCV to handle keyboard input while processing video frames. Here’s a breakdown:
- **`cv2.waitKey(1)`**:
- Waits for a key press for `1` millisecond.
- Returns the ASCII value of the key pressed, or `-1` if no key is pressed.
- **`& 255`**:
- Extracts only the last 8 bits (ASCII value).
- **`ord('q')`**:
- Provides the ASCII value of the character `'q'`.
- The condition checks if the user pressed the `'q'` key to quit the program.
""")
st.header("**Capturing and Saving a Specific Frame**")
st.markdown("""
- Use OpenCV to capture a specific frame from a video and save it as an image file.
""")
st.subheader("Example: Saving a Frame")
st.code("""
import cv2
video = cv2.VideoCapture("path_to_video.mp4") # Replace with 0 for webcam
while True:
success, frame = video.read()
if not success:
break
cv2.imshow("Video", frame)
# Save frame on 's' key press
if cv2.waitKey(1) & 255 == ord('s'):
cv2.imwrite("captured_frame.jpg", frame)
print("Frame saved as captured_frame.jpg")
# Break loop on 'q' key press
if cv2.waitKey(1) & 255 == ord('q'):
break
video.release()
cv2.destroyAllWindows()
""", language="python")
st.header("**Capturing Video from Webcam**")
st.markdown("""
- The `cv2.VideoCapture()` function can also be used to capture live video from your webcam or connected camera devices.
""")
st.subheader("**Example of Capturing Video from Webcam**")
st.code("""
import cv2
# Open video capture (0 for primary webcam)
video = cv2.VideoCapture(0)
# Loop to read frames
while True:
success, frame = video.read() # Read a frame
if not success:
break
cv2.imshow("Webcam", frame) # Display the frame
# Break loop on 'q' key press
if cv2.waitKey(1) & 255 == ord('q'):
break
video.release() # Release the video capture object
cv2.destroyAllWindows() # Close all OpenCV windows
""", language="python")
st.header("**Processing Video: Converting to Grayscale**")
st.markdown("""
You can process each frame of the video in real-time.By following steps:
- Convert each frame of a video to grayscale.
- Display the processed video.
""")
st.subheader("**Example of Converting Video to Grayscale**")
st.code("""
import cv2
# Open the video file
video = cv2.VideoCapture("path_to_video.mp4")
# Loop to read and process frames
while True:
success, frame = video.read() # Read a frame
if not suc:
break
gray_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) # Convert frame to grayscale
cv2.imshow("Grayscale Video", gray_frame) # Display the processed frame
# Break loop on 'q' key press
if cv2.waitKey(30) & 255 == ord('q'):
break
video.release() # Release the video file
cv2.destroyAllWindows() # Close all OpenCV windows
""", language="python")
st.header("**Splitting Channels in a Video Frame**")
st.markdown("""
- You can split the three color channels (Blue, Green, and Red) from a video frame and process them individually.
""")
st.subheader("Example: Splitting Video Frame Channels")
st.code("""
import cv2
# Open video capture
video = cv2.VideoCapture("path_to_video.mp4") # Replace with 0 for webcam
while True:
success, frame = video.read()
if not success:
break
# Split the frame into channels
b, g, r = cv2.split(frame)
# Merge and display individual channels
blue_img = cv2.merge([b, g*0, r*0])
green_img = cv2.merge([b*0, g, r*0])
red_img = cv2.merge([b*0, g*0, r])
cv2.imshow("Original Frame", frame)
cv2.imshow("Blue Channel", blue_img)
cv2.imshow("Green Channel", green_img)
cv2.imshow("Red Channel", red_img)
# Break loop on 'q' key press
if cv2.waitKey(1) & 255 == ord('q'):
break
video.release()
cv2.destroyAllWindows()
""", language="python")
if st.button("GitHub Link 🔗 (Video)"):
st.write("**GitHub Repository:** [Provide your GitHub link here]")
|