Ejemplo n.º 1
0
def blend_images(opacity, mode, img_1, img_2):
    if opacity > 0:
        if mode == "Dodge":
            return blend_modes.dodge(img_1, img_2, opacity)
        elif mode == "Addition":
            return blend_modes.addition(img_1, img_2, opacity)
        elif mode == "Overlay":
            return blend_modes.overlay(img_1, img_2, opacity)
        elif mode == "Subtract":
            return blend_modes.subtract(img_1, img_2, opacity)
        elif mode == "Grain Extract":
            return blend_modes.grain_extract(img_1, img_2, opacity)
        elif mode == "Darken Only":
            return blend_modes.darken_only(img_1, img_2, opacity)
        elif mode == "Screen":
            return blend_modes.screen(img_1, img_2, opacity)
        elif mode == "Divide":
            return blend_modes.divide(img_1, img_2, opacity)
        elif mode == "Grain Merge":
            return blend_modes.grain_merge(img_1, img_2, opacity)
        elif mode == "Difference":
            return blend_modes.difference(img_1, img_2, opacity)
        elif mode == "Multiply":
            return blend_modes.multiply(img_1, img_2, opacity)
        elif mode == "Soft Light":
            return blend_modes.soft_light(img_1, img_2, opacity)
        elif mode == "Hard Light":
            return blend_modes.hard_light(img_1, img_2, opacity)
        elif mode == "Lighten Only":
            return blend_modes.lighten_only(img_1, img_2, opacity)
        elif mode == "None":
            return blend_modes.normal(img_1, img_2, opacity)
    else:
        return img_1
Ejemplo n.º 2
0
def imgProcessor(logoName='wide'):
    # اجيب الصور
    filename = f'{logoName}.png'
    logo = 'logo.png'
    filename1 = 'image.jpg'
    frontImage = Image.open(filename)
    img = Image.open(filename1)
    thelogo = Image.open(logo)
    # حول الباككًراوند الى rgba
    background = img.convert("RGBA")
    # غير حجم الجريدينت
    new = frontImage.resize((background.width, background.height))
    # حول الى نمباي
    np_bg = np.array(background)
    np_foreground = np.array(new)
    #  انتجر امج
    foreground_img_float = np_foreground.astype(float)
    np_bg_float = np_bg.astype(float)
    # فلوت امج
    new = multiply(np_bg_float, foreground_img_float, 1)

    # #  rontImage = frontImage.convert("RGBA")
    rgbalogo = thelogo.convert("RGBA")
    goodlogo = rgbalogo.resize(
        (round(rgbalogo.width / 11), round(rgbalogo.height / 11)))
    # new = multiply(background, new, 1)
    # # background.paste(new, (0, 0), new)
    blended_img = np.uint8(new)
    blended_img_raw = Image.fromarray(blended_img)
    blended_img_raw.paste(goodlogo,
                          (background.width - 130, background.height - 165),
                          goodlogo)
    # Image needs to be converted back to uint8 type for PIL handling.

    blended_img_raw.save('end.png')
