Regresia obrázkov

Blog Admin

Zdrojový kód v jazyku Python 3.x

1
2
#!/opt/python/Python-3.6.5/python
# -*- coding: utf-8 -*-
from __future__ import division
import cgi
import cgitb
import sys
import os
cgitb.enable()
print ("Content-Type: text/html; Charset='UTF-8'")
print ("")#use this double quote print statement to add a blank line in the script

import os
import warnings
import argparse
import sys
from PIL import Image
import time

# Create instance of FieldStorage 
data = cgi.FieldStorage() 
global filename 
# Get data from fields
filename = str(data.getvalue('filename'))

fname = "/var/www/masternn/masternn/collect_static/blog/output/" + filename

mydir = '/var/www/masternn/masternn/collect_static/blog/output/'

now = time.time()
old = now - 7200

for f in os.listdir(mydir):
    path = os.path.join(mydir, f)
    if os.path.isfile(path):
        stat = os.stat(path)
        if stat.st_ctime < old and f.find('reg') is not -1:
            os.remove(path) 

from skimage.io import imread, imsave
from keras.models import Sequential
from keras.layers import Activation, Dense
from keras.callbacks import Callback
import numpy as np

arg_parser = argparse.ArgumentParser()
arg_parser.add_argument('-i', help='File name of input image', dest='input_filename', type=str, default='/var/www/masternn/masternn/collect_static/blog/output/xmas.png')
#arg_parser.add_argument('--num-epochs', help='Number of epochs', dest='num_epochs', type=int, default=1000)
args = arg_parser.parse_args()

num_epochs = 500

image = imread(args.input_filename, as_grey=False, plugin='pil')
if str(image.dtype) == 'uint8':
    image = np.divide(image, 255.0)

img_height = image.shape[0]
img_width = image.shape[1]
num_channels = image.shape[2]
x = []
y = []
for i in range(img_height):
    for j in range(img_width):
        x.append([i / img_height, j / img_width])
        y.append(image[i][j])
x = np.array(x)
y = np.array(y)

model = Sequential()
model.add(Dense(30, input_dim=2))
model.add(Activation('relu'))
model.add(Dense(30))
model.add(Activation('relu'))
model.add(Dense(30))
model.add(Activation('relu'))
model.add(Dense(30))
model.add(Activation('relu'))
model.add(Dense(num_channels))
model.add(Activation('relu'))

model.compile(
    loss='mean_squared_error',
    optimizer='rmsprop'
)


class CheckpointOutputs(Callback):
    def __init__(self):
        super(CheckpointOutputs, self).__init__()
        self.last_loss_checkpoint = 9001  # it's over 9000!
        self.loss_change_threshold = 0.05

    def on_epoch_end(self, epoch, logs=None):
        if logs is None:
            return
        loss_change = 1 - logs['loss'] / self.last_loss_checkpoint

        if loss_change > self.loss_change_threshold:
            self.last_loss_checkpoint = logs['loss']
            predicted_image = self.model.predict(x, verbose=False)
            predicted_image = np.clip(predicted_image, 0, 1)
            predicted_image = predicted_image.reshape(image.shape)

            with warnings.catch_warnings():            
                output_file_path = os.path.join(
                    '/var/www/masternn/masternn/collect_static/blog/output',
                    '{0}'.format(filename, epoch)
                )
                imsave(output_file_path, predicted_image)

checkpoint_outputs = CheckpointOutputs()
history = model.fit(
    x,
    y,
    batch_size=128,
    epochs=num_epochs,
    shuffle=True,
    callbacks=[checkpoint_outputs]
)

Autor príspevku: F. Gachulinec Dr., PhD.

          
Tágy:
Python regresia umelá inteligencia neurónová sieť