Phaneendrabayi commited on
Commit
a53d4c0
·
verified ·
1 Parent(s): 222392e

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +122 -94
app.py CHANGED
@@ -5,108 +5,136 @@ import numpy as np
5
 
6
 
7
  def main():
8
- st.title("Interactive Image Processing with Affine Transformations")
9
- st.write("Upload an image and apply affine transformations interactively using buttons.")
10
 
11
- # Upload image
 
 
 
 
 
 
 
 
 
 
12
  uploaded_file = st.file_uploader("Upload an image (JPG, PNG)", type=["jpg", "jpeg", "png"])
13
 
14
  if uploaded_file:
 
15
  file_bytes = np.asarray(bytearray(uploaded_file.read()), dtype=np.uint8)
16
  image = cv2.imdecode(file_bytes, cv2.IMREAD_COLOR)
17
 
18
- if image is not None:
19
- st.image(image, caption="Original Image", channels="BGR")
20
-
21
- rows, cols = image.shape[:2]
22
- image_data_list = []
23
-
24
- # Define transformation functions
25
- def apply_translation():
26
- tx, ty = 50, 50
27
- matrix = np.float32([[1, 0, tx], [0, 1, ty]])
28
- return cv2.warpAffine(image, matrix, (cols, rows))
29
-
30
- def apply_rotation():
31
- angle = 45
32
- center = (cols // 2, rows // 2)
33
- matrix = cv2.getRotationMatrix2D(center, angle, 1)
34
- return cv2.warpAffine(image, matrix, (cols, rows))
35
-
36
- def apply_scaling():
37
- scale_factor = 1.5
38
- return cv2.resize(image, (int(cols * scale_factor), int(rows * scale_factor)))
39
-
40
- def apply_shearing():
41
- shear_factor = 0.2
42
- matrix = np.float32([[1, shear_factor, 0], [shear_factor, 1, 0]])
43
- return cv2.warpAffine(image, matrix, (cols, rows))
44
-
45
- def apply_cropping():
46
- x_start, x_end = cols // 4, 3 * cols // 4
47
- y_start, y_end = rows // 4, 3 * rows // 4
48
- return image[y_start:y_end, x_start:x_end]
49
-
50
- # Add buttons for each transformation
51
- if st.button("Apply Translation"):
52
- transformed_image = apply_translation()
53
- display_transformed_image("Translated", transformed_image, image_data_list)
54
-
55
- if st.button("Apply Rotation"):
56
- transformed_image = apply_rotation()
57
- display_transformed_image("Rotated", transformed_image, image_data_list)
58
-
59
- if st.button("Apply Scaling"):
60
- transformed_image = apply_scaling()
61
- display_transformed_image("Scaled", transformed_image, image_data_list)
62
-
63
- if st.button("Apply Shearing"):
64
- transformed_image = apply_shearing()
65
- display_transformed_image("Sheared", transformed_image, image_data_list)
66
-
67
- if st.button("Apply Cropping"):
68
- transformed_image = apply_cropping()
69
- display_transformed_image("Cropped", transformed_image, image_data_list)
70
-
71
- # Display combined DataFrame for all transformations
72
- if image_data_list:
73
- combined_data = pd.concat(image_data_list, ignore_index=True)
74
- st.write("### Combined Tabular Data from All Transformations")
75
- st.dataframe(combined_data)
76
-
77
- # Allow downloading the data as a CSV
78
- csv_data = combined_data.to_csv(index=False).encode('utf-8')
79
- st.download_button(
80
- label="Download Transformed Data as CSV",
81
- data=csv_data,
82
- file_name="transformed_image_data.csv",
83
- mime="text/csv",
84
- )
85
-
86
-
87
- def display_transformed_image(transform_name, transformed_image, image_data_list):
88
- """Display the transformed image and add tabular data."""
89
- st.write(f"### {transform_name} Image")
90
-
91
- # Resize for consistency in processing
92
- resized_image = cv2.resize(transformed_image, (100, 100))
93
-
94
- # Check if the image is grayscale or color
95
- if len(resized_image.shape) == 2: # Grayscale
96
- flattened_image = resized_image.flatten()
97
- st.image(resized_image, caption=f"{transform_name} Image (Grayscale)")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
98
  else: # Color
99
- flattened_image = resized_image.flatten()
100
- st.image(resized_image, caption=f"{transform_name} Image (Color)", channels="BGR")
101
-
102
- # Create a DataFrame for flattened data
103
- image_data = pd.DataFrame(flattened_image.reshape(1, -1))
104
- image_data['Transformation'] = transform_name
105
- st.write(f"Tabular Data for {transform_name} Transformation")
106
- st.dataframe(image_data)
107
-
108
- # Append to the main data list
109
- image_data_list.append(image_data)
110
 
111
 
112
  if __name__ == "__main__":
 
5
 
6
 
7
  def main():
8
+ st.set_page_config(page_title="Interactive Affine Transformations", layout="wide")
 
9
 
10
+ st.title("Interactive Image Processing with Custom Affine Transformations")
11
+ st.write("Upload an image and apply transformations interactively using user-defined parameters.")
12
+
13
+ # Sidebar for parameters
14
+ st.sidebar.header("Transformation Parameters")
15
+
16
+ # Persistent storage for cumulative DataFrame
17
+ if "combined_data" not in st.session_state:
18
+ st.session_state.combined_data = pd.DataFrame()
19
+
20
+ # File uploader for the image
21
  uploaded_file = st.file_uploader("Upload an image (JPG, PNG)", type=["jpg", "jpeg", "png"])
22
 
23
  if uploaded_file:
24
+ # Load and display original image
25
  file_bytes = np.asarray(bytearray(uploaded_file.read()), dtype=np.uint8)
26
  image = cv2.imdecode(file_bytes, cv2.IMREAD_COLOR)
27
 
28
+ st.image(image, caption="Original Image", channels="BGR")
29
+ rows, cols = image.shape[:2]
30
+
31
+ # Collect user inputs for transformations
32
+ transform_option = st.sidebar.radio(
33
+ "Select a transformation type:",
34
+ ("Translation", "Rotation", "Scaling", "Shearing", "Cropping")
35
+ )
36
+
37
+ if transform_option == "Translation":
38
+ tx = st.sidebar.slider("Translate X (pixels)", -100, 100, 0)
39
+ ty = st.sidebar.slider("Translate Y (pixels)", -100, 100, 0)
40
+ if st.sidebar.button("Apply Translation"):
41
+ apply_transformation(image, transform_option, tx=tx, ty=ty)
42
+
43
+ elif transform_option == "Rotation":
44
+ angle = st.sidebar.slider("Rotation Angle (degrees)", -180, 180, 0)
45
+ if st.sidebar.button("Apply Rotation"):
46
+ apply_transformation(image, transform_option, angle=angle)
47
+
48
+ elif transform_option == "Scaling":
49
+ scale_factor = st.sidebar.slider("Scale Factor", 0.1, 3.0, 1.0, 0.1)
50
+ if st.sidebar.button("Apply Scaling"):
51
+ apply_transformation(image, transform_option, scale=scale_factor)
52
+
53
+ elif transform_option == "Shearing":
54
+ shear_x = st.sidebar.slider("Shear X", -1.0, 1.0, 0.0, 0.1)
55
+ shear_y = st.sidebar.slider("Shear Y", -1.0, 1.0, 0.0, 0.1)
56
+ if st.sidebar.button("Apply Shearing"):
57
+ apply_transformation(image, transform_option, shear_x=shear_x, shear_y=shear_y)
58
+
59
+ elif transform_option == "Cropping":
60
+ x_start = st.sidebar.slider("Crop Start X", 0, cols, 0)
61
+ x_end = st.sidebar.slider("Crop End X", 0, cols, cols)
62
+ y_start = st.sidebar.slider("Crop Start Y", 0, rows, 0)
63
+ y_end = st.sidebar.slider("Crop End Y", 0, rows, rows)
64
+ if st.sidebar.button("Apply Cropping"):
65
+ apply_transformation(image, transform_option, x_start=x_start, x_end=x_end, y_start=y_start, y_end=y_end)
66
+
67
+ # Display cumulative DataFrame
68
+ if not st.session_state.combined_data.empty:
69
+ st.write("### Cumulative Tabular Data from All Transformations")
70
+ st.dataframe(st.session_state.combined_data)
71
+
72
+ # Download button for CSV
73
+ csv_data = st.session_state.combined_data.to_csv(index=False).encode("utf-8")
74
+ st.download_button(
75
+ label="Download Tabular Data as CSV",
76
+ data=csv_data,
77
+ file_name="affine_transformations.csv",
78
+ mime="text/csv"
79
+ )
80
+
81
+
82
+ def apply_transformation(image, transform_name, **kwargs):
83
+ """Applies the selected affine transformation and updates the cumulative DataFrame."""
84
+ rows, cols = image.shape[:2]
85
+
86
+ if transform_name == "Translation":
87
+ tx, ty = kwargs["tx"], kwargs["ty"]
88
+ matrix = np.float32([[1, 0, tx], [0, 1, ty]])
89
+ transformed_image = cv2.warpAffine(image, matrix, (cols, rows))
90
+
91
+ elif transform_name == "Rotation":
92
+ angle = kwargs["angle"]
93
+ center = (cols // 2, rows // 2)
94
+ matrix = cv2.getRotationMatrix2D(center, angle, 1)
95
+ transformed_image = cv2.warpAffine(image, matrix, (cols, rows))
96
+
97
+ elif transform_name == "Scaling":
98
+ scale = kwargs["scale"]
99
+ transformed_image = cv2.resize(image, (int(cols * scale), int(rows * scale)))
100
+
101
+ elif transform_name == "Shearing":
102
+ shear_x, shear_y = kwargs["shear_x"], kwargs["shear_y"]
103
+ matrix = np.float32([[1, shear_x, 0], [shear_y, 1, 0]])
104
+ transformed_image = cv2.warpAffine(image, matrix, (cols, rows))
105
+
106
+ elif transform_name == "Cropping":
107
+ x_start, x_end, y_start, y_end = kwargs["x_start"], kwargs["x_end"], kwargs["y_start"], kwargs["y_end"]
108
+ transformed_image = image[y_start:y_end, x_start:x_end]
109
+
110
+ # Process the transformed image
111
+ update_combined_data(transformed_image, transform_name)
112
+ display_transformed_image(transformed_image, transform_name)
113
+
114
+
115
+ def update_combined_data(image, transform_name):
116
+ """Update the cumulative DataFrame with new transformation data."""
117
+ # Resize for uniformity
118
+ resized_image = cv2.resize(image, (100, 100))
119
+
120
+ # Flatten the image
121
+ flattened_data = resized_image.flatten()
122
+
123
+ # Create a new row
124
+ new_row = pd.DataFrame([flattened_data])
125
+ new_row["Transformation"] = transform_name
126
+
127
+ # Append to cumulative data
128
+ st.session_state.combined_data = pd.concat([st.session_state.combined_data, new_row], ignore_index=True)
129
+
130
+
131
+ def display_transformed_image(image, transform_name):
132
+ """Display the transformed image."""
133
+ st.write(f"### {transform_name} Result")
134
+ if len(image.shape) == 2: # Grayscale
135
+ st.image(image, caption=f"{transform_name} Image (Grayscale)")
136
  else: # Color
137
+ st.image(image, caption=f"{transform_name} Image (Color)", channels="BGR")
 
 
 
 
 
 
 
 
 
 
138
 
139
 
140
  if __name__ == "__main__":