-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfile_manager.py
223 lines (180 loc) · 7.53 KB
/
file_manager.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
import os
from tkinter import filedialog, simpledialog
import cv2 as cv
import imageio
import glob
class FileManager:
def __init__(self):
self.file = None
self.batch_files = None # Alternate variable for a list of batch processed files
def get_file(self):
"""
Prompts user to select an image file.
"""
# Valid file types for image files supported by this application
valid_file_types = [
("Image Files", "*.png *.jpeg *.jpg *.gif *.bmp *.tiff"),
("PNG files", "*.png"),
("JPEG files", "*.jpeg"),
("JPEG files", "*.jpg"),
("GIF files", "*.gif"),
("BMP files", "*.bmp"),
("TIFF files", "*.tiff")
]
# Prompts user to select an image file
file_path = filedialog.askopenfilename(
filetypes=valid_file_types)
if file_path:
if file_path.endswith(".gif"):
# Retrieves the first frame from the GIF
cap = cv.VideoCapture(file_path)
ret, first_frame = cap.read()
cap.release()
if ret:
directory, file_name = os.path.split(file_path)
name, ext = os.path.splitext(file_name)
new_file_path = os.path.join(
directory, f'{name}_first_frame.png')
# Prompt confirmation to user to create new image from GIF.
result = simpledialog.messagebox.askokcancel(
"Importing GIF", f"Creating PNG of first frame from select GIF to {new_file_path}")
if not result:
return
cv.imwrite(new_file_path, first_frame)
file_path = new_file_path
else:
print("Error: Could not read first frame from GIF")
self.file = file_path # Update file attribute with path of file selected
def find_file(self, path):
"""
Finds a file based on the path provided.
Parameters:
path (str): The path to the file.
Returns:
None
"""
file_path = path
if file_path:
self.file = file_path
def save_file(self, content):
"""
Saves the file with the edits made to it.
Parameters:
content (numpy.ndarray): The image to be saved.
Returns:
None
"""
if self.file:
# Overwrites existing file with new edits
cv.imwrite(self.file, content)
@staticmethod
def save_as_file(content):
"""
Prompts user to save the file under the desired name and file format.
Parameters:
content (numpy.ndarray): The image to be saved.
Returns:
None
"""
valid_file_types = [
("Image Files", "*.png *.jpeg *.jpg *.gif *.bmp *.tiff"),
("PNG files", "*.png"),
("JPEG files", "*.jpeg"),
("JPEG files", "*.jpg"),
("GIF files", "*.gif"),
("BMP files", "*.bmp"),
("TIFF files", "*.tiff")
]
# Prompts user to save the file under the desired name and file format
file_path = filedialog.asksaveasfilename(
defaultextension=".png", filetypes=valid_file_types)
if file_path:
if file_path.endswith("gif"):
# Opencv cant sasve images as GIF. Imageio is used to save.
imageio.mimsave(file_path, [content])
# Change color values from RBG to BGR
image_rgb = imageio.imread(file_path)
image_bgr = cv.cvtColor(image_rgb, cv.COLOR_RGB2BGR)
# Save the image again with correct colors.
imageio.mimsave(file_path, [image_bgr])
else:
# Saves the file in that destination
cv.imwrite(file_path, content)
def delete_file(self):
"""
Deletes the file from the system.
Returns:
None
"""
if self.file:
try:
os.remove(self.file) # Removes file from system
self.file = None # Clear the file attribute
except OSError:
print(f"Error: {OSError}")
def get_files(self):
"""
Prompts user to select multiple image files.
Returns:
None"""
answer = simpledialog.messagebox.askyesnocancel("Preparing to Select Folder",
"Would you rather select files manually? \n\nNote: A PNG will be created for the first frame of each GIF file.")
if answer is None:
return
gifFile = False
valid_file_types = [
("Image Files", "*.png *.jpeg *.jpg *.gif *.bmp *.tiff"),
("PNG files", "*.png"),
("JPEG files", "*.jpeg"),
("JPEG files", "*.jpg"),
("GIF files", "*.gif"),
("BMP files", "*.bmp"),
("TIFF files", "*.tiff")
]
# Prompt user to select a folder if they choose to not select files manually
if answer is False:
folder_path = filedialog.askdirectory()
if not folder_path:
return # User cancelled folder selection
warning = simpledialog.messagebox.askokcancel("Warning",
"Batch processing is irreversible. Are you sure you want to proceed?")
if warning is False:
return # User decided to cancel the process
file_set = []
for file_type in valid_file_types:
_, file_extension = file_type
file_pattern = os.path.join(folder_path, file_extension)
# Use glob to find files matching the pattern
matching_files = glob.glob(file_pattern)
# Add matching files to the file_set
file_set.extend(matching_files)
elif answer is True:
file_set = filedialog.askopenfilenames(
filetypes=valid_file_types) # Prompt user to select images
if not file_set:
return
warning = simpledialog.messagebox.askokcancel("Warning",
"Batch processing is irreversible. Are you sure you want to proceed?")
if warning is False:
return # User decided to cancel the process
file_set = list(file_set)
for i, file_path in enumerate(file_set):
if file_path.endswith(".gif"):
# Gets the first frame from the gif
cap = cv.VideoCapture(file_path)
ret, first_frame = cap.read()
cap.release()
if ret:
gifFile = True
directory, file_name = os.path.split(file_path)
name, ext = os.path.splitext(file_name)
new_file_path = os.path.join(
directory, f'{name}_first_frame.png')
cv.imwrite(new_file_path, first_frame)
file_set[i] = new_file_path
else:
print("Error: Could not read first frame from GIF")
if gifFile is True:
simpledialog.messagebox.showinfo(
"GIF(s) Detected", "For each GIF file that was processed, another image was created of its first frame.")
self.batch_files = file_set