Spaces:
Build error
Build error
File size: 18,967 Bytes
13e8f60 0e2fe1b 0e78d33 0e2fe1b 94e939a 0e2fe1b 1b4cb98 1db03cb b4b42f8 1db03cb b4b42f8 1db03cb 92d7f44 1db03cb f626c18 1db03cb f626c18 1db03cb d13a2b7 1db03cb 71fd3ae 1db03cb 212b647 1db03cb 0e2fe1b 94e939a 0e2fe1b 3be0020 7848c2f 94e939a 1db03cb 7bc9e42 94e939a 7bc9e42 00dddb7 7bc9e42 00dddb7 7bc9e42 00dddb7 7bc9e42 7848c2f 94e939a 00dddb7 94e939a 00dddb7 94e939a 00dddb7 94e939a 7bc9e42 94e939a 2fee42c 94e939a 20a2844 94e939a 5b7c7b8 94e939a 894f775 1db03cb 06a6818 1db03cb 894f775 1db03cb e8da5f2 1db03cb e8da5f2 1db03cb e8da5f2 78b7608 e8da5f2 3c58be5 4a39d87 1db03cb 16075a1 438ca75 bffd71f 3c6c4df 62c44e2 4c5dbb5 438ca75 71145ee c59dcc2 71145ee 4a39d87 438ca75 0e2fe1b d955c69 4138ff2 bc36179 fa3257d 62c44e2 0c7f89d d955c69 49925b9 d955c69 4a39d87 e27a8ff d955c69 d479ee0 d955c69 d479ee0 d955c69 f35256b 0e2fe1b e48d533 7a4c5d9 |
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 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 |
# Libraries
import tensorflow as tf
import os
import pathlib
import time
import datetime
from matplotlib import pyplot as plt
import numpy as np
import cv2 as cv2
import math
from tensorflow import keras
from tensorflow.keras.models import *
from tensorflow.keras.layers import *
from tensorflow.keras.optimizers import *
###YOLOFACE
import sys
CONF_THRESHOLD = 0.5
NMS_THRESHOLD = 0.4
IMG_WIDTH = 416
IMG_HEIGHT = 416
# Default colors
COLOR_BLUE = (255, 0, 0)
COLOR_GREEN = (0, 255, 0)
COLOR_RED = (0, 0, 255)
COLOR_WHITE = (255, 255, 255)
COLOR_YELLOW = (0, 255, 255)
# Get the names of the output layers
def get_outputs_names(net):
# Get the names of all the layers in the network
layers_names = net.getLayerNames()
# Get the names of the output layers, i.e. the layers with unconnected
# outputs
return [layers_names[i - 1] for i in net.getUnconnectedOutLayers()]
# Draw the predicted bounding box
def draw_predict(frame, conf, left, top, right, bottom):
# Draw a bounding box.
cv2.rectangle(frame, (left, top), (right, bottom), COLOR_YELLOW, 2)
text = '{:.2f}'.format(conf)
# Display the label at the top of the bounding box
label_size, base_line = cv2.getTextSize(text, cv2.FONT_HERSHEY_SIMPLEX, 0.5, 1)
top = max(top, label_size[1])
cv2.putText(frame, text, (left, top - 4), cv2.FONT_HERSHEY_SIMPLEX, 0.4,
COLOR_WHITE, 1)
def post_process(frame, outs, conf_threshold, nms_threshold):
frame_height = frame.shape[0]
frame_width = frame.shape[1]
# Scan through all the bounding boxes output from the network and keep only
# the ones with high confidence scores. Assign the box's class label as the
# class with the highest score.
confidences = []
boxes = []
final_boxes = []
for out in outs:
for detection in out:
scores = detection[5:]
class_id = np.argmax(scores)
confidence = scores[class_id]
if confidence > conf_threshold:
center_x = int(detection[0] * frame_width)
center_y = int(detection[1] * frame_height)
width = int(detection[2] * frame_width)
height = int(detection[3] * frame_height)
left = int(center_x - width / 2)
top = int(center_y - height / 2)
confidences.append(float(confidence))
boxes.append([left, top, width, height])
# Perform non maximum suppression to eliminate redundant
# overlapping boxes with lower confidences.
indices = cv2.dnn.NMSBoxes(boxes, confidences, conf_threshold,
nms_threshold)
field = 0
ratio = 0
face = 0
for i in indices:
box = boxes[i]
left = box[0]
top = box[1]
width = box[2]
height = box[3]
final_boxes.append(box)
if len(indices)==1:
field = 2*(width+height)
ratio = (field * 100) / (256 *256)
#print("%.2f" % ratio)
elif len(indices)>1:
if len(indices) != i+1:
field += 2*(width+height)
ratio = (field * 100) / (256 * 256)
#if len(indices) == i:
#print("%.2f" % ratio)
if ratio > 0.60:
face = 1
#print("face!")
left, top, right, bottom = refined_box(left, top, width, height)
# draw_predict(frame, confidences[i], left, top, left + width,
# top + height)
draw_predict(frame, confidences[i], left, top, right, bottom)
return final_boxes, face
class FPS:
def __init__(self):
# store the start time, end time, and total number of frames
# that were examined between the start and end intervals
self._start = None
self._end = None
self._num_frames = 0
def start(self):
self._start = datetime.datetime.now()
return self
def stop(self):
self._end = datetime.datetime.now()
def update(self):
# increment the total number of frames examined during the
# start and end intervals
self._num_frames += 1
def elapsed(self):
# return the total number of seconds between the start and
# end interval
return (self._end - self._start).total_seconds()
def fps(self):
# compute the (approximate) frames per second
return self._num_frames / self.elapsed()
def refined_box(left, top, width, height):
right = left + width
bottom = top + height
original_vert_height = bottom - top
top = int(top + original_vert_height * 0.15)
bottom = int(bottom - original_vert_height * 0.05)
margin = ((bottom - top) - (right - left)) // 2
left = left - margin if (bottom - top - right + left) % 2 == 0 else left - margin - 1
right = right + margin
return left, top, right, bottom
model_cfg = 'yolov3-face.cfg'
model_weights = 'yolov3-wider_16000.weights'
net = cv2.dnn.readNetFromDarknet(model_cfg, model_weights)
net.setPreferableBackend(cv2.dnn.DNN_BACKEND_OPENCV)
net.setPreferableTarget(cv2.dnn.DNN_TARGET_CPU)
def face_detection(image):
output_file = ''
index = 1
while True:
image = np.array(image)
# Create a 4D blob from a frame.
blob = cv2.dnn.blobFromImage(image, 1 / 255, (IMG_WIDTH, IMG_HEIGHT),[0, 0, 0], 1, crop=False)
# Sets the input to the network
net.setInput(blob)
# Runs the forward pass to get output of the output layers
outs = net.forward(get_outputs_names(net))
# Remove the bounding boxes with low confidence
faces = post_process(image, outs, CONF_THRESHOLD, NMS_THRESHOLD)
#print('[i] ==> # detected faces: {}'.format(len(faces)))
#print('#' * 60)
# initialize the set of information we'll displaying on the frame
info = [
('number of faces detected', '{}'.format(len(faces)))
]
"""
for (i, (txt, val)) in enumerate(info):
text = '{}: {}'.format(txt, val)
cv2.putText(frame, text, (10, (i * 20) + 20),
cv2.FONT_HERSHEY_SIMPLEX, 0.4, COLOR_RED, 1)
"""
return faces[1]
cap.release()
cv2.destroyAllWindows()
###PIX2PIX
def color_imread(path):
img = cv2.imread(path)
img = cv2.cvtColor(img , cv2.COLOR_BGR2RGB)
img = (img/127.5) - 1
img = img.astype(np.float32)
return img
def gray_imread(path):
img = cv2.imread(path)
img = cv2.cvtColor(img ,cv2.COLOR_BGR2GRAY)
img = img.astype(np.float32)
return img
def reshape(gray_img):
gray_img = np.asarray(gray_img)
gray_img = gray_img.reshape(256,256,1)
return gray_img
array_Gen_loss=[]
def histogram_graphic(img):
hist,bins = np.histogram(img.flatten(),256,[0,256])
cdf = hist.cumsum()
cdf_normalized = cdf * float(hist.max()) / cdf.max()
plt.plot(cdf_normalized, color = 'b')
plt.hist(img.flatten(),256,[0,256], color = 'r')
plt.xlim([0, 230])
plt.legend(('cdf','histogram'), loc = 'upper left')
plt.show()
def preprocessing(path):
img = cv2.imread(path)
img = np.asarray(img).reshape(256,256,3)
#print(img.shape)
#cv2.imshow(img)
#cv2.imwrite("/content/drive/MyDrive/ColabNotebooks/enhance/Before_hist_equalizer.png",img)
#Işık ayarı
hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV) #hsv formatında gerekiyor
hue, sat, val = cv2.split(hsv)
mid = 0.5
mean = np.mean(val)
gamma = math.log(mid*255)/math.log(mean)
#print("Gamma:",gamma)
#Çıkan gamma değerine göre ters işlem uygulayacak
def image_colorfulness(image):
# split the image into its respective RGB components
(B, G, R) = cv2.split(image.astype("float"))
# compute rg = R - G
rg = np.absolute(R - G)
# compute yb = 0.5 * (R + G) - B
yb = np.absolute(0.5 * (R + G) - B)
# compute the mean and standard deviation of both `rg` and `yb`
(rbMean, rbStd) = (np.mean(rg), np.std(rg))
(ybMean, ybStd) = (np.mean(yb), np.std(yb))
# combine the mean and standard deviations
stdRoot = np.sqrt((rbStd ** 2) + (ybStd ** 2))
meanRoot = np.sqrt((rbMean ** 2) + (ybMean ** 2))
# derive the "colorfulness" metric and return it
return stdRoot + (0.3 * meanRoot) # sınırı 24
from PIL import Image, ImageEnhance
def add_saturation(path):
clr = cv2.imread(path)
value = image_colorfulness(clr)
print(value)
img = Image.open(path)
enhanced_obj = ImageEnhance.Color(img)
if value<30 : #renk doygunluğu iyi durumda çıkanları da bir miktar arttırmak için sınırı 30 yapıyoruz
enhanced_obj.enhance((30-value)*0.1 + 0.75).save("enhance/deneme_sat.jpg")
#add_saturation("/content/drive/MyDrive/ColabNotebooks/enhance/cikti2.jpeg")
def unsharp_mask(image, kernel_size=(5, 5), sigma=1.0, amount=1.0, threshold=0):
"""Return a sharpened version of the image, using an unsharp mask."""
blurred = cv2.GaussianBlur(image, kernel_size, sigma)
sharpened = float(amount + 1) * image - float(amount) * blurred
sharpened = np.maximum(sharpened, np.zeros(sharpened.shape))
sharpened = np.minimum(sharpened, 255 * np.ones(sharpened.shape))
sharpened = sharpened.round().astype(np.uint8)
if threshold > 0:
low_contrast_mask = np.absolute(image - blurred) < threshold
np.copyto(sharpened, image, where=low_contrast_mask)
return sharpened
def example(image,name):
sharpened_image = unsharp_mask(image)
cv2.imwrite(name, sharpened_image)
def ssim_psnr(pre,target):
ssim_res = ssim(pre,target)
psnr_res = psnr(pre,target)
ssim_results.append(ssim_res)
psnr_results.append(ssim_results)
def alexnet(pretrained_weights = None,input_size = (256,256,3)):
model = Sequential()
model.add(Conv2D(input_shape=input_size, filters= 512, kernel_size =(11,11) ,strides=(4,4), activation = keras.layers.LeakyReLU(alpha=0.01)))
model.add(MaxPooling2D(pool_size=(3, 3), strides=(2,2)))
model.add(Conv2D(filters= 256, kernel_size =(5,5) ,strides=(2,2), activation = keras.layers.LeakyReLU(alpha=0.01) , padding='same'))
model.add(MaxPooling2D(pool_size=(3, 3), strides=(2,2)))
model.add(Conv2D(filters= 128, kernel_size =(3,3) , activation = keras.layers.LeakyReLU(alpha=0.01) , padding='same'))
model.add(Conv2D(filters= 32, kernel_size =(3,3) , activation = keras.layers.LeakyReLU(alpha=0.01) , padding='same'))
model.add(MaxPooling2D(pool_size=(3, 3), strides=(2,2)))
model.add(Flatten())
model.add(Dense(4096 , activation = keras.layers.LeakyReLU(alpha=0.01)))
model.add(Dropout(0.3))
model.add(Dense(4096 , activation = keras.layers.LeakyReLU(alpha=0.01)))
model.add(Dropout(0.5))
model.add(Dense(256 , activation = keras.layers.LeakyReLU(alpha=0.01)))
model.add(Dropout(0.3))
model.add(Dense(2 , activation='softmax'))
return model
def result(Input,Choice,Step):
if Choice=="Place-Coloring":
###ALEXNET
model = alexnet()
model.load_weights('indoor_outdoor.h5')
image = cv2.cvtColor(Input,cv2.COLOR_BGR2RGB)
image = cv2.resize(image, (256,256), interpolation = cv2.INTER_AREA)
image = np.array(image).reshape(-1,256,256,3)
pred = model.predict(image)
result = np.argmax(pred, axis=1)
if int(result[0]) == 1:
if Step == 1.0:
pre_trained = tf.keras.models.load_model("indoor_1.h5")
if Step == 2.0:
pre_trained = tf.keras.models.load_model("indoor_2.h5")
if Step == 3.0:
pre_trained = tf.keras.models.load_model("indoor_3.h5")
size0 = Input.shape[0]
size1 = Input.shape[1]
start = Input
Input = cv2.cvtColor(Input,cv2.COLOR_RGB2BGR)
Input = cv2.resize(Input, (256,256), interpolation = cv2.INTER_AREA)
Input = cv2.cvtColor(Input , cv2.COLOR_BGR2GRAY)
Input = np.array(Input).reshape(1,256,256,1)
prediction = pre_trained(Input,training=True)
Input = prediction[0]
Input = (Input+1)*127.5
Input = np.uint8(Input)
Input = cv2.resize(Input, (size1,size0), interpolation = cv2.INTER_AREA)
Input = unsharp_mask(Input)
finish = Input
mse = np.mean((start - finish) ** 2)
MAX = np.iinfo(start.dtype).max
if mse == 0:
Psnr = 100
else:
Psnr = 20 * math.log10(MAX / math.sqrt(mse))
return Input,Psnr
if int(result[0]) == 0:
if Step == 1.0:
pre_trained = tf.keras.models.load_model("outdoor_1.h5")
if Step == 2.0:
pre_trained = tf.keras.models.load_model("outdoor_2.h5")
if Step == 3.0:
pre_trained = tf.keras.models.load_model("outdoor_3.h5")
size0 = Input.shape[0]
size1 = Input.shape[1]
start = Input
Input = cv2.cvtColor(Input,cv2.COLOR_RGB2BGR)
Input = cv2.resize(Input, (256,256), interpolation = cv2.INTER_AREA)
Input = cv2.cvtColor(Input , cv2.COLOR_BGR2GRAY)
Input = np.array(Input).reshape(1,256,256,1)
prediction = pre_trained(Input,training=True)
Input = prediction[0]
Input = (Input+1)*127.5
Input = np.uint8(Input)
Input = cv2.resize(Input, (size1,size0), interpolation = cv2.INTER_AREA)
Input = unsharp_mask(Input)
finish = Input
mse = np.mean((start - finish) ** 2)
MAX = np.iinfo(start.dtype).max
if mse == 0:
Psnr = 100
else:
Psnr = 20 * math.log10(MAX / math.sqrt(mse))
return Input,Psnr
if Choice=="Face-Coloring":
test_face = face_detection(Input)
if test_face != 1:
Psnr = -1
return Input, Psnr
else:
if Step == 1.0:
pre_trained = tf.keras.models.load_model("face_1.h5")
if Step == 2.0:
pre_trained = tf.keras.models.load_model("face_2.h5")
if Step == 3.0:
pre_trained = tf.keras.models.load_model("face_3.h5")
size0 = Input.shape[0]
size1 = Input.shape[1]
start = Input
Input = cv2.resize(Input, (256,256), interpolation = cv2.INTER_AREA)
Input = cv2.cvtColor(Input , cv2.COLOR_BGR2GRAY)
Input = np.array(Input).reshape(1,256,256,1)
prediction = pre_trained(Input,training=True)
Input = prediction[0]
Input = (Input+1)*127.5
Input = np.uint8(Input)
Input = cv2.resize(Input, (size1,size0), interpolation = cv2.INTER_AREA)
Input = unsharp_mask(Input)
finish = Input
mse = np.mean((start - finish) ** 2)
MAX = np.iinfo(start.dtype).max
if mse == 0:
Psnr = 100
else:
Psnr = 20 * math.log10(MAX / math.sqrt(mse))
return Input,Psnr
if Choice =="Enhancement":
if Step == 1.0:
pre_trained = tf.keras.models.load_model("generatorLR-HR_300.h5")
if Step == 2.0:
pre_trained = tf.keras.models.load_model("generatorLR-HR_300.h5")
if Step == 3.0:
pre_trained = tf.keras.models.load_model("generatorLR-HR_300.h5")
size0 = Input.shape[0]
size1 = Input.shape[1]
start = Input
Input = cv2.resize(Input, (256,256), interpolation = cv2.INTER_AREA)
Input = cv2.cvtColor(Input , cv2.COLOR_BGR2RGB)
Input = (Input/127.5) - 1
Input = Input.astype(np.float32)
Input = np.array(Input).reshape(1,256,256,3)
prediction = pre_trained(Input,training=True)
Input = prediction[0]
Input = (Input+1)*127.5
Input = np.uint8(Input)
Input = np.array(Input).reshape(256,256,3)
Input = cv2.cvtColor(Input , cv2.COLOR_BGR2RGB)
Input = cv2.resize(Input, (size1,size0), interpolation = cv2.INTER_AREA)
Input = unsharp_mask(Input)
finish = Input
mse = np.mean((start - finish) ** 2)
MAX = np.iinfo(start.dtype).max
if mse == 0:
Psnr = 100
else:
Psnr = 20 * math.log10(MAX / math.sqrt(mse))
return Input,Psnr
if Choice=="Repair":
if Step == 1.0:
pre_trained = tf.keras.models.load_model("Repair_1.h5")
if Step == 2.0:
pre_trained = tf.keras.models.load_model("Repair_2.h5")
if Step == 3.0:
pre_trained = tf.keras.models.load_model("Repair_3.h5")
size0 = Input.shape[0]
size1 = Input.shape[1]
start = Input
start = cv2.cvtColor(start , cv2.COLOR_RGB2GRAY)
start = np.array(start).reshape(256,256)
Input = cv2.resize(Input, (256,256), interpolation = cv2.INTER_AREA)
Input = cv2.cvtColor(Input , cv2.COLOR_RGB2GRAY)
Input = Input.astype(np.float32)
Input = np.array(Input).reshape(1,256,256,1)
prediction = pre_trained(Input,training=True)
Input = prediction[0]
Input = (Input+1)*127.5
Input = np.uint8(Input)
Input = np.array(Input).reshape(256,256,3)
Input = cv2.resize(Input, (size1,size0), interpolation = cv2.INTER_AREA)
Input = unsharp_mask(Input)
Input = cv2.cvtColor(Input , cv2.COLOR_RGB2GRAY)
finish = Input
mse = np.mean((start - finish) ** 2)
MAX = np.iinfo(start.dtype).max
if mse == 0:
Psnr = 100
else:
Psnr = 20 * math.log10(MAX / math.sqrt(mse))
return Input,Psnr
#lst = cv2.imread('/content/drive/MyDrive/ColabNotebooks/enhance/low-sat.jpg')
#r = result(lst)
#cv2.imshow(r)
import gradio as gr
gr.Interface(fn=result, inputs=[gr.inputs.Image(type="numpy",image_mode="RGB"), gr.inputs.Radio(
choices=["Place-Coloring","Face-Coloring","Enhancement", "Repair"]),gr.inputs.Slider(minimum=1.0,maximum=3.0,default=3.0,step=1.0)], outputs=[gr.outputs.Image(type="numpy", label="Output"),gr.outputs.Textbox(label="Psnr Between Input and Output")], live=True,title="Color, Enhancement, Restoration for Old Images - ImgCERO",examples=[["repair.png","Repair",3.0],["enhancement.png","Enhancement",3.0],["face_color.png","Face-Coloring",3.0],["indoor_color.png","Place-Coloring",3.0],["outdoor_color.png","Place-Coloring",3.0]],css=""" body {background-color: rgba(127,191,63,0.48)} """,article=""" <a href="https://docs.google.com/document/d/19k6dyR5x_hd1M0yoU8i49dlDWvFmtnBT/edit?usp=sharing&ouid=115743073712072785012&rtpof=true&sd=true" download="example.docx"><img src="https://img.icons8.com/external-itim2101-lineal-color-itim2101/64/000000/external-article-blogger-and-influencer-itim2101-lineal-color-itim2101-1.png" alt="Article"></a>""").launch(debug="True") |