image_commons.py 1.93 KB
Newer Older
Arne Gerdes's avatar
Arne Gerdes committed
1
"""
tihmels's avatar
tihmels committed
2
Utility Class for working with images in OpenCV
Arne Gerdes's avatar
Arne Gerdes committed
3
4
5
6
7
8
9
10
"""
import cv2
import numpy as np
from PIL import Image


def image_as_nparray(image):
    """
tihmels's avatar
tihmels committed
11
    Convert PIL Image to Numpy array
Arne Gerdes's avatar
Arne Gerdes committed
12
    :param image: PIL's Image object.
tihmels's avatar
tihmels committed
13
    :return: Numpy Array
Arne Gerdes's avatar
Arne Gerdes committed
14
15
16
17
18
19
    """
    return np.asarray(image)


def nparray_as_image(nparray, mode='RGB'):
    """
tihmels's avatar
tihmels committed
20
    Convert numpy array to PIL image
Arne Gerdes's avatar
Arne Gerdes committed
21
    :param nparray: Numpy's array of image.
tihmels's avatar
tihmels committed
22
23
    :param mode: transformation mode
    :return: PIL image
Arne Gerdes's avatar
Arne Gerdes committed
24
25
26
27
28
29
    """
    return Image.fromarray(np.asarray(np.clip(nparray, 0, 255), dtype='uint8'), mode)


def load_image(source_path):
    """
tihmels's avatar
tihmels committed
30
31
32
    Load the RGB image and convert to grayscale
    :param source_path: source path to image
    :return: converted image
Arne Gerdes's avatar
Arne Gerdes committed
33
34
35
36
37
38
39
    """
    source_image = cv2.imread(source_path)
    return cv2.cvtColor(source_image, cv2.COLOR_BGR2GRAY)


def draw_with_alpha(source_image, image_to_draw, coordinates):
    """
tihmels's avatar
tihmels committed
40
41
42
43
    Draw a partially transparent image on another image
    :param source_image: Background image
    :param image_to_draw: Overdraw image
    :param coordinates: : Coordinates to which the image should be drawn
Arne Gerdes's avatar
Arne Gerdes committed
44
45
46
47
48
    """
    x, y, w, h = coordinates
    image_to_draw = image_to_draw.resize((h, w), Image.ANTIALIAS)
    image_array = image_as_nparray(image_to_draw)
    for c in range(0, 3):
tihmels's avatar
tihmels committed
49
        source_image[y:y + h, x:x + w, c] = image_array[:, :, c] * (image_array[:, :, 3] / 255.0) + source_image[y:y + h, x:x + w, c] * (1.0 - image_array[:, :, 3] / 255.0)
50
51
52

def draw_img(source_image, image_to_draw, coordinates):
    """
tihmels's avatar
tihmels committed
53
54
55
56
    Draw an image to another image
    :param source_image: Background image
    :param image_to_draw: Overdraw image
    :param coordinates: : Coordinates to which the image should be drawn
57
58
59
60
61
62
    """
    x, y, w, h = coordinates
    image_to_draw = image_to_draw.resize((h, w), Image.ANTIALIAS)
    image_array = image_as_nparray(image_to_draw)
    for c in range(0, 3):
        source_image[y:y + h, x:x + w, c] = image_array[:, :]