Passed
Pull Request — master (#1)
by Konstantinos
59s
created

reshape_image()   A

Complexity

Conditions 1

Size

Total Lines 2
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 2
dl 0
loc 2
rs 10
c 0
b 0
f 0
cc 1
nop 2
1
import numpy as np
2
from numpy.typing import NDArray
3
from typing import Tuple
4
5
6
def reshape_image(image: NDArray, shape: Tuple[int, ...]) -> NDArray:
7
    return np.reshape(image, shape)
8
9
10
def subtract(image: NDArray, array: NDArray) -> NDArray:
11
    """Normalize the input image.
12
13
    Args:
14
        image (NDArray): [description]
15
16
    Raises:
17
        ShapeMissmatchError: in case of ValueError due to numpy broadcasting failing
18
19
    Returns:
20
        NDArray: [description]
21
    """ 
22
    try:
23
        return image - array
24
    except ValueError as numpy_broadcast_error: 
25
        raise ShapeMissmatchError(
26
            f'Expected arrays with matching shapes.') from numpy_broadcast_error
27
28
29
class ShapeMissmatchError(Exception): pass
30
31
32
def noisy(image: NDArray, ratio: float) -> NDArray:
33
    """Generates a noisy image by adding random noise to the content_image"""
34
    if ratio < 0 or 1 < ratio:
35
        raise InvalidRatioError('Expected a ratio value x such that 0 <= x <= 1') 
36
37
    prod_shape = image.shape
38
    # assert prod_shape == (1, self.config.image_height, self.config.image_width, self.config.color_channels)
39
40
    noise_image = np.random.uniform(-20, 20, prod_shape).astype('float32')
41
42
    # Set the input_image to be a weighted average of the content_image and a noise_image
43
    return noise_image * ratio + image * (1 - ratio)
44
45
46
class InvalidRatioError(Exception): pass
47
48
49
class ImageDTypeConverter:
50
51
    bit_2_data_type = {8: np.uint8}
52
53
    def __call__(self, image: NDArray):
54
        return self._convert_to_uint8(image)
55
56
    def _convert_to_uint8(self, im):
57
        bitdepth = 8
58
        out_type = type(self).bit_2_data_type[bitdepth]
59
        mi = np.nanmin(im)
60
        ma = np.nanmax(im)
61
        if not np.isfinite(mi):
62
            raise ValueError("Minimum image value is not finite")
63
        if not np.isfinite(ma):
64
            raise ValueError("Maximum image value is not finite")
65
        if ma == mi:
66
            return im.astype(out_type)
67
68
        # Make float copy before we scale
69
        im = im.astype("float64")
70
        # Scale the values between 0 and 1 then multiply by the max value
71
        im = (im - mi) / (ma - mi) * (np.power(2.0, bitdepth) - 1) + 0.499999999
72
        assert np.nanmin(im) >= 0
73
        assert np.nanmax(im) < np.power(2.0, bitdepth)
74
        im = im.astype(out_type)
75
        return im
76
77
78
convert_to_uint8 = ImageDTypeConverter()
79