-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.py
255 lines (207 loc) · 11.6 KB
/
utils.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
from __future__ import print_function
from io import BytesIO
from PIL import Image
import cv2
import matplotlib.pyplot as plt
from PIL import Image
import numpy as np
import os
# import the required libraries
import pickle
import os.path
import io
import shutil
import requests
from mimetypes import MimeTypes
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
from googleapiclient.http import MediaIoBaseDownload, MediaFileUpload
# client.txt okumak için
def read_ccloud_config(config_file):
conf = {}
with open(config_file) as fh:
for line in fh:
line = line.strip()
if len(line) != 0 and line[0] != "#":
parameter, value = line.strip().split('=', 1)
conf[parameter] = value.strip()
return conf
# Pillow Image tipindeki değişkenleri byte'a çevirmek için
def get_bytes_from_image_data(image_data):
byteImgIO = BytesIO()
image_data.save(byteImgIO, "PNG")
byteImgIO.seek(0)
byteImg = byteImgIO.read()
return byteImg
def get_image_data_from_bytes(byteImg):
image_data = Image.open(BytesIO(byteImg))
if image_data.mode != 'RGB':
image_data = image_data.convert('RGB')
return image_data
def box_label(image, box, label='', color=(128, 128, 128), txt_color=(255, 255, 255)):
lw = max(round(sum(image.shape) / 2 * 0.003), 2)
p1, p2 = (int(box[0]), int(box[1])), (int(box[2]), int(box[3]))
cv2.rectangle(image, p1, p2, color, thickness=lw, lineType=cv2.LINE_AA)
if label:
tf = max(lw - 1, 1) # font thickness
w, h = cv2.getTextSize(label, 0, fontScale=lw / 3, thickness=tf)[0] # text width, height
outside = p1[1] - h >= 3
p2 = p1[0] + w, p1[1] - h - 3 if outside else p1[1] + h + 3
cv2.rectangle(image, p1, p2, color, -1, cv2.LINE_AA) # filled
cv2.putText(image,
label, (p1[0], p1[1] - 2 if outside else p1[1] + h + 2),
0,
lw / 3,
txt_color,
thickness=tf,
lineType=2)
def plot_bboxes(image, boxes, labels=[], colors=[], score=True, conf=None):
#Define COCO Labels
if labels == []:
labels = {0: u'__background__', 1: u'person', 2: u'bicycle',3: u'car', 4: u'motorcycle', 5: u'airplane', 6: u'bus', 7: u'train', 8: u'truck', 9: u'boat', 10: u'traffic light', 11: u'fire hydrant', 12: u'stop sign', 13: u'parking meter', 14: u'bench', 15: u'bird', 16: u'cat', 17: u'dog', 18: u'horse', 19: u'sheep', 20: u'cow', 21: u'elephant', 22: u'bear', 23: u'zebra', 24: u'giraffe', 25: u'backpack', 26: u'umbrella', 27: u'handbag', 28: u'tie', 29: u'suitcase', 30: u'frisbee', 31: u'skis', 32: u'snowboard', 33: u'sports ball', 34: u'kite', 35: u'baseball bat', 36: u'baseball glove', 37: u'skateboard', 38: u'surfboard', 39: u'tennis racket', 40: u'bottle', 41: u'wine glass', 42: u'cup', 43: u'fork', 44: u'knife', 45: u'spoon', 46: u'bowl', 47: u'banana', 48: u'apple', 49: u'sandwich', 50: u'orange', 51: u'broccoli', 52: u'carrot', 53: u'hot dog', 54: u'pizza', 55: u'donut', 56: u'cake', 57: u'chair', 58: u'couch', 59: u'potted plant', 60: u'bed', 61: u'dining table', 62: u'toilet', 63: u'tv', 64: u'laptop', 65: u'mouse', 66: u'remote', 67: u'keyboard', 68: u'cell phone', 69: u'microwave', 70: u'oven', 71: u'toaster', 72: u'sink', 73: u'refrigerator', 74: u'book', 75: u'clock', 76: u'vase', 77: u'scissors', 78: u'teddy bear', 79: u'hair drier', 80: u'toothbrush'}
#Define colors
if colors == []:
#colors = [(6, 112, 83), (253, 246, 160), (40, 132, 70), (205, 97, 162), (149, 196, 30), (106, 19, 161), (127, 175, 225), (115, 133, 176), (83, 156, 8), (182, 29, 77), (180, 11, 251), (31, 12, 123), (23, 6, 115), (167, 34, 31), (176, 216, 69), (110, 229, 222), (72, 183, 159), (90, 168, 209), (195, 4, 209), (135, 236, 21), (62, 209, 199), (87, 1, 70), (75, 40, 168), (121, 90, 126), (11, 86, 86), (40, 218, 53), (234, 76, 20), (129, 174, 192), (13, 18, 254), (45, 183, 149), (77, 234, 120), (182, 83, 207), (172, 138, 252), (201, 7, 159), (147, 240, 17), (134, 19, 233), (202, 61, 206), (177, 253, 26), (10, 139, 17), (130, 148, 106), (174, 197, 128), (106, 59, 168), (124, 180, 83), (78, 169, 4), (26, 79, 176), (185, 149, 150), (165, 253, 206), (220, 87, 0), (72, 22, 226), (64, 174, 4), (245, 131, 96), (35, 217, 142), (89, 86, 32), (80, 56, 196), (222, 136, 159), (145, 6, 219), (143, 132, 162), (175, 97, 221), (72, 3, 79), (196, 184, 237), (18, 210, 116), (8, 185, 81), (99, 181, 254), (9, 127, 123), (140, 94, 215), (39, 229, 121), (230, 51, 96), (84, 225, 33), (218, 202, 139), (129, 223, 182), (167, 46, 157), (15, 252, 5), (128, 103, 203), (197, 223, 199), (19, 238, 181), (64, 142, 167), (12, 203, 242), (69, 21, 41), (177, 184, 2), (35, 97, 56), (241, 22, 161)]
colors = [(89, 161, 197),(67, 161, 255),(19, 222, 24),(186, 55, 2),(167, 146, 11),(190, 76, 98),(130, 172, 179),(115, 209, 128),(204, 79, 135),(136, 126, 185),(209, 213, 45),(44, 52, 10),(101, 158, 121),(179, 124, 12),(25, 33, 189),(45, 115, 11),(73, 197, 184),(62, 225, 221),(32, 46, 52),(20, 165, 16),(54, 15, 57),(12, 150, 9),(10, 46, 99),(94, 89, 46),(48, 37, 106),(42, 10, 96),(7, 164, 128),(98, 213, 120),(40, 5, 219),(54, 25, 150),(251, 74, 172),(0, 236, 196),(21, 104, 190),(226, 74, 232),(120, 67, 25),(191, 106, 197),(8, 15, 134),(21, 2, 1),(142, 63, 109),(133, 148, 146),(187, 77, 253),(155, 22, 122),(218, 130, 77),(164, 102, 79),(43, 152, 125),(185, 124, 151),(95, 159, 238),(128, 89, 85),(228, 6, 60),(6, 41, 210),(11, 1, 133),(30, 96, 58),(230, 136, 109),(126, 45, 174),(164, 63, 165),(32, 111, 29),(232, 40, 70),(55, 31, 198),(148, 211, 129),(10, 186, 211),(181, 201, 94),(55, 35, 92),(129, 140, 233),(70, 250, 116),(61, 209, 152),(216, 21, 138),(100, 0, 176),(3, 42, 70),(151, 13, 44),(216, 102, 88),(125, 216, 93),(171, 236, 47),(253, 127, 103),(205, 137, 244),(193, 137, 224),(36, 152, 214),(17, 50, 238),(154, 165, 67),(114, 129, 60),(119, 24, 48),(73, 8, 110)]
#plot each boxes
for box in boxes:
#add score in label if score=True
if score :
label = labels[int(box[-1])+1] + " " + str(round(100 * float(box[-2]),1)) + "%"
else :
label = labels[int(box[-1])+1]
#filter every box under conf threshold if conf threshold setted
if conf :
if box[-2] > conf:
color = colors[int(box[-1])]
box_label(image, box, label, color)
else:
color = colors[int(box[-1])]
box_label(image, box, label, color)
#show image
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
return image
def plot_results(results, folder_path = None,image_path = None, image_data = None, result_name = None,box_type = False, labels=[], save_image = True, return_image = False):
image = None
if image_path:
image = Image.open(image_path)
else:
image = image_data
image = np.asarray(image)
img = None
if not box_type:
img = plot_bboxes(image, results[0].boxes.boxes,labels=labels,score=True)
else:
img = plot_bboxes(image, results,score=True)
result_image_name = result_name if result_name else image_path.split('/')[-1]
print('OS',os.listdir())
if not folder_path:
folder_path = 'results/'
if not os.path.exists(folder_path):
os.mkdir(folder_path)
if save_image:
cv2.imwrite(folder_path + result_image_name, img)
if return_image:
return img
# read ENV.txt file and return config dict
def read_env(file_path):
env_file = open(file_path, 'r')
env = env_file.read()
env = env.split('\n')
env = [i.split('=') for i in env]
env_new = {}
for i in env:
if len(i) > 1:
env_new[i[0]] = i[1]
return env_new
class DriveAPI:
global SCOPES
# Define the scopes
SCOPES = ['https://www.googleapis.com/auth/drive']
def __init__(self, credential_file_path = 'credentials.json'):
# Variable self.creds will
# store the user access token.
# If no valid token found
# we will create one.
self.creds = None
# The file token.pickle stores the
# user's access and refresh tokens. It is
# created automatically when the authorization
# flow completes for the first time.
# Check if file token.pickle exists
if os.path.exists('token.pickle'):
# Read the token from the file and
# store it in the variable self.creds
with open('token.pickle', 'rb') as token:
self.creds = pickle.load(token)
# If no valid credentials are available,
# request the user to log in.
if not self.creds or not self.creds.valid:
# If token is expired, it will be refreshed,
# else, we will request a new one.
if self.creds and self.creds.expired and self.creds.refresh_token:
self.creds.refresh(Request())
else:
flow = InstalledAppFlow.from_client_secrets_file(
credential_file_path, SCOPES)
self.creds = flow.run_local_server(port=0)
# Save the access token in token.pickle
# file for future usage
with open('token.pickle', 'wb') as token:
pickle.dump(self.creds, token)
# Connect to the API service
self.service = build('drive', 'v3', credentials=self.creds)
def FileDownload(self, file_id, file_name):
request = self.service.files().get_media(fileId=file_id)
fh = io.BytesIO()
# Initialise a downloader object to download the file
downloader = MediaIoBaseDownload(fh, request, chunksize=204800)
done = False
try:
# Download the data in chunks
while not done:
status, done = downloader.next_chunk()
fh.seek(0)
# Write the received data to the file
with open(file_name, 'wb') as f:
shutil.copyfileobj(fh, f)
print("File Downloaded")
# Return True if file Downloaded successfully
return True
except:
# Return False if something went wrong
print("Something went wrong.")
return False
def FileUpload(self, filepath, name=None, folder_id = None):
# Extract the file name out of the file path
if name is None:
name = filepath.split('/')[-1]
# Find the MimeType of the file
mimetype = MimeTypes().guess_type(name)[0]
# create file metadata
file_metadata = {'name': name}
if folder_id:
file_metadata['parents'] = [folder_id]
try:
media = MediaFileUpload(filepath, mimetype=mimetype)
# Create a new file in the Drive storage
file = self.service.files().create(
body=file_metadata, media_body=media, fields='id').execute()
print("File Uploaded. Returning File ID")
# Return the created file's id
return file.get('id')
except:
# Raise UploadError if file is not uploaded.
raise UploadError("Can't Upload File.")
def getDriveDownloadLink(file_id):
return 'https://drive.google.com/uc?export=download&id=' + file_id
def downloadImageFromURL(url, image_path='temp.jpg'):
img_data = requests.get(url).content
with open(image_path, 'wb') as handler:
handler.write(img_data)
def getImageDataFromDriveFileId(driveAPI,file_id):
# get download link from google drive file id
driveAPI.FileDownload(file_id, 'temp.jpg')
im = Image.open('temp.jpg')
return im