Example #1
0
    def train(self, training_image):
        """ Training """
        real_image = functions.read_image(training_image)
        #real_image = normalize_m11(real_image)

        self.num_scales, stop_scale, scale1, self.scale_factor, reals =\
            functions.adjust_scales2image(real_image, self.scale_factor, self.min_size, self.max_size)

        real_image = functions.read_image(training_image)
        real_image = my_imresize(real_image, scale1)
        reals = []
        reals = functions.creat_reals_pyramid(real_image, reals,
                                              self.scale_factor, stop_scale)
        reals = [
            tf.convert_to_tensor(real.permute((0, 2, 3, 1)).numpy(),
                                 dtype=tf.float32) for real in reals
        ]

        self.Z_fixed = []
        self.NoiseAmp = []
        noise_amp = tf.constant(0.1)

        for scale in range(stop_scale + 1):
            print(scale)
            start = time.perf_counter()

            if scale > 0:
                self.init_from_previous_model(scale)
            g_opt = Adam(learning_rate=self.learning_schedule,
                         beta_1=0.5,
                         beta_2=0.999)
            d_opt = Adam(learning_rate=self.learning_schedule,
                         beta_1=0.5,
                         beta_2=0.999)
            """ Build with shape """
            prev_rec = tf.zeros_like(reals[scale])
            self.discriminators[scale](prev_rec)
            self.generators[scale](prev_rec, prev_rec)

            train_step = self.wrapper()
            print(tf.get_collection('checkpoints'))
            for step in tf.range(self.num_iters):
                z_fixed, prev_rec, noise_amp, metrics = train_step(
                    reals, prev_rec, noise_amp, scale, step, g_opt, d_opt)

            print(tf.get_collection('checkpoints'))

            self.Z_fixed.append(z_fixed)
            self.NoiseAmp.append(noise_amp)
            self.save_model(scale)

            if self.debug:
                self.write_summaries(metrics, scale)
                self.update_metrics(metrics, scale)
                print(
                    f'Time taken for scale {scale} is {time.perf_counter()-start:.2f} sec\n'
                )
def do_one_image(f):

    filename = f
    w = 5
    W = 256
    samples_per_bin = 20000
    n = 0.05
    m = 0.3

    res_directory = functions.create_res_directory(filename)
    img = functions.read_image(filename)

    blocks_list = functions.valid_blocks(img, w)
    num_blocks = len(blocks_list)
    img_means = functions.all_image_means(img, w)
    num_channels = img.shape[2]
    T_mask = functions.get_T_mask(w)

    with multiprocessing.Pool(processes=num_channels) as pool:

        results = Parallel(n_jobs=num_channels)(
            delayed(do_one_channel)(i, n, m, img, W, w, img_means, blocks_list,
                                    num_blocks, samples_per_bin, T_mask)
            for i in range(num_channels))
        all_blocks = results[0][0] + results[1][0] + results[2][0]
        red_blocks = results[0][1] + results[1][1] + results[2][1]

    functions.compute_save_NFA(img, w, W, n, m, samples_per_bin, all_blocks,
                               red_blocks, res_directory)
    functions.do_mask(res_directory, img, 1)
Example #3
0
    def __init__(self, opt):
        super(SinGanOne_Dataset, self).__init__()

        if not isinstance(opt.device, torch.device):
            raise SinGanOne_NonTorchDevice(opt.device)
        self.device = opt.device

        self.real_path = os.path.join(opt.reals_dir, opt.real_name)
        if not os.path.exists(self.real_path):
            raise SinGanOne_PathNotFound(self.real_path)

        self.real_original = read_image(self.real_path, opt.device)
        self.real_scaled = adjust_scales2image(self.real_original, opt)
        self.reals = []
        self.reals = create_reals_pyramid(self.real_scaled, self.reals, opt)

        self.m_noise = nn.ZeroPad2d(int(opt.pad_noise))
        self.m_image = nn.ZeroPad2d(int(opt.pad_image))
        self.len = opt.niter
Example #4
0
def test_image_fail():
    with pytest.raises(FileNotFoundError):
        read_image(
            "nonexistent_file_please_dont_create_file_named_like_this.pls")
Example #5
0
def test_read_image():
    assert read_image("test_images/test_img.png"
                      ).ndim > 0  # jakykoliv non fail vysledek je ok
Example #6
0
def test_compare_darken():
    out = do_darken(test_image, args_mock)
    save_image(out, "test_images/darkenOut.png")
    output = read_image("test_images/darkenOut.png")
    test_input = read_image("test_images/darken.png")
    assert (output == test_input).all()
Example #7
0
def test_compare_bw():
    out = do_bw(test_image)
    save_image(out, "test_images/bwOut.png")
    output = read_image("test_images/bwOut.png")
    test_input = read_image("test_images/bw.png")
    assert (output == test_input).all()
Example #8
0
def test_compare_inverse():
    out = do_inverse(test_image)
    test_input = read_image("test_images/inverse.png")
    assert (out == test_input).all()
Example #9
0
def test_compare_mirror():
    out = do_mirror(test_image)
    test_input = read_image("test_images/mirror.png")
    assert (out == test_input).all()
Example #10
0
def test_compare_rotate():
    out = do_rotate(test_image)
    test_input = read_image("test_images/rotate.png")
    assert (out == test_input).all()
Example #11
0
import unittest.mock as umock
from argparse import ArgumentTypeError

import numpy as np
import pytest

from functions import do_embossing, do_edge_detection, do_blur_5x5, do_blur_3x3, do_sharpen, do_bw, do_darken, \
    do_inverse, do_lighten, do_mirror, do_rotate, percentage, read_image, save_image

test_array = np.array([[1, 1, 1], [1, 1, 1], [1, 1, 1]])

test_image = read_image("test_images/test_img.png")

args_mock = umock.MagicMock()
# zesvetleni a ztmaveni, TODO udelat aby mock vzdy vracel 50, pro pripad ze bude vic unit testu nez hodnot
args_mock.darken = [50, 50, 50, 50, 80, 70, 80, 10,
                    80]  # TODO mockovat veci v danem testu
args_mock.lighten = [50, 50, 50, 50, 100, 70, 40, 50, 100]


def test_read_image():
    assert read_image("test_images/test_img.png"
                      ).ndim > 0  # jakykoliv non fail vysledek je ok


def test_image_fail():
    with pytest.raises(FileNotFoundError):
        read_image(
            "nonexistent_file_please_dont_create_file_named_like_this.pls")

Example #12
0
    help=
    "použije konvoluční metodu k \"vyražení\" POZOR: tento přepínač zabere čas"
)
parser.add_argument("INPUT_FILE",
                    help="Vstupni soubor na upravu (cestu k nemu)")
parser.add_argument("OUTPUT_FILE", help="Cesta k vystupu tohoto programu")
"""
------------
"""

queue = sys.argv[1:-2]  # slice pro poradi prepinacu
args = parser.parse_args()
np_image = None

try:
    np_image = read_image(args.INPUT_FILE)

except FileNotFoundError:
    print("Soubor nenalezen, ukoncuji")
    exit(1)
except Exception as ex:
    print("chyba", ex)
    exit(1)

for act in queue:
    try:
        np_image = action_dict[act](np_image, args)
    except KeyError:  # ciselne a nevalidni hodnoty muzeme preskocit
        pass
    except Exception as ex:
        print("chyba", ex)