# This Python file uses the following encoding: utf-8 import re import cv2 import numpy as np from PIL import Image def random_normal_distribution_int(a, b, n=3): """Generate a normal distribution int within the interval. Use the average value of several random numbers to simulate normal distribution. Args: a (int): The minimum of the interval. b (int): The maximum of the interval. n (int): The amount of numbers in simulation. Default to 3. Returns: int """ if a < b: output = np.mean(np.random.randint(a, b, size=n)) return int(output.round()) else: return b def ensure_time(second, n=3, precision=3): """Ensure to be time. Args: second (int, float, tuple): time, such as 10, (10, 30), '10, 30' n (int): The amount of numbers in simulation. Default to 5. precision (int): Decimals. Returns: float: """ if isinstance(second, tuple): multiply = 10 ** precision result = random_normal_distribution_int(second[0] * multiply, second[1] * multiply, n) / multiply return round(result, precision) elif isinstance(second, str): if ',' in second: lower, upper = second.replace(' ', '').split(',') lower, upper = int(lower), int(upper) return ensure_time((lower, upper), n=n, precision=precision) if '-' in second: lower, upper = second.replace(' ', '').split('-') lower, upper = int(lower), int(upper) return ensure_time((lower, upper), n=n, precision=precision) else: return int(second) else: return second def point2str(x, y, length=4): """ Args: x (int, float): y (int, float): length (int): Align length. Returns: str: String with numbers right aligned, such as '( 100, 80)'. """ return '(%s, %s)' % (str(int(x)).rjust(length), str(int(y)).rjust(length)) def random_rectangle_point(area, n=3): """Choose a random point in an area. Args: area: (upper_left_x, upper_left_y, bottom_right_x, bottom_right_y). n (int): The amount of numbers in simulation. Default to 3. Returns: tuple(int): (x, y) """ x = random_normal_distribution_int(area[0], area[2], n=n) y = random_normal_distribution_int(area[1], area[3], n=n) return x, y def random_line_segments(p1, p2, n, random_range=(0, 0, 0, 0)): """Cut a line into multiple segments. Args: p1: (x, y). p2: (x, y). n: Number of slice. random_range: Add a random_range to points. Returns: list[tuple]: [(x0, y0), (x1, y1), (x2, y2)] """ return [tuple((((n - index) * p1 + index * p2) / n).astype(int) + random_rectangle_point(random_range)) for index in range(0, n + 1)]