Ejemplo n.º 3
0
def mergeRGB(video_dict, codec, mode):
    capA = cv2.VideoCapture(video_dict['A'])
    capB = cv2.VideoCapture(video_dict['B'])
    frame_width = int(capA.get(3))
    frame_height = int(capA.get(4))
    frame_rate = round(capA.get(5), 2)
    input_name = os.path.splitext(os.path.basename(video_dict['A']))
    output_name = mode + "_RGBMerge_" + input_name[0][:-4] + input_name[1]
    out = cv2.VideoWriter(output_name, codec, frame_rate,
                          (frame_width, frame_height))
    while (capA.isOpened()):
        retA, frameA = capA.read()
        retB, frameB = capB.read()
        if retA == True:
            ## give frames an alpha channel to prepare for blending; blend_modes requires 32bit
            frameA = cv2.cvtColor(frameA, cv2.COLOR_BGR2BGRA,
                                  4).astype(np.float32)
            frameB = cv2.cvtColor(frameB, cv2.COLOR_BGR2BGRA,
                                  4).astype(np.float32)
            if mode == "difference":
                extraChannel = blend_modes.difference(frameA, frameB, 1)
            elif mode == "multiply":
                extraChannel = blend_modes.multiply(frameA, frameB, 1)
            else:
                extraChannel = np.zeros((frame_width, frame_height, 3),
                                        np.uint8)
                extraChannel = cv2.cvtColor(extraChannel, cv2.COLOR_BGR2BGRA,
                                            4).astype(np.float32)

            ## get rid of alpha channel in preparation for converting back to grayscale; opencv prefers 8bit
            frameA = cv2.cvtColor(frameA, cv2.COLOR_BGRA2BGR).astype(np.uint8)
            frameB = cv2.cvtColor(frameB, cv2.COLOR_BGRA2BGR).astype(np.uint8)
            extraChannel = cv2.cvtColor(extraChannel,
                                        cv2.COLOR_BGRA2BGR).astype(np.uint8)

            ## convert to grayscale so we can merge into 3-channel image
            frameA = cv2.cvtColor(frameA, cv2.COLOR_BGR2GRAY)
            frameB = cv2.cvtColor(frameB, cv2.COLOR_BGR2GRAY)
            extraChannel = cv2.cvtColor(extraChannel, cv2.COLOR_BGR2GRAY)

            ## merge, show and write
            merged = cv2.merge((extraChannel, frameB, frameA))
            cv2.imshow('merged', merged)
            out.write(merged)
            if cv2.waitKey(1) & 0xFF == ord('q'):
                break
        else:
            break
    capA.release()
    capB.release()
    out.release()
    cv2.destroyAllWindows()
    print("done!")
Ejemplo n.º 4
0
def make_party_gif(filename):
    print(f'Processing {filename}')
    im = Image.open(filename).convert('LA').convert('RGBA')

    basewidth = 100
    wpercent = (basewidth/float(im.size[0]))
    hsize = int((float(im.size[1])*float(wpercent)))
    im = im.resize((basewidth,hsize), Image.ANTIALIAS)

    im.putdata(replace_color_with_transaprency(im, 255, 255, 255))
    # im.putdata(replace_color_with_transaprency(im, 0, 0, 0))

    background_img = np.array(im)  # Inputs to blend_modes need to be numpy arrays.
    background_img_float = background_img.astype(float)  # Inputs to blend_modes need to be floats.

    frames = []
    for c in colours:
        layer = Image.new('RGBA', im.size, c)
        foreground_img = np.array(layer)
        foreground_img_float = foreground_img.astype(float)

        # Blend images
        opacity = 0.8
        blended_img_float = overlay(background_img_float, foreground_img_float, opacity)
        blended_img_float = multiply(blended_img_float, foreground_img_float, opacity)

        # Convert blended image back into PIL image
        blended_img = np.uint8(blended_img_float)
        blended_img_raw = Image.fromarray(blended_img)
        blended_img_raw.putdata(replace_alpha_with_white(blended_img_raw))
        frames.append(blended_img_raw)

    frames = frames + frames[::-1]

    # Save into a GIF file that loops forever
    print(f"Saving /output_data/{filename.split('/')[-1]}.gif")
    frames[0].save(
        f"/output_data/{filename.split('/')[-1]}.gif",
        format='GIF',
        append_images=frames[1:],
        save_all=True,
        duration=100,
        loop=0
    )
Ejemplo n.º 5
0
def multiply(foreground, background, mix=0.7):
    """
    Multiplies the foreground by the background.

    :param foreground:  Foreground PIL Image
    :param background:  Background PIL Image
    :param mix:         Amount of foreground that contributes
                        to the final image. Between [0.0, 1.0]
    :return:            Blended PIL Image
    """
    foreground = _conv_to_rbga(foreground)
    background = _conv_to_rbga(background)

    background, foreground = size_to_same(background, foreground)

    bkg = to_numeric(background)
    frg = to_numeric(foreground)

    raw = blend_modes.multiply(bkg, frg, mix)

    return to_pil(raw)
