Пример #1
0
def is_apply_all_expr(expr_str):

    match = re.findall('(?<=apply-all \[)(.*)] to (.*)', expr_str)
    if (len(match) != 1):
        raise hiphop_error("ParserError", 'Invalid syntax for `apply-all` expression.')
    match_funcs, match_id = match[0]
    lambda_funcs = []
    new_funcs = match_funcs.split(",")
    for new_func in new_funcs:
        new_lambda = make_lambda_func(new_func.strip())
        if (isinstance(new_lambda, hiphop_error)):
            raise hiphop_error("ParserError", 'Unable to make lambda function for {}'.format(new_func))
        lambda_funcs.append(new_lambda)
    return apply_all_expr(lambda_funcs, match_id)
Пример #2
0
def openfile(filename, id):

    # print("Open file function called. Parameters: {}, {}".format(filename, id))
    img = cv2.imread(filename)
    if (img is None):
        raise hiphop_error("OpenImageError", "Filename does not exist.")
    saved_vars.add_var(id, img)
Пример #3
0
def is_save_expr(expr_str):
    if 'genfilename' in expr_str:
        gen = True
        genMax = 2
    else:
        gen = False
        genMax = 1
    # print(gen)
    expr_arr = expr_str.split('"', maxsplit=genMax)
    expr_arr.insert(1, env_vars['wd'])
    if gen:
        fileType = expr_arr[3]
        newFile = genFilename(fileType)
        expr_arr[2] = newFile
        # print(newFile)
        expr_arr.pop()
    # print(expr_arr)
    expr_str = ''.join(expr_arr)
    # print(expr_str)

    match_id = re.findall('(?<=save )(.*)(?= as)', expr_str)
    match_filename = re.findall('(?<=save ).*(?<= as ")(.*)"', expr_str)
    # print("filename: {}; id: {}".format(match_filename[0], match_id[0]))
    if (len(match_filename) != 1 or len(match_id) != 1):
        raise hiphop_error("ParserError",
                           'Invalid syntax for `save` expression.')
    else:
        return save_expr(match_id[0], match_filename[0])
Пример #4
0
    def parse_line(self, expr):

        tokens = expr.split()
        if tokens[0] == "open":
            open_expr = is_open_expr(expr)
            open_expr.evaluate()
        elif tokens[0] == "reload":
            load_expr = is_load_expr(expr)
            load_expr.evaluate()
        elif tokens[0] == "apply":
            apply_expr = is_apply_expr(expr)
            apply_expr.evaluate()
        elif tokens[0] == "save":
            save_expr = is_save_expr(expr)
            save_expr.evaluate()
        elif tokens[0] == "apply-all":
            apply_all_expr = is_apply_all_expr(expr)
            apply_all_expr.evaluate()
        elif tokens[0] == "save-macro":
            save_macro = is_save_macro_expr(expr)
            save_macro.evaluate()
        elif tokens[0] == "set":
            set_expr = is_set_expr(expr)
            set_expr.evaluate()
        elif tokens[0] == "get":
            get_expr = is_get_expr(expr)
            get_expr.get()
        # elif is_identifier(expr):
        #    pass
        else:
            raise hiphop_error("ParseError", "Unable to parse line")
Пример #5
0
def is_save_macro_expr(expr_str):

    match = re.findall('(?<=save-macro \[)(.*)] as (.*)', expr_str)
    if (len(match) != 1):
        raise hiphop_error("ParserError", 'Invalid syntax for `save-macro` expression.')
    match_funcs, match_id = match[0]
    return save_macro_expr(match_funcs, match_id)
