Spaces:
Sleeping
Sleeping
File size: 82,551 Bytes
db9e325 e29723f 31e7792 b2c23d9 55b4077 31e7792 db9e325 e29723f db9e325 e29723f 911253b e29723f 911253b a5ce67c 911253b d758b45 414089c b8484bf 414089c db9e325 9463b76 e29723f 08858a0 e29723f 08858a0 e29723f 08858a0 e29723f 9463b76 08858a0 e29723f bb0ed14 c201e4c bb0ed14 69f2239 f2259ac 69f2239 bb0ed14 f2259ac e29723f ce4df21 04b689e ce4df21 74fb91f ce4df21 74fb91f ce4df21 486ccb0 ce4df21 486ccb0 ce4df21 486ccb0 74fb91f 486ccb0 74fb91f 486ccb0 e29723f ce4df21 9463b76 e29723f 334b087 140a95d 334b087 140a95d 334b087 140a95d 334b087 140a95d 334b087 140a95d 334b087 140a95d 334b087 140a95d 334b087 140a95d 334b087 140a95d 334b087 140a95d 334b087 140a95d 334b087 140a95d 334b087 140a95d 334b087 140a95d 334b087 140a95d 334b087 140a95d 334b087 140a95d 334b087 140a95d 334b087 140a95d 9463b76 1749ad2 e29723f 7f28719 bf61356 7f28719 2b19b54 7f28719 2b19b54 aa140e4 7f28719 bf61356 11f9713 bf61356 8a70c80 bf61356 11f9713 fca0995 11f9713 ad0c3b0 783fb2f 11f9713 157d6fd 11f9713 fca0995 11f9713 ad0c3b0 783fb2f 11f9713 157d6fd 11f9713 783fb2f fca0995 c98b109 11f9713 783fb2f 11a9a4c 11f9713 ad0c3b0 c98b109 aa140e4 7f28719 c666782 7f28719 21e094d 7f28719 21e094d 7f28719 21e094d 7f28719 bf61356 7f28719 21e094d 7f28719 21e094d 7f28719 21e094d 7f28719 bf61356 7f28719 21e094d 7f28719 21e094d 7f28719 21e094d bf61356 21e094d bf61356 7f28719 bf61356 7f28719 21e094d 7f28719 21e094d bf61356 21e094d 7f28719 21e094d 7f28719 bf61356 7f28719 bf61356 7f28719 bf61356 7f28719 bf61356 7f28719 29c4c71 7f28719 bf61356 7f28719 bf61356 7f28719 bf61356 7f28719 89f9d0c bf61356 7f28719 bf61356 7f28719 bf61356 7f28719 bf61356 7f28719 bf61356 7f28719 bf61356 a3e9a7d bf61356 7f28719 bf61356 7f28719 b06dcde 8a70c80 a3e9a7d 11a9a4c a3e9a7d 11a9a4c a3e9a7d 11a9a4c a3e9a7d 11a9a4c a3e9a7d 11a9a4c a3e9a7d 8a70c80 bf61356 8a70c80 3f6d752 8a70c80 bf61356 7f28719 e29723f fa40f07 9aaa374 bc6c0bc 945277f fa40f07 bc6c0bc e80ceac bc6c0bc 945277f bc6c0bc 945277f bc6c0bc 945277f bc6c0bc 945277f bc6c0bc 945277f bc6c0bc 4929e2b fa40f07 bc6c0bc 4929e2b bc6c0bc 4a0f836 bc6c0bc 29c4c71 4929e2b bc6c0bc fa40f07 945277f fa40f07 bc6c0bc 945277f bc6c0bc 29c4c71 fa40f07 bc6c0bc fa40f07 4929e2b bc6c0bc 4a0f836 fa40f07 8dcbcf2 bc6c0bc 4a0f836 bc6c0bc 945277f fa40f07 bc6c0bc 0249cda bc6c0bc 4a0f836 bc6c0bc 29c4c71 9708550 1a70c54 bc6c0bc b5f0e5c 648a44c 1a70c54 e29723f 1a70c54 e29723f 1a70c54 53601b7 1a70c54 e6c9b3a 1a70c54 53601b7 e6c9b3a 88fde66 61e591e 1a70c54 61e591e bbd6d79 61e591e fb098f8 55b4077 fb098f8 55b4077 fb098f8 55b4077 fb098f8 55b4077 fb098f8 55b4077 fb098f8 607bb85 e29723f cced416 7906df1 b5f0e5c 29c478e b5f0e5c a044396 7906df1 8497e0a 29c478e 8497e0a 29c478e 8497e0a 7906df1 29c478e 8ae48d0 67adddc 8ae48d0 29c478e 67adddc a044396 7906df1 b5f0e5c 6310ce8 b5f0e5c 6310ce8 bb3e46f 29c478e a044396 7906df1 b5f0e5c e29723f db9e325 e29723f b5f0e5c 88fde66 b5f0e5c |
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 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 |
import streamlit as st
import pandas as pd
import matplotlib.pyplot as plt
import cv2
import io
import zipfile
import numpy as np
# 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 = "white"
# 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")
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/1ePttPUBbaq9DjGS0OuzLhe32KNPStaLR"
st.write("Click below for Jupyter notebook:")
st.markdown(f"[Open Jupyter Notebook in Google Colab]({notebook_url})")
# 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("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("<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/1JD2AbzrHaDEg2BMFHeNdFCPbHk3Nb1pW"
st.write("Click below for Jupyter notebook:")
st.markdown(f"[Open Jupyter Notebook in Google Colab]({notebook_url})")
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)
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/1bbw_pOPjiCXghTnfZCnPmNz9znn9Utgp"
st.write("Click below for Jupyter notebook:")
st.markdown(f"[Open Jupyter Notebook in Google Colab]({notebook_url})")
# 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: left; color: #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")
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/1bbw_pOPjiCXghTnfZCnPmNz9znn9Utgp"
st.write("Click below for Jupyter notebook:")
st.markdown(f"[Open Jupyter Notebook in Google Colab]({notebook_url})")
# Open Cv Project
if st.button("opencv_projects"):
st.session_state['page'] = "OpenCV Projects"
def opencv_projects_page():
st.title("OpenCV Projects")
st.markdown("""
<h2 style="color: #BB3385;">OpenCV Projects</h2>
""", unsafe_allow_html=True)
# Project 1: Converting an Image into Tabular Data
st.markdown("""
<h3 style="color: #5b2c6f;">Converting an Image into Tabular Data</h3>
<p>
This project explains how to convert an image into tabular data by extracting pixel values
and representing them as structured rows and columns for analysis or machine learning tasks.
</p>
""", unsafe_allow_html=True)
st.markdown("""
<a href="https://github.com/hari3485/Open-Cv-Animation-project/blob/main/Extract%20Images%20to%20Tabular%20Data.ipynb"
target="_blank" style="color: #2a52be;">
Check out the project on GitHub
</a>
""", unsafe_allow_html=True)
# Project 2: Converting a Video into Tabular Data
st.markdown("""
<h3 style="color: #5b2c6f;">Converting a Video into Tabular Data</h3>
<p>
Learn to process videos frame by frame and extract pixel data from each frame.
This project demonstrates how to represent video data in a structured tabular format.
</p>
""", unsafe_allow_html=True)
st.markdown("""
<a href="https://github.com/hari3485/Open-Cv-Animation-project/blob/main/Extract%20Videos%20to%20Tabular%20Data.ipynb"
target="_blank" style="color: #2a52be;">
Check out the project on GitHub
</a>
""", unsafe_allow_html=True)
# Project 3: Animation Project
st.markdown("""
<h3 style="color: #5b2c6f;">A Tale of Integrity: Finding Money, Choosing Honesty</h3>
<p>
This animation tells the story of a young boy who finds a bundle of money. Torn between keeping it or doing the right thing,
he remembers his grandfather’s words: <em>"True character shines through in moments of choice."</em>
He chooses integrity and returns the money to its rightful owner, reminding us all that honesty is priceless.
</p>
""", unsafe_allow_html=True)
st.markdown("""
<a href="https://github.com/hari3485/Open-Cv-Animation-project/blob/main/Animation%20Project.ipynb"
target="_blank" style="color: #2a52be;">
Check out the animation on GitHub
</a>
""", unsafe_allow_html=True)
st.video("https://huggingface.co/spaces/hari3485/DiveIntoML/resolve/main/Images/full_frame_video.mp4")
# Project 4: GIF Project
st.markdown("""
<h3 style="color: #5b2c6f;">The Coding Journey: Debugging Woes Turned Joy (GIF)</h3>
<p>
This humorous and relatable GIF portrays every coder’s struggle: A boy sits at his desk exclaiming,
<em>"My code is not working; I don’t know what to do!"</em> Moments later, he joyfully discovers,
<em>"It’s working perfectly!"</em> – capturing the emotional highs and lows of debugging.
</p>
""", unsafe_allow_html=True)
st.markdown("""
<a href="https://github.com/hari3485/Open-Cv-Animation-project/blob/main/Giffy.ipynb"
target="_blank" style="color: #2a52be;">
Check out the GIF on GitHub
</a>
""", unsafe_allow_html=True)
st.video("https://huggingface.co/spaces/hari3485/DiveIntoML/resolve/main/Images/giphy_animation.mp4")
if st.button("Image_Augmentation"):
st.session_state['page'] = "Image_Augmentation"
def Image_Augmentation_page():
st.title("Image Augmentation")
# Heading
st.markdown("""
<h3 style="color: #9400d3;">What is Image Augmentation?</h3>
""", unsafe_allow_html=True)
# Definition
st.write("""
Image augmentation is a method used to enhance the size and variety of an image dataset by applying transformations to existing images.
These transformations introduce variations while preserving the core features of the image, making it useful for training machine learning models to handle diverse inputs.
*How It Works*
Image augmentation applies transformations like resizing, rotation, flipping, and more to the original image. These changes simulate real-world variations, ensuring that machine learning models can identify patterns even with differences in perspective, scale, or lighting conditions.
The key idea is to preserve the original features of the image while introducing diversity. For example, if we take an image and apply five different transformations, we generate five new variations of that image. This provides the model with more data to learn from, improving its performance and ability to generalize.
""")
# Types of Image Augmentation
st.markdown("""
<h3 style="color: #9400d3;">Types of Image Augmentation</h3>
""", unsafe_allow_html=True)
st.write("""
Image augmentation is broadly categorized into two types:
1. *Affine Transformations*
2. *Non-Affine Transformations*
""")
# Affine Transformations
st.markdown("""
<h3 style="color: #9400d3;">Affine Transformations</h3>
""", unsafe_allow_html=True)
st.write("""
*Affine Transformations* are transformations where:
1. The transformed image and the original image maintain *parallelism between lines*.
2. In some cases, the *angle between lines* and the *length of the lines* may also be preserved.
These transformations ensure that the geometric relationships within the image remain intact, even as the image is resized, rotated, or shifted.
Affine transformations are performed using a mathematical operation known as an *Affine Matrix*, which maps the original image coordinates to new coordinates.
""")
st.markdown("""
<h3 style="color: #e25822;">Common Affine Transformations:</h3>
""", unsafe_allow_html=True)
st.write("""
1. *Scaling*: Changing the size of the image while maintaining its proportions.
2. *Translation*: Shifting the image horizontally, vertically, or both.
3. *Rotation*: Rotating the image around a specified center point.
4. *Shearing*: Slanting the image along the x or y axis, creating a skewed effect.
5. *Cropping*: Extracting a specific portion of the image, usually to focus on a region of interest.
These transformations are linear, meaning the relationships between points in the image remain consistent.
""")
st.image(
"https://huggingface.co/spaces/hari3485/DiveIntoML/resolve/main/Images/Image-Augmentation.jpg",
use_container_width=True)
# Explanation for Translation
st.markdown("""
<h3 style="color: #9400d3;">Translation</h3>
""", unsafe_allow_html=True)
st.write("""
*Translation* involves moving an image from one location to another along the x-axis, y-axis, or both. It adjusts the position of the image on the canvas without modifying its original content.
The transformation is performed using a translation matrix:
""")
st.write("""
The translation matrix is represented as:
[[1, 0, tx], [0, 1, ty]]
Here:
- *tx*: Specifies the shift along the x-axis (horizontal axis).
- *ty*: Specifies the shift along the y-axis (vertical axis).
""")
st.code("""
# Load the image
img = cv2.imread('path_to_image.jpg')
# Define translation parameters
tx = 100 # Shift 100 pixels along the x-axis
ty = 50 # Shift 50 pixels along the y-axis
# Create the translation matrix
translation_matrix = np.array([[1, 0, tx], [0, 1, ty]], dtype=np.float32)
# Apply translation
translated_img = cv2.warpAffine(img, translation_matrix, (300, 300))
# Display the images
cv2.imshow("Original Image", img)
cv2.imshow("Translated Image", translated_img)
cv2.waitKey(0)
cv2.destroyAllWindows()
""", language="python")
# Explanation for Rotation
st.markdown("""
<h3 style="color: #9400d3;">Rotation</h3>
""", unsafe_allow_html=True)
st.write("""
*Rotation* involves rotating an image around a specified center point by a given angle. It changes the orientation of the image while preserving its content.
The rotation is performed using a rotation matrix:
[[cos(θ), -sin(θ), tx], [sin(θ), cos(θ), ty]]
Here:
- *θ (theta)*: Specifies the rotation angle in degrees.
- *tx, ty*: Specifies the adjustments to reposition the rotated image.
- *Scale*: A factor that can resize the image during rotation.
""")
# Code Example
st.code("""
# Load the image
img = cv2.imread('path_to_image.jpg')
# Define the rotation matrix
r_m = cv2.getRotationMatrix2D((1347, 900), 50, 1) # Center at (1347, 900), Rotate by 50 degrees, Scale = 1
# Apply rotation
r_img = cv2.warpAffine(img, r_m, (580, 500), borderMode=cv2.BORDER_DEFAULT)
# Display the images
cv2.imshow("Original Image", img)
cv2.imshow("Rotated Image", r_img)
cv2.waitKey(0)
cv2.destroyAllWindows()
""", language="python")
# Explanation for Direct Rotation
st.markdown("""
<h3 style="color: #9400d3;">Direct Rotation Using cv2.rotate</h3>
""", unsafe_allow_html=True)
st.write("""
OpenCV provides a direct method for rotating images with predefined angles: cv2.rotate.
This method simplifies rotation operations for 90°, 180°, and 270° (clockwise or counterclockwise) without requiring a custom rotation matrix.
- **cv2.ROTATE_180**: Rotates the image by 180°.
- **cv2.ROTATE_90_CLOCKWISE**: Rotates the image by 90° clockwise.
- **cv2.ROTATE_90_COUNTERCLOCKWISE**: Rotates the image by 90° counterclockwise.
""")
# Code Example
st.code("""
# Rotate the image using predefined rotation modes
img1 = cv2.rotate(img, cv2.ROTATE_180) # Rotate 180 degrees
img2 = cv2.rotate(img, cv2.ROTATE_90_CLOCKWISE) # Rotate 90 degrees clockwise
img3 = cv2.rotate(img, cv2.ROTATE_90_COUNTERCLOCKWISE) # Rotate 90 degrees counterclockwise
# Display the images
cv2.imshow("Original Image", img)
cv2.imshow("Rotated 180°", img1)
cv2.imshow("Rotated 90° Clockwise", img2)
cv2.imshow("Rotated 90° Counterclockwise", img3)
cv2.waitKey(0)
cv2.destroyAllWindows()
""", language="python")
# Explanation for Shearing
st.markdown("""
<h3 style="color: #9400d3;">Shearing</h3>
""", unsafe_allow_html=True)
st.write("""
*Shearing* is a transformation that slants the shape of an image along the x-axis, y-axis, or both. It skews the content of the image, creating a shifted or stretched effect.
The transformation is performed using a shearing matrix:
""")
st.write("""
The shearing matrix is represented as:
For x-axis shear:
[[1, shx, 0], [0, 1, 0]]
For y-axis shear:
[[1, 0, 0], [shy, 1, 0]]
Here:
- *shx*: Shear factor along the x-axis.
- *shy*: Shear factor along the y-axis.
""")
st.code("""
# Load the image
img = cv2.imread('path_to_image.jpg')
# Define shearing parameters
shx = 1 # Shear factor along the x-axis
shy = 3 # Shear factor along the y-axis
tx = 0 # Translation along the x-axis
ty = 0 # Translation along the y-axis
# Create the shearing matrix
shearing_matrix = np.array([[1, shx, tx], [shy, 1, ty]], dtype=np.float32)
# Apply the shearing transformation
sheared_img = cv2.warpAffine(img, shearing_matrix, (300, 300))
# Display the original and sheared images
cv2.imshow("Original Image", img)
cv2.imshow("Sheared Image", sheared_img)
cv2.waitKey(0)
cv2.destroyAllWindows()
""", language="python")
# Explanation for Scaling
st.markdown("""
<h3 style="color: #9400d3;">Scaling</h3>
""", unsafe_allow_html=True)
st.write("""
*Scaling* is a transformation that changes the size of an image. It can be used to enlarge or shrink the image while maintaining its original proportions or altering them.
Scaling is performed using a scaling matrix:
""")
st.write("""
The scaling matrix is represented as:
[[sx, 0, 0], [0, sy, 0]]
Here:
- *sx*: Scaling factor along the x-axis.
- *sy*: Scaling factor along the y-axis.
- If sx and sy are greater than 1, the image is enlarged.
- If sx and sy are less than 1, the image is shrunk.
""")
st.code("""
# Load the image
img = cv2.imread('path_to_image.jpg')
# Define scaling and translation parameters
sx, sy = 2, 1 # Scale by 2 along the x-axis and 1 along the y-axis
tx, ty = 0, 0 # No translation
# Create the scaling matrix
scaling_matrix = np.array([[sx, 0, tx], [0, sy, ty]], dtype=np.float32)
# Apply scaling
scaled_img = cv2.warpAffine(img, scaling_matrix, (2 * 300, 300))
# Display the images
cv2.imshow("Original Image", img)
cv2.imshow("Scaled Image", scaled_img)
cv2.waitKey(0)
cv2.destroyAllWindows()
""", language="python")
# Explanation for Cropping
st.markdown("""
<h3 style="color: #9400d3;">Cropping</h3>
""", unsafe_allow_html=True)
st.write("""
*Cropping* is a transformation that extracts a specific portion of an image, usually to focus on a region of interest.
It is achieved by selecting a rectangular region of the image using pixel coordinates.
The process involves defining the coordinates for:
- *Top-left corner (x1, y1)*: Starting point of the crop.
- *Bottom-right corner (x2, y2)*: Ending point of the crop.
""")
st.code("""
# Load the image
img = cv2.imread('path_to_image.jpg')
# Define crop coordinates
x1, y1 = 50, 50 # Top-left corner
x2, y2 = 200, 200 # Bottom-right corner
# Crop the image
cropped_img = img[y1:y2, x1:x2]
# Display the images
cv2.imshow("Original Image", img)
cv2.imshow("Cropped Image", cropped_img)
cv2.waitKey(0)
cv2.destroyAllWindows()
""", language="python")
# Function to apply affine transformations
def apply_affine_transformation(image, transformation_type):
transformed_images = []
rows, cols, _ = image.shape
for i in range(1, 11): # Generate 10 variations
if transformation_type == "Rotation":
angle = i * 10
M = cv2.getRotationMatrix2D((cols / 2, rows / 2), angle, 1)
elif transformation_type == "Scaling":
scale = 1 + (i * 0.05) # Reduced scale increments
M = np.float32([[scale, 0, 0], [0, scale, 0]])
elif transformation_type == "Translation":
tx, ty = i * 5, i * 5 # Reduced translation
M = np.float32([[1, 0, tx], [0, 1, ty]])
elif transformation_type == "Shearing":
shear = 0.05 * i # Reduced shear factor
M = np.float32([[1, shear, 0], [shear, 1, 0]])
elif transformation_type == "Cropping":
# Simple cropping: reduce the size incrementally
x1, y1 = i * 5, i * 5
x2, y2 = cols - i * 5, rows - i * 5
if x1 < x2 and y1 < y2: # Ensure cropping dimensions are valid
transformed_image = image[y1:y2, x1:x2]
transformed_images.append(transformed_image)
continue # Skip warpAffine for cropping
else:
st.error("Invalid transformation type!")
return []
transformed_image = cv2.warpAffine(image, M, (cols, rows))
transformed_images.append(transformed_image)
return transformed_images
# Streamlit App
st.title("Dynamic Affine Transformation Tool")
st.write("Select a transformation type to proceed and learn how it works before uploading an image.")
# Transformation Options
transformation = st.selectbox(
"Step 1: Select a transformation type:",
["Select a Transformation", "Rotation", "Scaling", "Translation", "Shearing", "Cropping"]
)
# Ensure the user selects a valid transformation
if transformation != "Select a Transformation":
# Provide guidance based on the selected transformation
if transformation == "Rotation":
st.info("Rotation rotates the image around a fixed point. Angles are applied in steps of 10 degrees.")
elif transformation == "Scaling":
st.info("Scaling adjusts the size of the image. The scale factor increases incrementally.")
elif transformation == "Translation":
st.info("Translation shifts the image horizontally and vertically in small steps.")
elif transformation == "Shearing":
st.info("Shearing skews the image along the x-axis or y-axis, creating a slanted effect.")
elif transformation == "Cropping":
st.info("Cropping trims the image edges step by step to focus on a smaller region.")
# Image Uploader (Only appears after selection)
uploaded_file = st.file_uploader("Step 2: Now, upload an image", type=["jpg", "jpeg", "png"])
if uploaded_file:
# Read the uploaded file into a numpy array using OpenCV
file_bytes = np.asarray(bytearray(uploaded_file.read()), dtype=np.uint8)
image = cv2.imdecode(file_bytes, cv2.IMREAD_COLOR)
# Display the uploaded image
st.image(cv2.cvtColor(image, cv2.COLOR_BGR2RGB), caption="Uploaded Image", use_container_width=True)
# Automatically apply the transformation after upload
transformed_images = apply_affine_transformation(image, transformation)
if transformed_images:
st.write(f"Generated {len(transformed_images)} images using {transformation}:")
# Display all transformed images
for i, img in enumerate(transformed_images):
st.image(cv2.cvtColor(img, cv2.COLOR_BGR2RGB), caption=f"{transformation} {i+1}", use_container_width=True)
# Create ZIP file for download
zip_buffer = io.BytesIO()
with zipfile.ZipFile(zip_buffer, "w") as zip_file:
for i, img in enumerate(transformed_images):
# Save each image as bytes
_, img_encoded = cv2.imencode('.jpg', img)
zip_file.writestr(f"{transformation}image{i+1}.jpg", img_encoded.tobytes())
zip_buffer.seek(0)
st.download_button(
label=f"Download All {transformation} Images",
data=zip_buffer,
file_name=f"{transformation}_transformed_images.zip",
mime="application/zip"
)
else:
st.warning("No transformed images generated. Please check your transformation type.")
else:
st.warning("Please upload an image to proceed.")
else:
st.warning("Please select a valid transformation type to proceed.")
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":
# 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.")
names = ["Hari", "Harika", "Varshi", "Shamitha"]
cities = ["Hyderabad", "Bangalore", "Chennai", "Mumbai"]
marks = [90, 87, 98, 94]
# Create the DataFrame
data = {
"Name": names,
"City": cities,
"Marks": marks
}
df = pd.DataFrame(data)
st.subheader("Details of Students")
st.table(df)
if st.button("Excel"):
st.session_state['page'] = "excel"
elif data_type == "Semi-Structured":
# 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.")
st.markdown("""
Unlike structured data, **semi-structured data** does not require a fixed schema.
However, it often includes tags or markers to separate elements. This means that the data can be organized in a flexible way, allowing you to add new data elements without disturbing the existing ones.
""")
# Display explanation for Self-Descriptive Tags
st.subheader("Self-Descriptive Tags:")
st.markdown("""
Semi-structured data uses **tags** or **keys** to identify and describe the data. For example, in **JSON** and **XML**, the tags or keys help to organize and label the data, making it easier to understand.
""")
st.write("Semi-Structured Data includes formats like CSV, JSON, XML, and HTML.")
# JSON Data
json_data = {
"Name": "Hari",
"City": "Hyderabad",
"Marks": 90
}
# XML Data as a string
xml_data = """
<student>
<name>Hari</name>
<city>Hyderabad</city>
<marks>90</marks>
</student>
"""
html_data = """
<html>
<head><title>Student Info</title></head>
<body>
<h1>Details of Students</h1>
<table border="1">
<tr><th>Name</th><th>City</th><th>Marks</th></tr>
<tr><td>Hari</td><td>Hyderabad</td><td>90</td></tr>
<tr><td>Harika</td><td>Bangalore</td><td>87</td></tr>
<tr><td>Varshi</td><td>Chennai</td><td>98</td></tr>
<tr><td>Shamitha</td><td>Mumbai</td><td>94</td></tr>
</table>
</body>
</html>
"""
# Display JSON
st.subheader("JSON Data:")
st.json(json_data)
# Display XML
st.subheader("XML Data:")
st.code(xml_data, language='xml')
st.title("Student Data Table HTML Format")
st.code("""
<table>
<tr><th>Name</th><th>City</th><th>Marks</th></tr>
<tr><td>John</td><td>New York</td><td>95</td></tr>
<tr><td>Alice</td><td>Los Angeles</td><td>88</td></tr>
<tr><td>Bob</td><td>Chicago</td><td>92</td></tr>
<tr><td>Eve</td><td>San Francisco</td><td>90</td></tr>
</table>
""",language = "python")
# Display the table using markdown
st.markdown(html_data, unsafe_allow_html=True)
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":
# 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.")
st.write("Unstructured Data includes formats like Images and Videos.")
# Image Definition
st.subheader("What is an Image?")
st.markdown("""
An image is a visual representation, such as a photo or picture, made up of pixels. It captures information visually and can be in various formats like JPEG, PNG, or HEIC.
""")
# Image Formats
st.subheader("Image Formats:")
st.markdown("""
1. **JPEG (.jpg)**: Common for photos; uses lossy compression to reduce file size but loses some quality.
2. **JPEG 2000 (.jp2)**: Improved version of JPEG with better compression and quality, but not widely supported.
3. **HEIC (.heic)**: High-efficiency format, used on iPhones; offers better compression than JPEG without losing quality.
4. **PNG (.png)**: Lossless compression; supports transparency, ideal for images like logos or icons.
""")
# Video Definition
st.subheader("What is a Video?")
st.markdown("""
A video is a sequence of moving images, often with sound, that creates the illusion of motion. It is used for entertainment, information, and communication, commonly in formats like MP4.
""")
# Video Format
st.subheader("Video Format:")
st.markdown("""
1. **MP4 (.mp4)**: Widely used for videos; supports good quality and small file size. It’s compatible with most devices and platforms.
""")
if st.button("Image"):
st.session_state['page'] = "image"
if st.button("Video"):
st.session_state['page'] = "video"
# 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()
elif st.session_state['page'] == "OpenCV Projects":
opencv_projects_page()
elif st.session_state['page'] == "Image_Augmentation":
Image_Augmentation_page()
|