Ejemplo n.º 6
0
def cli(ctx, opt_dir_ims, opt_fps, opt_bitrate, opt_codec, opt_fp_out_video,
        opt_bg_color, opt_write_video, opt_cleanup):
    """Composites real and mask images, writes optional video"""

    import pandas as pd
    from glob import glob
    from pathlib import Path

    import cv2 as cv
    import numpy as np
    import blend_modes
    from moviepy.editor import VideoClip
    from tqdm import tqdm

    from app.utils import log_utils, file_utils

    log = app_cfg.LOG
    log.info('Compositing masks and synthetic 3D images')

    # init
    fps_ims_comp = []

    # glob images
    fps_ims_real = [
        im for im in glob(str(Path(opt_dir_ims) / app_cfg.DN_REAL / '*.png'))
    ]
    fps_ims_mask = [
        im for im in glob(str(Path(opt_dir_ims) / app_cfg.DN_MASK / '*.png'))
    ]
    if not len(fps_ims_mask) == len(fps_ims_real):
        print('Error: number images not same')
    print(f'found {len(fps_ims_mask)} masks, {len(fps_ims_real)} images')

    # ensure output dir
    opt_dir_ims_comp = Path(opt_dir_ims) / app_cfg.DN_COMP
    if not Path(opt_dir_ims_comp).is_dir():
        Path(opt_dir_ims_comp).mkdir(parents=True, exist_ok=True)

    # generate image sequence
    for fp_im_mask, fp_im_real in tqdm(zip(fps_ims_mask, fps_ims_real),
                                       total=len(fps_ims_real)):

        #im_mask = cv.cvtColor(cv.imread(fp_im_mask).astype(np.float32), cv.COLOR_BGR2BGRA)
        im_mask = cv.cvtColor(cv.imread(fp_im_mask),
                              cv.COLOR_BGR2BGRA).astype(np.float32)
        bg_color = np.array([0., 0., 0., 255.])  # black fill
        mask_idxs = np.all(im_mask == bg_color, axis=2)
        im_mask[mask_idxs] = [0, 0, 0, opt_bg_color]

        im_real = cv.cvtColor(cv.imread(fp_im_real),
                              cv.COLOR_BGR2BGRA).astype(np.float32)
        im_comp = blend_modes.multiply(im_real, im_mask, 0.5)
        im_comp = blend_modes.addition(im_comp, im_mask, 0.5)
        im_comp = cv.cvtColor(im_comp, cv.COLOR_BGRA2BGR)
        fp_out = Path(opt_dir_ims_comp) / Path(fp_im_mask).name
        cv.imwrite(str(fp_out), im_comp)

    if not opt_fp_out_video and opt_write_video:
        opt_fp_out_video = str(
            Path(opt_dir_ims) / f'{Path(opt_dir_ims).name}.mp4')

    if opt_fp_out_video:
        # glob comp images
        fps_ims_comp = sorted(
            [im for im in glob(str(Path(opt_dir_ims_comp) / '*.png'))])

        opt_bitrate = f'{opt_bitrate}M'  # megabits / second
        num_frames = len(fps_ims_comp)
        duration_sec = num_frames / opt_fps

        log.debug(f'num images: {len(fps_ims_comp)}')

        def make_frame(t):
            #global fps_ims_comp
            frame_idx = int(np.clip(np.round(t * opt_fps), 0, num_frames - 1))
            fp_im = fps_ims_comp[frame_idx]
            im = cv.cvtColor(cv.imread(fp_im),
                             cv.COLOR_BGR2RGB)  # Moviepy uses RGB
            return im

        log.info(f'Generating movieclip to: {opt_fp_out_video}')
        VideoClip(make_frame,
                  duration=duration_sec).write_videofile(opt_fp_out_video,
                                                         fps=opt_fps,
                                                         codec=opt_codec,
                                                         bitrate=opt_bitrate)
        log.info('Done.')

    if opt_cleanup:
        # remove all comp images
        log.info('Removing all temporary images...')
        import shutil
        shutil.rmtree(opt_dir_ims_comp)
        log.info(f'Deleted {opt_dir_ims_comp}')
