-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathImageEditor.py
260 lines (218 loc) · 11.6 KB
/
ImageEditor.py
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
from flask import Flask, render_template, request, redirect, url_for, send_file, flash
from PIL import Image, ImageFilter
from io import BytesIO
import base64
import os
import cv2
import numpy as np
import pytesseract
import tempfile
app = Flask(__name__,static_folder='data')
# stack to store edit image
undostack = []
redostack = []
#---------------------------------------------------------------Editor function---------------------------------------------------------
def detect_faces(main_image):
'''Function check in the image face is present or not if face in there the make a rectangle box on the face
Parameters:
- main_image: a image use for operaton
'''
img = cv2.cvtColor(np.array(main_image), cv2.COLOR_RGB2BGR) # Convert PIL Image to OpenCV format
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml')
faces = face_cascade.detectMultiScale(gray, scaleFactor=1.3, minNeighbors=5)
for (x, y, w, h) in faces:
cv2.rectangle(img, (x, y), (x + w, y + h), (255, 0, 0), 2)
pil_image = Image.fromarray(cv2.cvtColor(img, cv2.COLOR_BGR2RGB)) # Convert back to PIL Image
return pil_image
def extract_text_from_image(image_data):
'''Function use to extrect text from the image if text in there using pytesseract module
Parameters:
- image_data: a image use for operaton
Return:
- text present on the image.
'''
try:
image = Image.open(BytesIO(image_data))
text = pytesseract.image_to_string(image)
return text
except Exception as e:
return str(e)
#--------------------------------------------------------------------------------ROUTE-----------------------------------------------------------------------------------
@app.route('/', methods=['GET', 'POST'])
def portal():
'''Main route which take image and store in a undostack'''
# Here I make a clear undo and redo list clear for each new img
undostack.clear()
redostack.clear()
try:
if 'file' in request.files:
file = request.files['file']
if file.filename == '':
return redirect(request.url)
# Convert file to image
image_data = Image.open(BytesIO(file.read()))
undostack.append(image_data)
return redirect(url_for('editor'))
except Exception as e:
print(e)
return render_template('image_inpu.html')
# Route for the console page
@app.route('/editor', methods=['GET', 'POST'])
def editor():
try:
blur_amount=0
unducount='0'
reducount='0'
total=0
messages=''
if len(undostack) > 0:
image_data = undostack[-1] # Get the last uploaded image from the stack
img_io = BytesIO() # create a instance of BytesIO class
image_data.save(img_io, format='JPEG') # Save the image in JPEG format
img_io.seek(0) # Move the cursor to the beginning of the BytesIO object
image_data = base64.b64encode(img_io.getvalue()).decode('utf-8') # Encode the image data in base64 format and decode it to a UTF-8 string
if request.method == 'POST':
effect = request.form['effect']
# print(effect)
main_image = Image.open(BytesIO(base64.b64decode(image_data))) # decode the image from base64 image data
if effect == 'rotate':
"""
Rotate the image using the PIL module's rotate function.
Parameters:
- rotate_angle: The angle (in degrees) by which to rotate the image.
Returns:
- The rotated image is appended to the undo stack.
"""
rotate_angle = int(request.form['rotate'])
image = main_image.rotate(rotate_angle)
undostack.append(image) # store edited img in undostack
elif effect == 'crop':
"""
Crop the image using the PIL module's crop function, taking x and y coordinates as parameters.
Parameters:
- crop_size: The size of the crop box.
- x: The x-coordinate for cropping.
- y: The y-coordinate for cropping.
Returns:
- The cropped image is appended to the undo stack.
"""
crop_size = int(request.form['crop_size'])
x0, y0 = main_image.size
x=int(request.form['x'])
y=int(request.form['y'])
# Calculate the crop box to maintain center crop
if x0>=x and y0>=y:
crop_left = x
crop_upper = y
crop_right = x + crop_size
crop_lower = y + crop_size
# Crop the image
image = main_image.crop((crop_left, crop_upper, crop_right, crop_lower))
# store edited img in undostack
undostack.append(image)
elif effect=='blur':
'''Apply BoxBlur filter to the image with given bule amount
Parameters:
- blur: The amount of blur to apply (0-99)
Return:
- The blurred image is appended to the undo stack'''
blur_amount = int(request.form['blur'])
blur_amount=blur_amount%100
image = main_image.filter(ImageFilter.BoxBlur(blur_amount))
# undustack append
undostack.append(image)
elif effect == 'filter':
"""
Apply a selected filter from a predefined list of filters to the main image.
Parameters:
- effect_option: The name of the filter selected by the user.
Returns:
- The filtered image is appended to the undo stack.
"""
filter_name = request.form.get('effect_option')
# print(filter_name)
lst=["BLUR", "CONTOUR", "DETAIL", "EDGE_ENHANCE", "EDGE_ENHANCE_MORE","EMBOSS", "FIND_EDGES", "SMOOTH", "SMOOTH_MORE", "SHARPEN"]
lst_filter = [ImageFilter.BLUR, ImageFilter.CONTOUR, ImageFilter.DETAIL, ImageFilter.EDGE_ENHANCE,
ImageFilter.EDGE_ENHANCE_MORE, ImageFilter.EMBOSS, ImageFilter.FIND_EDGES, ImageFilter.SMOOTH, ImageFilter.SMOOTH_MORE, ImageFilter.SHARPEN]
# image = main_image
if filter_name in lst:
# Applying the blur filter
filter_obj = lst_filter[lst.index(filter_name)] # Get the ImageFilter object
image = main_image.filter(filter_obj)
# undustack append
undostack.append(image)
elif effect == 'detect_faces':
"""
Detect faces in the main image using a face detection algorithm
"""
image = detect_faces(main_image)
# undustack append
undostack.append(image)
elif effect == 'extract_text':
"""Extract text from an image using OCR (Optical Character Recognition)"""
text = extract_text_from_image(base64.b64decode(image_data))
flash("Extracted Text: " + text)
elif effect == 'undu':
"""If image in undostack than it pop and append in redostack"""
if len(undostack) > 0:
image = undostack.pop()
redostack.append(image)
print('redu', len(redostack))
elif effect == 'redu' and len(redostack) > 0:
"""If image in redostack than it pop and append in undostack"""
image = redostack.pop()
undostack.append(image)
print('undu', len(undostack))
elif effect == 'reset':
image = undostack[0]
undostack.clear()
redostack.clear()
undostack.append(image)
if image is not None:
# Another stuff
edited_io = BytesIO()
image.save(edited_io, format='JPEG')
edited_io.seek(0)
image_data = base64.b64encode(edited_io.getvalue()).decode('utf-8')
# length of list
unducount=len(undostack)
reducount=len(redostack)
total=unducount+reducount
return render_template('image_editor.html', image_data=image_data,blur_amount=blur_amount,unducount=unducount,total=total,messages=messages)
else:
# Here I make a clear undo and redo list clear for each new img
undostack.clear()
redostack.clear()
return render_template('image_inpu.html')
except:
return render_template('image_editor.html',image_data=image_data,unducount=unducount,total=total)
# dawonload
@app.route('/download')
def download():
"""
Try to download the last edited image from the undo stack. If no edited image is available, redirect to the portal
"""
try:
if len(undostack) > 0:
# Get the last edited image from the stack
edited_image = undostack[-1]
# Save the edited image to a temporary file
temp_file = tempfile.NamedTemporaryFile(delete=False, suffix='.jpg')
edited_image.save(temp_file.name, format='JPEG')
# Serve the temporary file for download
return send_file(temp_file.name, as_attachment=True)
else:
# If no edited image is available, redirect to the portal
return redirect(url_for('portal'))
except Exception as e:
return render_template('image_editor.html')
if __name__ == '__main__':
app.run(debug=True)
# Create a Flask WebApp where users can upload an image and apply various filters to transform the uploaded image, which should be displayed on the website. No need for storing the uploading images.
# - Host this website on www.render.com [free tier of 3 months]. Do not enter your bank information anywhere.
# - Create a detailed PDF report of the algorithm used and show output for a few test cases.
# - You can do this assignment either individually or in groups of 2. In case of a group, each student's contribution should be clearly mentioned in the PDF report and also on the website.
# 10 marks : Functional website with basic filters for cropping, rotating and blurring
# 5 marks : Novelty in the choice and implementation of filters
# 5 marks : Quality and overall visual appeal of frontend UI/UX