Phaneendrabayi commited on
Commit
683da96
·
verified ·
1 Parent(s): 78f7d0b

Create The_Image_Agumentation.py

Browse files
Files changed (1) hide show
  1. pages/The_Image_Agumentation.py +147 -0
pages/The_Image_Agumentation.py ADDED
@@ -0,0 +1,147 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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")
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()