Phaneendrabayi commited on
Commit
563a874
·
verified ·
1 Parent(s): c5fe864

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +99 -144
app.py CHANGED
@@ -1,147 +1,102 @@
1
  import streamlit as st
2
- import cv2
3
  import pandas as pd
4
  import numpy as np
5
-
6
- def main():
7
- st.set_page_config(page_title="Interactive Transformations for Multiple Images", layout="wide")
8
-
9
- st.title("Interactive Affine Transformations for Multiple Images")
10
- st.write("Upload multiple images, apply transformations independently, and analyze all transformations in a unified DataFrame.")
11
-
12
- # Initialize session state for cumulative DataFrame
13
- if "combined_data" not in st.session_state:
14
- st.session_state.combined_data = pd.DataFrame(columns=["Image Name", "Transformation", "Image Data"])
15
-
16
- # Multi-file uploader
17
- uploaded_files = st.file_uploader("Upload images (JPG, PNG)", type=["jpg", "jpeg", "png"], accept_multiple_files=True)
18
-
19
- if uploaded_files:
20
- for idx, uploaded_file in enumerate(uploaded_files):
21
- with st.expander(f"Image {idx + 1}: {uploaded_file.name}"):
22
-
23
- # Allow user to input a custom image name
24
- custom_image_name = st.text_input(f"Enter custom name for {uploaded_file.name}", key=f"custom_name_{idx}")
25
-
26
- if not custom_image_name:
27
- custom_image_name = uploaded_file.name # Default to uploaded filename if no custom name is provided
28
-
29
- # Load and display the current image
30
- file_bytes = np.asarray(bytearray(uploaded_file.read()), dtype=np.uint8)
31
- image_bgr = cv2.imdecode(file_bytes, cv2.IMREAD_COLOR)
32
- image_rgb = cv2.cvtColor(image_bgr, cv2.COLOR_BGR2RGB)
33
-
34
- st.image(image_rgb, caption=f"Original Image: {custom_image_name}")
35
- rows, cols = image_rgb.shape[:2]
36
-
37
- st.write("### Apply Transformations")
38
-
39
- # Translation
40
- st.write("#### Translation")
41
- tx = st.slider(f"Translate X (pixels) - {custom_image_name}", -cols, cols, 0, key=f"tx_{idx}")
42
- ty = st.slider(f"Translate Y (pixels) - {custom_image_name}", -rows, rows, 0, key=f"ty_{idx}")
43
- translated_img, _ = apply_transformation(image_bgr, "Translation", tx=tx, ty=ty)
44
- st.image(translated_img, caption=f"Translated (tx={tx}, ty={ty})")
45
-
46
- # Rotation
47
- st.write("#### Rotation")
48
- angle = st.slider(f"Rotation Angle (degrees) - {custom_image_name}", -180, 180, 0, key=f"angle_{idx}")
49
- rotated_img, _ = apply_transformation(image_bgr, "Rotation", angle=angle)
50
- st.image(rotated_img, caption=f"Rotated (angle={angle}°)")
51
-
52
- # Scaling
53
- st.write("#### Scaling")
54
- scale_x = st.slider(f"Scale Factor X - {custom_image_name}", 0.1, 3.0, 1.0, 0.1, key=f"scale_x_{idx}")
55
- scale_y = st.slider(f"Scale Factor Y - {custom_image_name}", 0.1, 3.0, 1.0, 0.1, key=f"scale_y_{idx}")
56
- scaled_img, _ = apply_transformation(image_bgr, "Scaling", fx=scale_x, fy=scale_y)
57
- st.image(scaled_img, caption=f"Scaled (scale_x={scale_x}, scale_y={scale_y})")
58
-
59
- # Shearing
60
- st.write("#### Shearing")
61
- shear_x = st.slider(f"Shear X - {custom_image_name}", -1.0, 1.0, 0.0, 0.1, key=f"shear_x_{idx}")
62
- shear_y = st.slider(f"Shear Y - {custom_image_name}", -1.0, 1.0, 0.0, 0.1, key=f"shear_y_{idx}")
63
- sheared_img, _ = apply_transformation(image_bgr, "Shearing", shx=shear_x, shy=shear_y)
64
- st.image(sheared_img, caption=f"Sheared (shear_x={shear_x}, shear_y={shear_y})")
65
-
66
- # Cropping
67
- st.write("#### Cropping")
68
- x_start = st.slider(f"Crop Start X - {custom_image_name}", 0, cols - 1, 0, key=f"x_start_{idx}")
69
- x_end = st.slider(f"Crop End X - {custom_image_name}", 1, cols, cols, key=f"x_end_{idx}")
70
- y_start = st.slider(f"Crop Start Y - {custom_image_name}", 0, rows - 1, 0, key=f"y_start_{idx}")
71
- y_end = st.slider(f"Crop End Y - {custom_image_name}", 1, rows, rows, key=f"y_end_{idx}")
72
- cropped_img, _ = apply_transformation(image_bgr, "Cropping", x_start=x_start, x_end=x_end, y_start=y_start, y_end=y_end)
73
- st.image(cropped_img, caption=f"Cropped (x=({x_start}, {x_end}), y=({y_start}, {y_end}))")
74
-
75
- # Add current image's transformations to the DataFrame
76
- if st.button(f"Add All Transformations to DataFrame - {custom_image_name}"):
77
- transformations = {
78
- "Translation": translated_img,
79
- "Rotation": rotated_img,
80
- "Scaling": scaled_img,
81
- "Shearing": sheared_img,
82
- "Cropping": cropped_img,
83
- }
84
- for name, img in transformations.items():
85
- add_to_dataframe(custom_image_name, img, name)
86
- st.success(f"Transformations for {custom_image_name} have been added to the DataFrame.")
87
-
88
- # Display cumulative DataFrame
89
- if not st.session_state.combined_data.empty:
90
- st.write("## Cumulative Transformation DataFrame")
91
- st.dataframe(st.session_state.combined_data)
92
-
93
- # Download button for DataFrame
94
- csv_data = st.session_state.combined_data.to_csv(index=False).encode("utf-8")
95
- st.download_button(
96
- label="Download DataFrame as CSV",
97
- data=csv_data,
98
- file_name="transformed_images.csv",
99
- mime="text/csv",
100
- )
101
-
102
-
103
- def apply_transformation(image, transform_name, **kwargs):
104
- """Applies a transformation and returns the transformed image and description."""
105
- rows, cols = image.shape[:2]
106
-
107
- if transform_name == "Translation":
108
- tx, ty = kwargs["tx"], kwargs["ty"]
109
- matrix = np.float32([[1, 0, tx], [0, 1, ty]])
110
- transformed_image = cv2.warpAffine(image, matrix, (cols, rows))
111
- return cv2.cvtColor(transformed_image, cv2.COLOR_BGR2RGB), f"tx={tx}, ty={ty}"
112
-
113
- elif transform_name == "Rotation":
114
- angle = kwargs["angle"]
115
- center = (cols // 2, rows // 2)
116
- matrix = cv2.getRotationMatrix2D(center, angle, 1)
117
- transformed_image = cv2.warpAffine(image, matrix, (cols, rows))
118
- return cv2.cvtColor(transformed_image, cv2.COLOR_BGR2RGB), f"angle={angle}°"
119
-
120
- elif transform_name == "Scaling":
121
- fx, fy = kwargs["fx"], kwargs["fy"]
122
- transformed_image = cv2.resize(image, None, fx=fx, fy=fy)
123
- return cv2.cvtColor(transformed_image, cv2.COLOR_BGR2RGB), f"scale_x={fx}, scale_y={fy}"
124
-
125
- elif transform_name == "Shearing":
126
- shx, shy = kwargs["shx"], kwargs["shy"]
127
- matrix = np.float32([[1, shx, 0], [shy, 1, 0]])
128
- transformed_image = cv2.warpAffine(image, matrix, (cols, rows))
129
- return cv2.cvtColor(transformed_image, cv2.COLOR_BGR2RGB), f"shear_x={shx}, shear_y={shy}"
130
-
131
- elif transform_name == "Cropping":
132
- x_start, x_end, y_start, y_end = kwargs["x_start"], kwargs["x_end"], kwargs["y_start"], kwargs["y_end"]
133
- cropped_image = image[y_start:y_end, x_start:x_end]
134
- return cv2.cvtColor(cropped_image, cv2.COLOR_BGR2RGB), f"x=({x_start}, {x_end}), y=({y_start}, {y_end})"
135
-
136
-
137
- def add_to_dataframe(image_name, image, transform_name):
138
- """Updates the cumulative DataFrame with a transformed image's details."""
139
- resized_image = cv2.resize(image, (100, 100)) # Resize for uniformity
140
- flattened_data = resized_image.flatten()
141
- new_row = pd.DataFrame([[image_name, transform_name] + flattened_data.tolist()],
142
- columns=["Image Name", "Transformation"] + [f"Pixel {i}" for i in range(flattened_data.size)])
143
- st.session_state.combined_data = pd.concat([st.session_state.combined_data, new_row], ignore_index=True)
144
-
145
-
146
- if __name__ == "__main__":
147
- main()
 
1
  import streamlit as st
 
2
  import pandas as pd
3
  import numpy as np
4
+ import matplotlib.pyplot as plt
5
+ import seaborn as sns
6
+ from scipy import stats
7
+
8
+ st.set_page_config(page_title="EDA Tool")
9
+
10
+ st.title("Exploratory Data Analysis (EDA) Tool")
11
+
12
+ # File uploader
13
+ uploaded_file = st.file_uploader("Upload a CSV or Excel file", type=["csv", "xlsx"])
14
+
15
+ if uploaded_file:
16
+ # Load dataset
17
+ file_extension = uploaded_file.name.split(".")[-1]
18
+ if file_extension == "csv":
19
+ df = pd.read_csv(uploaded_file)
20
+ else:
21
+ df = pd.read_excel(uploaded_file)
22
+
23
+ st.write("### Preview of the Dataset")
24
+ st.write(df.head())
25
+
26
+ # Dataset Information
27
+ st.write("### Dataset Info")
28
+ st.write(f"Rows: {df.shape[0]}, Columns: {df.shape[1]}")
29
+
30
+ st.write("### Data Types")
31
+ st.write(df.dtypes)
32
+
33
+ st.write("### Missing Values")
34
+ st.write(df.isnull().sum())
35
+
36
+ # Summary Statistics
37
+ st.write("### Summary Statistics")
38
+ st.write(df.describe())
39
+
40
+ # Correlation Heatmap
41
+ st.write("### Correlation Heatmap")
42
+ fig, ax = plt.subplots(figsize=(10, 6))
43
+ sns.heatmap(df.corr(), annot=True, cmap="coolwarm", fmt=".2f", linewidths=0.5)
44
+ st.pyplot(fig)
45
+
46
+ # Pairplot
47
+ st.write("### Pairplot")
48
+ if len(df.columns) <= 5: # Avoid plotting for too many columns
49
+ fig = sns.pairplot(df)
50
+ st.pyplot(fig)
51
+ else:
52
+ st.write("Too many columns for pairplot, showing only first 5 numerical columns.")
53
+ fig = sns.pairplot(df.iloc[:, :5])
54
+ st.pyplot(fig)
55
+
56
+ # Univariate Analysis
57
+ st.write("### Univariate Analysis")
58
+ for column in df.select_dtypes(include=[np.number]).columns:
59
+ st.write(f"#### {column}")
60
+ fig, ax = plt.subplots()
61
+ sns.histplot(df[column].dropna(), kde=True, bins=30, ax=ax)
62
+ st.pyplot(fig)
63
+ fig, ax = plt.subplots()
64
+ sns.boxplot(x=df[column], ax=ax)
65
+ st.pyplot(fig)
66
+
67
+ # Bivariate Analysis
68
+ st.write("### Bivariate Analysis")
69
+ numeric_cols = df.select_dtypes(include=[np.number]).columns.tolist()
70
+ if len(numeric_cols) >= 2:
71
+ col1, col2 = st.selectbox("Select two columns for scatter plot", numeric_cols, index=[0, 1])
72
+ fig, ax = plt.subplots()
73
+ sns.scatterplot(x=df[col1], y=df[col2], ax=ax)
74
+ st.pyplot(fig)
75
+
76
+ # Regression Plot
77
+ fig, ax = plt.subplots()
78
+ sns.regplot(x=df[col1], y=df[col2], ax=ax)
79
+ st.pyplot(fig)
80
+
81
+ # Correlation
82
+ correlation = df[col1].corr(df[col2])
83
+ st.write(f"Correlation between {col1} and {col2}: {correlation:.4f}")
84
+
85
+ # Statistical Tests
86
+ st.write("### Statistical Tests")
87
+ if len(numeric_cols) >= 2:
88
+ col1, col2 = st.selectbox("Select two columns for t-test", numeric_cols, index=[0, 1])
89
+ t_stat, p_value = stats.ttest_ind(df[col1].dropna(), df[col2].dropna())
90
+ st.write(f"T-Test between {col1} and {col2}: T-Statistic = {t_stat:.4f}, P-Value = {p_value:.4f}")
91
+
92
+ # Outliers Detection
93
+ st.write("### Outliers Detection")
94
+ selected_col = st.selectbox("Select a column for outlier detection", numeric_cols)
95
+ Q1 = df[selected_col].quantile(0.25)
96
+ Q3 = df[selected_col].quantile(0.75)
97
+ IQR = Q3 - Q1
98
+ outliers = df[(df[selected_col] < (Q1 - 1.5 * IQR)) | (df[selected_col] > (Q3 + 1.5 * IQR))]
99
+ st.write(f"Number of outliers in {selected_col}: {outliers.shape[0]}")
100
+ st.write(outliers)
101
+
102
+ st.write("### EDA Complete")