Ejemplo n.º 7
0
def main():
    # Parameters
    start_time = time.time()
    L = 10  # length of a strokes
    sigma_gaussian = 10  # standard deviation >=0
    epsilon = 2  # level >=0
    random = 1000000  # set random to -1 to cross all the image

    # Read image
    img_path = get_args()
    img = cv.imread(str(img_path), cv.IMREAD_COLOR)
    img_ycrcb = cv.cvtColor(img, cv.COLOR_BGR2YCrCb)
    img_y = img_ycrcb[:, :, 0]

    # Gaussian filter
    gaussian = cv.GaussianBlur(img_y, (5, 5), sigma_gaussian)
    # Gradient
    sobel = cv.Sobel(gaussian, cv.CV_64F, 1, 1, ksize=1)

    # Initialize img_greyscale image
    height, width = sobel.shape
    img_greyscale = np.zeros((height, width), np.uint8)
    img_greyscale[:, :] = 255

    # Random position
    cpt = 0

    if random > 0:
        # pick random location
        for cpt in range(0, random + 1):
            x = np.random.randint(0, sobel.shape[0])
            y = np.random.randint(0, sobel.shape[1])
            cpt, img_greyscale = strokes(x, y, cpt, img_greyscale, sobel,
                                         epsilon, L)
            if round(((cpt - 1) / random) * 100) != round(
                (cpt / random) * 100):
                print('strokes : ' + str(random) + ' - ' +
                      str(round((cpt / random) * 100)) + ' %')
    else:
        # cross all the image
        for x in range(sobel.shape[0]):
            for y in range(sobel.shape[1]):
                cpt, img_greyscale = strokes(x, y, cpt, img_greyscale, sobel,
                                             epsilon, L)
                print('strokes : ' + str(cpt) + '/' +
                      str(sobel.shape[0] * sobel.shape[1]))

    cv.imwrite('./output/naive/img_grayscale.jpg', img_greyscale)

    # Colorisation
    # img_res = cv.GaussianBlur(img,(35,35),0)
    # for i in range(img_greyscale.shape[0]):
    #     for j in range(img_greyscale.shape[1]):
    #         if img_greyscale[i,j]<255:
    #             img_res[i,j,0] =0
    #             img_res[i, j, 1] =0
    #             img_res[i, j, 2] =0
    # cv.imwrite("./output/res_color_s_"+str(sigma_gaussian)+"_l_"+str(L)+"_e_"+str(epsilon)+".jpg", img_res)

    # Blend - https://pythonhosted.org/blend_modes/#description
    img_gaussian = cv.GaussianBlur(img, (5, 5), 0)
    img_rgba = cv.cvtColor(img_gaussian, cv.COLOR_RGB2RGBA)
    img_greyscale_rgba = cv.cvtColor(img_greyscale, cv.COLOR_RGB2RGBA)

    opacity = 0.7  # The opacity of the foreground that is blended onto the background
    img_blended = blend_modes.multiply(img_greyscale_rgba.astype(float),
                                       img_rgba.astype(float), opacity)
    cv.imwrite('./output/naive/img_res_1.jpg', img_blended)
    img_blended = blend_modes.multiply(img_rgba.astype(float),
                                       img_greyscale_rgba.astype(float),
                                       opacity)
    cv.imwrite('./output/naive/img_res_2.jpg', img_blended)
    print('time : ' + str(round(time.time() - start_time)) + ' seconds')
Ejemplo n.º 8
0
def blend_multiply(base: Image, new: Image, opacity: float = 1) -> Image:
    base_f = numpy.array(base).astype(float)
    new_f = numpy.array(new).astype(float)
    blended_f = multiply(base_f, new_f, opacity)
    return Image.fromarray(numpy.uint8(blended_f))