Пример #6
0
def impose(id, overlay, px, py):
    img = saved_vars.get_var(id)
    other_image = saved_vars.get_var(overlay)

    # Mask ranges from 0 to width / height of overlay
    mask = np.zeros(img.shape, dtype=np.bool)
    mask[:other_image.shape[0], :other_image.shape[1]] = True

    locs = np.where(mask != 0)  # Get the non-zero mask locations

    # Following conditional logic is equivalent to copyTo from other languages
    # TODO implement overflow logic to cutoff instead of wrap

    # Background is colored but overlay is grayscale
    if len(img.shape) == 3 and len(other_image.shape) != 3:
        img[locs[0] + px, locs[1] + py] = other_image[locs[0], locs[1], None]
    # Both overlay and background are grayscale
    elif (len(img.shape) == 3 and len(other_image.shape) == 3) or \
            (len(img.shape) == 1 and len(other_image.shape) == 1):
        img[locs[0] + px, locs[1] + py] = other_image[locs[0], locs[1]]
    # Otherwise, we can't do this
    else:
        raise hiphop_error("InvalidFunctionError",
                           "Incompatible input and output dimensions.")
    saved_vars.add_var(id, img, saved_vars.get_path(id))
    return
Пример #7
0
def is_save_expr(expr_str):

    match_id = re.findall('(?<=save )(.*)(?= as)', expr_str)
    match_filename = re.findall('(?<=save ).*(?<= as ")(.*)"', expr_str)
    # print("filename: {}; id: {}".format(match_filename[0], match_id[0]))
    if (len(match_filename) != 1 or len(match_id) != 1):
        raise hiphop_error("ParserError", 'Invalid syntax for `save` expression.')
    else:
        return save_expr(match_id[0], match_filename[0])
Пример #8
0
def is_load_expr(expr_str):
    # even though reloading is just opening, the syntax is different,
    # which requires this check

    args = expr_str.split()
    if len(args) > 2:
        raise hiphop_error("ParserError",
                           "Invalid syntax for `reload` expression.")
    else:
        return open_expr(saved_vars.get_path(args[1]), args[1])
Пример #9
0
def is_apply_expr(expr_str):

    match = re.findall('(?<=apply )(.*)( to )(.*)', expr_str)
    if (len(match) != 1):
        raise hiphop_error("ParserError", 'Invalid syntax for `apply` expression.')
    match_func, _, match_id = match[0]
    match_function= match_func.split()
    match_funcname, match_args = match_function[0], match_function[1:]
    # print("funcname: {}; args: {}; id: {}".format(match_funcname, match_args, match_id))
    return apply_expr(match_funcname, match_args, match_id)
Пример #10
0
def is_open_expr(expr_str):
    # For one line of the program, if valid program return object,
    # otherwise False

    match_filename = re.findall('(?<=open ")(.*)(?=" as)', expr_str)
    match_id = re.findall('(?<=open ")*(?<=" as )(.*)$', expr_str)
    if (len(match_filename) != 1 or len(match_id) != 1):
        raise hiphop_error("ParserError", 'Invalid syntax for `open` expression.')
    else:
        return open_expr(match_filename[0], match_id[0])
Пример #11
0
def is_get_expr(expr_str):
    # get expressions allow users to retrieve values of existing
    # environment variables

    args = expr_str.split()
    if len(args) > 2:
        raise hiphop_error("ParserError",
                           "Invalid syntax for `get` expression.")
    else:
        envVar = args[1]
        return get_expr(envVar)
Пример #12
0
    def __init__(self, funcs, id):

        self.funcs = []

        # Parse the string of functions into lambda functions
        new_funcs = funcs.split(",")
        for new_func in new_funcs:
            lambda_func = make_lambda_func(new_func.strip())
            if (isinstance(lambda_func, hiphop_error)):
                raise hiphop_error("FunctionNotFound", "Could not create lambda function.")
            self.funcs.append(lambda_func)

        self.id = id
Пример #13
0
def is_open_expr(expr_str):
    # For one line of the program, if valid program return object,
    # otherwise False
    expr_arr = expr_str.split('"', maxsplit=1)
    expr_arr.insert(1, env_vars['wd'])
    expr_str = ''.join(expr_arr)
    # print(expr_str)

    match_filename = re.findall('(?<=open ")(.*)(?=" as)', expr_str)
    match_id = re.findall('(?<=open ")*(?<=" as )(.*)$', expr_str)
    if (len(match_filename) != 1 or len(match_id) != 1):
        raise hiphop_error("ParserError",
                           'Invalid syntax for `open` expression.')
    else:
        return open_expr(match_filename[0], match_id[0])
