codewithdark commited on
Commit
48582da
·
verified ·
1 Parent(s): 7e0c748

Upload app.py

Browse files
Files changed (1) hide show
  1. app.py +245 -0
app.py ADDED
@@ -0,0 +1,245 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ from rembg import remove
3
+ from PIL import Image
4
+ from io import BytesIO
5
+ import numpy as np
6
+ import base64
7
+ import random
8
+ import cv2
9
+ import requests
10
+ from bs4 import BeautifulSoup
11
+
12
+ st.set_page_config(page_title="ImageMagic - Your Image Processing Companion")
13
+
14
+ MAX_FILE_SIZE = 5 * 1024 * 1024
15
+
16
+
17
+ # Function to remove background using rembg library
18
+ def remove_background(image):
19
+ return remove(image)
20
+
21
+ # Function to convert image to pencil sketch
22
+ def convert_to_pencil_sketch(image):
23
+ gray_img = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
24
+ invert = cv2.bitwise_not(gray_img)
25
+ blur = cv2.GaussianBlur(invert, (111, 111), 0)
26
+ invertedblur = cv2.bitwise_not(blur)
27
+ sketch = cv2.divide(gray_img, invertedblur, scale=256.0)
28
+ sketch_image = Image.fromarray(sketch)
29
+ return sketch_image
30
+
31
+ # Function to convert image to byte format for download
32
+ def convert_image(img):
33
+ buf = BytesIO()
34
+ img.save(buf, format="PNG")
35
+ byte_im = buf.getvalue()
36
+ return byte_im
37
+
38
+ # Function to process uploaded image based on selected action
39
+ def process_image(upload, action):
40
+ image = Image.open(upload)
41
+
42
+ coli = st.columns(5)
43
+ with coli[0]:
44
+ st.image(image, caption="Original Image", width=300)
45
+ with coli[3]:
46
+ if action == "Remove Background":
47
+ result = remove_background(image)
48
+ st.image(result, caption="Background Removed", width=300)
49
+
50
+ elif action == "Convert to Pencil Sketch":
51
+ result = convert_to_pencil_sketch(cv2.cvtColor(np.array(image), cv2.COLOR_RGB2BGR))
52
+ st.image(result, caption="Pencil Sketch", width=200)
53
+
54
+
55
+ st.markdown(get_image_download_link(result), unsafe_allow_html=True)
56
+
57
+ # Function to generate download link for processed image
58
+
59
+ def get_image_download_link(img, filename="result.png"):
60
+ """
61
+ Generates a download link for the given image.
62
+
63
+ Parameters:
64
+ img (PIL.Image.Image): The image to be downloaded.
65
+ filename (str): The filename to be used when downloading the image.
66
+
67
+ Returns:
68
+ str: The HTML string representing the download link.
69
+ """
70
+ buffered = BytesIO()
71
+ img.save(buffered, format="PNG")
72
+ img_str = base64.b64encode(buffered.getvalue()).decode()
73
+ href = f'<a href="data:image/png;base64,{img_str}" download="{filename}">Download Image</a>'
74
+ return href
75
+
76
+
77
+ def search_unsplash_images(query):
78
+ try:
79
+ # Send a request to Unsplash with the search query
80
+ url = f"https://unsplash.com/s/photos/{query}"
81
+ response = requests.get(url)
82
+ response.raise_for_status() # Raise an exception for bad status codes
83
+
84
+ # Parse the HTML content
85
+ soup = BeautifulSoup(response.text, 'html.parser')
86
+
87
+ # Extract image URLs from the parsed HTML
88
+ image_urls = [img['src'] for img in soup.find_all('img') if img.get('src')]
89
+ image_urls = image_urls[:40]
90
+ random.shuffle(image_urls)
91
+ # Display the images in columns with three images per column
92
+ num_columns = 3
93
+ images_per_column = len(image_urls) // num_columns
94
+ for i in range(num_columns):
95
+ col = st.columns(num_columns)
96
+ start_index = i * images_per_column
97
+ end_index = (i + 1) * images_per_column
98
+ for j, image_url in enumerate(image_urls[start_index:end_index], start=start_index):
99
+
100
+ # Download the image
101
+ image_data = requests.get(image_url).content
102
+ image = Image.open(BytesIO(image_data))
103
+
104
+ # Display the image
105
+ col[j % num_columns].image(image, use_column_width=True)
106
+
107
+
108
+ except requests.exceptions.RequestException as e:
109
+ st.warning(f"Image Not Show Try Again ")
110
+
111
+ # App description
112
+ st.title("🎉Welcome to ImageMagic")
113
+ st.write("""
114
+ ✨ImageMagic is a versatile image processing application🚀 that simplifies common image editing tasks.
115
+ Upload an image and choose from the available options to enhance your images effortlessly⚡!
116
+ """)
117
+
118
+ # Sidebar for options
119
+ st.sidebar.title("Options")
120
+ selected_option = st.sidebar.radio("Select an option", ("Home", "Remove Background", "Convert to Pencil Sketch", "Search image", "README.md"))
121
+
122
+ # Display README content within the Options section
123
+ if selected_option == "README.md":
124
+ st.title("README")
125
+ readme_content = """
126
+ # ImageMagic
127
+
128
+ ## Overview
129
+
130
+ ImageMagic is a powerful image processing application that allows users to enhance their images with ease. Whether you want to remove backgrounds or create stunning pencil sketches, ImageMagic has you covered. This app offers a simple and intuitive interface, making it accessible to users of all skill levels.
131
+
132
+ ## Features
133
+
134
+ - **Background Removal:** Effortlessly remove backgrounds from images to isolate subjects and create stunning compositions.
135
+ - **Pencil Sketch Conversion:** Transform your images into beautiful pencil sketches with just a click of a button.
136
+ - **Upload and Download:** Easily upload your images for processing and download the results to your device.
137
+
138
+ ## Usage
139
+
140
+ 1. **Upload Image:** Select an image file (supported formats include PNG, JPG, and JPEG) by clicking on the "Upload an image" button.
141
+ 2. **Select Action:** Choose from the available options in the sidebar to either remove the background or convert the image to a pencil sketch.
142
+ 3. **View Results:** The processed image will be displayed in the main window, allowing you to preview the changes.
143
+ 4. **Download:** Once you're satisfied with the result, you can download the processed image by clicking on the "Download Result" link.
144
+
145
+ ## Installation
146
+
147
+ To run ImageMagic locally, follow these steps:
148
+
149
+ 1. Clone this repository to your local machine:
150
+
151
+ ```
152
+ git clone https://github.com/codewithdark-git/ImageMagic.git
153
+ ```
154
+
155
+ 2. Navigate to the project directory:
156
+
157
+ ```
158
+ cd ImageMagic
159
+ ```
160
+
161
+ 3. Install the required dependencies:
162
+
163
+ ```
164
+ pip install -r requirements.txt
165
+ ```
166
+
167
+ 4. Run the Streamlit app:
168
+
169
+ ```
170
+ streamlit run app.py
171
+ ```
172
+
173
+ 5. Access the app in your web browser at `http://localhost:8501`.
174
+
175
+ ## Credits
176
+
177
+ - This app utilizes the [rembg](https://github.com/danielgatis/rembg) library for background removal.
178
+ - Built with [Streamlit](https://streamlit.io/).
179
+
180
+ ## License
181
+
182
+ This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.
183
+ """
184
+ st.markdown(readme_content)
185
+
186
+ elif selected_option == "Home":
187
+ st.subheader("Home")
188
+ st.write("## Welcome to Image Processing App")
189
+ st.write("This app allows you to perform various image processing tasks such as background removal and converting images to pencil sketches.")
190
+
191
+ # Introduction to Background Removal
192
+ st.write("### Background Removal")
193
+ st.write("With the background removal feature, you can easily separate the main object from its background.")
194
+ st.write("Here's an example of an original image and its background removed version:")
195
+
196
+ # Display original image and background removed image
197
+ st.write("### Original Image and Background Removed")
198
+ st.write('<div style="display: flex;">', unsafe_allow_html=True)
199
+ with st.container():
200
+ st.image("Background_remove.png", caption="Original Image", width=600)
201
+ st.write('</div>', unsafe_allow_html=True)
202
+
203
+ # Introduction to Pencil Sketch Conversion
204
+ st.write("### Pencil Sketch Conversion")
205
+ st.write("The app also provides an option to convert images into pencil sketches using OpenCV.")
206
+ st.write("Here's an example of an original image and its corresponding pencil sketch:")
207
+
208
+ # Display original image and pencil sketch image
209
+ st.write("### Original Image and Pencil Sketch")
210
+ st.write('<div style="display: flex;">', unsafe_allow_html=True)
211
+ with st.container():
212
+ st.image("pencil_sketch.png", caption="Original Image", width=600)
213
+ st.write('</div>', unsafe_allow_html=True)
214
+
215
+ # Summarize the App
216
+ st.write("### Summary")
217
+ st.write("This app offers a simple yet powerful interface for performing common image processing tasks.")
218
+ st.write("Explore the various functionalities and unleash your creativity!")
219
+
220
+ # Footer with Author Information
221
+ st.write("---")
222
+ st.write("### About the Author")
223
+ st.write("This app was created by [Your Name].")
224
+ st.write("For more projects and contact information, visit:")
225
+ st.write("[GitHub](https://github.com/codewithdark-git) | [LinkedIn](https://www.linkedin.com/in/codewithdark)")
226
+
227
+ elif selected_option == "Search image":
228
+ st.title("") # No title for the search image section
229
+
230
+ search_query = st.text_input("Enter search query:")
231
+ if st.button("Search"):
232
+ if search_query:
233
+ search_unsplash_images(search_query)
234
+ else:
235
+ st.warning("Please enter a search query.")
236
+
237
+
238
+ else:
239
+ # Process uploaded image
240
+ my_upload = st.file_uploader("Upload an image", type=["png", "jpg", "jpeg"])
241
+ if my_upload is not None:
242
+ if my_upload.size > MAX_FILE_SIZE:
243
+ st.error("The uploaded file is too large. Please upload an image smaller than 5MB.")
244
+ else:
245
+ process_image(upload=my_upload, action=selected_option)