Пример #14
0
def make_lambda_func(str):
    # From a string representation, creates a lambda function
    # ie. grayscale 50

    func_tokens = str.split(" ")
    funcname, func_args = func_tokens[0], func_tokens[1:]
    # print("Making lambda function - funcname: {}, args: {}".format(funcname, func_args))

    if (funcname == "blur"):
        if (len(func_args) != 1):
            raise hiphop_eval_error("InvalidFunctionError", "Invalid number of arguments for `blur`")
        return lambda img: blur(img, int(func_args[0]))
    elif (funcname == "grayscale"):
        if (len(func_args) != 0):
            raise hiphop_eval_error("InvalidFunctionError", "Invalid number of arguments for `grayscale`")
        return lambda img: grayscale(img)
    elif (funcname == "erode"):
        if (len(func_args) != 1):
            raise hiphop_eval_error("InvalidFunctionError", "Invalid number of argments for `erode`")
        return lambda img: erode(img, int(func_args[0]))
    elif (funcname == "dilate"):
        if (len(func_args) != 1):
            raise hiphop_eval_error("InvalidFunctionError", "Invalid number of argments for `erode`")
        return lambda img: dilate(img, int(func_args[0]))
    elif (funcname == "outline"):
        if (len(func_args) != 1):
            raise hiphop_error("InvalidFunctionError", -1, "Invalid number of argments for `outline`")
        return lambda img: outline(img, int(func_args[0]))
    elif (funcname == "filtercolor"):
        if (len(func_args) != 6):
            raise hiphop_eval_error("InvalidFunctionError", "Invalid number of arguments for `filtercolor lowR lowG lowB highR highG highB`")
        return lambda img: filtercolor(img, int(func_args[0]), int(func_args[1]), int(func_args[2]),
                                int(func_args[3]), int(func_args[4]), int(func_args[5]))
    elif (funcname == "scale"):
        if (len(func_args) != 2):
            raise hiphop_eval_error("InvalidFunctionError", "Invalid number of argments for `scale`")
        return lambda img: scale(img, float(func_args[0]), float(func_args[1]))
    elif (funcname == "crop"):
        if (len(func_args) != 4):
            raise hiphop_eval_error("InvalidFunctionError", "Invalid number of arguments for `crop widthlow widthhigh heightlow heighthigh`")
        return lambda img: crop(img, float(func_args[0]), float(func_args[1]), float(func_args[2]), float(func_args[3]))
    else:
        raise hiphop_eval_error("InvalidFunctionError",  "Function name does not exist.")
Пример #15
0
def wave(id, direction, amplitude):
    img = saved_vars.get_var(id)
    img_output = np.zeros(img.shape, dtype=img.dtype)
    rows, cols, mask = img.shape
    if direction == "v":
        # print("Dir v")
        for i in range(rows):
            for j in range(cols):
                offset_x = int(int(amplitude) * np.sin(2 * 3.14 * i / 180))
                offset_y = 0
                if j + offset_x < rows:
                    img_output[i, j] = img[i, (j + offset_x) % cols]
                else:
                    img_output[i, j] = 0
    elif direction == "h":
        # print("Dir h")
        for i in range(rows):
            for j in range(cols):
                offset_x = 0
                offset_y = int(int(amplitude) * np.sin(2 * 3.14 * j / 150))
                if i + offset_y < rows:
                    img_output[i, j] = img[(i + offset_y) % rows, j]
                else:
                    img_output[i, j] = 0

    elif direction == "m":
        for i in range(rows):
            for j in range(cols):
                offset_x = int(int(amplitude) * np.sin(2 * 3.14 * i / 150))
                offset_y = int(int(amplitude) * np.cos(2 * 3.14 * j / 150))
                if i + offset_y < rows and j + offset_x < cols:
                    img_output[i, j] = img[(i + offset_y) % rows,
                                           (j + offset_x) % cols]
                else:
                    img_output[i, j] = 0
    else:
        raise hiphop_error("InvalidFunctionError", "Invalid parameters.")
    saved_vars.add_var(id, img_output, saved_vars.get_path(id))
    return