Esempio n. 1
0
def screenshotter():
    im = pyautogui.screenshot(region=(350, 180, 625, 370))
    im_left = im.crop((10, 210, 75, 350))
    im_right = im.crop((505, 200, 565, 315))
    im_left = im_left.rotate(-9.8)
    im_right = im_right.rotate(10)
    im_left_blurred = im_left.filter(filter=ImageFilter.BoxBlur(1))
    im_right_blurred = im_right.filter(filter=ImageFilter.BoxBlur(1))
    im.paste(im_left_blurred, (10, 210))
    im.paste(im_right_blurred, (505, 200))
    return im
Esempio n. 2
0
    def visualize(self, layer, filt, lr=1e-2, opt_steps=36):
        sz = self.size
        img = Image.fromarray(
            np.uint8(np.random.uniform(150, 180, (sz, sz, 3))))
        activations = SaveFeatures(list(self.target.children())[layer])
        gaussian_filter = get_gaussian_kernel()
        self.model.zero_grad()
        for outer in tqdm(range(self.upscaling_steps), leave=False):
            img_var = torch.unsqueeze(ToTensor()(img),
                                      0).cuda(ORDINAL).requires_grad_(True)
            img_var.requires_grad_(True).cuda(ORDINAL)
            optimizer = torch.optim.Adam([img_var], lr=lr, weight_decay=1e-6)

            pbar = tqdm(range(opt_steps), leave=False)
            for n in pbar:
                optimizer.zero_grad()
                self.model(img_var)
                loss = -activations.features[
                    0, filt].mean() + 0.00 * torch.norm(img_var)
                loss.backward()
                pbar.set_description(f'Loss: {loss.item()}')
                optimizer.step()

            sz = int(sz * self.upscaling_factor)
            img = ToPILImage()(img_var.squeeze(0))
            if outer != self.upscaling_steps:
                img = img.resize((sz, sz))
                img = img.filter(ImageFilter.BoxBlur(2))
            self.output = img.copy()
        self.save(layer, filt)
        activations.close()
Esempio n. 3
0
async def box_blur(client, message):
    try:
        userid = str(message.chat.id)
        if not os.path.isdir(f"./DOWNLOADS/{userid}"):
            os.makedirs(f"./DOWNLOADS/{userid}")
        download_location = "./DOWNLOADS" + "/" + userid + "/" + userid + ".jpg"
        if not message.reply_to_message.empty:
            msg = await message.reply_to_message.reply_text(
                "Downloading image", quote=True)
            a = await client.download_media(message=message.reply_to_message,
                                            file_name=download_location)
            await msg.edit("Processing Image...")
            im1 = Image.open(a)
            im2 = im1.filter(ImageFilter.BoxBlur(0))
            edit_img_loc = "./DOWNLOADS" + "/" + userid + "/" + "box_blur.jpg"
            im2.save(edit_img_loc)
            await message.reply_chat_action("upload_photo")
            await message.reply_to_message.reply_photo(edit_img_loc,
                                                       quote=True)
            await msg.delete()
        else:
            await message.reply_text("Why did you delete that??")
        try:
            shutil.rmtree(f"./DOWNLOADS/{userid}")
        except Exception:
            pass
    except Exception as e:
        print("box_blur-error - " + str(e))
        if "USER_IS_BLOCKED" in str(e):
            return
        try:
            await message.reply_to_message.reply_text("Something went wrong!",
                                                      quote=True)
        except Exception:
            return
Esempio n. 4
0
    def transform(self, frame):
        frame = frame.resize((self._width, self._height), Image.BILINEAR)
        frame = frame.rotate(self._rotation, Image.BILINEAR)

        if self._blur_in_frames > 0 and self._count_frame_total < self._blur_in_frames and not self._deinit_started:
            strength = int((self._blur_in_frames - self._count_frame_total) *
                           10 / self._blur_in_frames)
            frame = frame.filter(ImageFilter.BoxBlur(strength))

        if self.blur_out_frames > 0 and self._deinit_started:
            strength = 10 - int(
                (self._blur_out_frames - self._count_frame_total) * 10 /
                self.blur_out_frames)
            frame = frame.filter(ImageFilter.BoxBlur(strength))

        return frame
Esempio n. 5
0
    def save(self, *args, **kwargs):
        super().save(*args, **kwargs)
        # Load Image from File
        img_read = storage.open(self.img.name, 'rb')
        img = Image.open(img_read)

        # Convert Image to Array
        pixels = asarray(img)
        # Create the Detector Using the Default Weights
        detector = MTCNN()
        # Detect Faces in the Image
        results = detector.detect_faces(pixels)
        numfaces = len(results)
        # Create For Loop to Blur All Faces in Photo
        for i in range(numfaces):
            # Extract the Bounding Box from the First Face
            x1, y1, width, height = results[i]['box']
            # Negative Coordinates Bug Fix
            x1, y1 = abs(x1), abs(y1)
            x2, y2 = x1 + width, y1 + height
            # Extract the Face
            face = pixels[y1:y2, x1:x2]
            # Blur Out Face Pixels
            faceimage = Image.fromarray(face)
            faceimage = faceimage.filter(ImageFilter.BoxBlur(radius=100))
            # Reattach Blurred Faces to Original Photo
            img = img.copy()
            img.paste(faceimage, (x1, y1))
        # Show the New Image
        # image.show()
        # Save the New Image
        in_mem_file = io.BytesIO()
        img.save(in_mem_file, format='JPEG')
Esempio n. 6
0
    def __getitem__(self, idx):

        img_number = np.random.randint(0, high=len(self.imgs))
        x_coord = np.random.randint(0, high=self.x_dim - self.patch_size)
        y_coord = np.random.randint(0, high=self.y_dim - self.patch_size)

        if self.num_modalities > 1:
            seed = np.random.randint(2147483647)
            I_list = []
            for m in self.modalities:
                random.seed(seed)
                I = Image.open(
                    os.path.join(self.data_dir, m, self.imgs[img_number]))
                I_list.append(
                    self.transformation(
                        I.crop((x_coord, y_coord, x_coord + self.patch_size,
                                y_coord + self.patch_size))))
            patch = torch.cat(I_list, dim=0)

        else:
            I = Image.open(os.path.join(
                self.data_dir, self.imgs[img_number])).convert(mode='L')

            if self.binary_data:
                I = I.filter(ImageFilter.BoxBlur(1))

            patch = self.transformation(
                I.crop((x_coord, y_coord, x_coord + self.patch_size,
                        y_coord + self.patch_size)))
            if self.binary_data:  # clamp values away from boundaries if binarized data
                patch = torch.clamp(patch, -0.35, 0.25)

        return patch, torch.ones((1))
Esempio n. 7
0
def upload_image_swarm(file: FileStorage, username: str,
                       is_public) -> (str, str):
    image_format = DICTIONARY_FORMAT[secure_filename(
        file.filename).split('.')[-1].lower()]
    url = SWARM_URL_NODE
    if is_public:
        headers = {"content-type": f"image/{image_format}"}
    else:
        headers = {
            "content-type": f"image/{image_format}",
            "Swarm-Encrypt": "true"
        }
    result = requests.post(url, data=file, headers=headers)
    # swarm_hash = json.loads(result.content.decode('utf8'))["reference"]
    swarm_hash = result.content.decode('utf8')
    image = Image.open(file)
    output = io.BytesIO()
    image.save(output, format=image_format)
    hex_data = output.getvalue()
    blob_client = BlobClient.from_connection_string(
        BLOB_CONNECTION_STRING, IMAGES_CONTAINER,
        f"{username.lower()}/{swarm_hash}.{image_format}")
    blob_client.upload_blob(hex_data, overwrite=True)
    blurry_image = Image.open(file).filter(ImageFilter.BoxBlur(30))
    blurry_output = io.BytesIO()
    blurry_image.save(blurry_output, format=image_format)
    blurry_hex_data = blurry_output.getvalue()
    blurry_blob_client = BlobClient.from_connection_string(
        BLOB_CONNECTION_STRING, BLURRY_IMAGES_CONTAINER,
        f"{username.lower()}/{swarm_hash}.{image_format}")
    blurry_blob_client.upload_blob(blurry_hex_data, overwrite=True)
    return swarm_hash
Esempio n. 8
0
def box_blur(image, *params):
    global box_blur_radius
    if (not box_blur_radius):
        box_blur_radius = 0
    box_blur_radius += 2
    print("From box blur")
    return image.filter(ImageFilter.BoxBlur(box_blur_radius))
Esempio n. 9
0
    def blurFaces(self):
        for top, right, bottom, left in self.faceLocations:
            faceImage = self.image[top:bottom, left:right]
            faceImage = Image.fromarray(faceImage)
            faceImage = faceImage.filter(ImageFilter.BoxBlur(23))

            self.image[top:bottom, left:right] = faceImage
Esempio n. 10
0
def edit_image(img, width, height):
    x, y = img.size
    temp = img.resize((width, height), Image.ANTIALIAS)
    temp = temp.filter(ImageFilter.BoxBlur(9))
    enhancer = ImageEnhance.Color(temp)
    temp = enhancer.enhance(.3)
    print('baground size : ', temp.size)
    print('required size : ', width, height)

    w_dif = x - width
    h_dif = y - height
    print('width diff : ', x - width, 'height diff : ', y - height)
    temp2 = temp
    if w_dif < h_dif:
        new_width = int(x / (y / height))
        print('new_width : ', new_width)
        temp2 = img.resize((new_width, height), Image.ANTIALIAS)
    else:
        new_height = int(y / (x / width))
        print('new_height : ', new_height)
        temp2 = img.resize((width, new_height), Image.ANTIALIAS)

    #print('temp = ',temp.size)
    #print('temp2 = ',temp2.size)
    img_w, img_h = temp2.size
    print('after editing size of image : ', temp2.size)
    offset = ((width - img_w) // 2, (height - img_h) // 2)
    temp.paste(temp2, offset)
    return temp
Esempio n. 11
0
def create_classifications(s3, folder, image_name, polygons, border, inside,
                           outside, window_width, window_height):
    im = Image.open(folder + "/" + image_name)
    im = im.filter(ImageFilter.BoxBlur(1))
    px = im.load()
    width, height = im.size
    dim = len(px[0, 0])
    assert (dim == 3)
    increment = 5  # Don't need to use every pixel

    for i in range(0, height * width, increment):
        y = math.floor(i / width)
        x = i % width
        [r, g, b] = px[x, y]
        window = create_window(px, x, y, window_width, window_height, width,
                               height)
        if len(polygons) == 0:
            write(outside, window, OUTSIDE)
        else:
            found = False
            for polygon in polygons:
                if on_border(polygon, x, y):
                    write(border, window, BORDER)
                    found = True
                    break
                elif in_polygon(polygon, x, y):
                    write(inside, window, INSIDE)
                    found = True
            if not found:
                write(outside, window, OUTSIDE)
Esempio n. 12
0
    def test_sanity(self):

        def filter(filter):
            for mode in ["L", "RGB", "CMYK"]:
                im = hopper(mode)
                out = im.filter(filter)
                self.assertEqual(out.mode, im.mode)
                self.assertEqual(out.size, im.size)

        filter(ImageFilter.BLUR)
        filter(ImageFilter.CONTOUR)
        filter(ImageFilter.DETAIL)
        filter(ImageFilter.EDGE_ENHANCE)
        filter(ImageFilter.EDGE_ENHANCE_MORE)
        filter(ImageFilter.EMBOSS)
        filter(ImageFilter.FIND_EDGES)
        filter(ImageFilter.SMOOTH)
        filter(ImageFilter.SMOOTH_MORE)
        filter(ImageFilter.SHARPEN)
        filter(ImageFilter.MaxFilter)
        filter(ImageFilter.MedianFilter)
        filter(ImageFilter.MinFilter)
        filter(ImageFilter.ModeFilter)
        filter(ImageFilter.GaussianBlur)
        filter(ImageFilter.GaussianBlur(5))
        filter(ImageFilter.BoxBlur(5))
        filter(ImageFilter.UnsharpMask)
        filter(ImageFilter.UnsharpMask(10))

        self.assertRaises(TypeError, filter, "hello")
    def add_random_alpha_variation(self, image: Image.Image) -> Image.Image:
        """
        Randomly changes the alpha value of the image by applying a blur and max filter to a randomized array
        and setting the result array as new alpha channel
        
        # Arguments
            image: Image. the image to augment
            
        # Returns
            Image. the augmented image
        """

        if image.mode == "L":  # skip mask images
            return image

        img_array = np.array(image.convert('RGBA'))
        rand_alpha_array = np.random.randint(0, 255, img_array.shape[:2])

        rand_alpha_img = Image.fromarray(rand_alpha_array, mode='L')
        rand_alpha_img = rand_alpha_img.filter(ImageFilter.MaxFilter(self.max_filter_size))\
            .filter(ImageFilter.BoxBlur(self.blur_size))

        new_alpha_array = np.rint(img_array[:, :, 3] *
                                  (np.asarray(rand_alpha_img) / 255))
        img_array[:, :, 3] = new_alpha_array

        return Image.fromarray(img_array, mode='RGBA')
Esempio n. 14
0
def test_sanity():
    def apply_filter(filter_to_apply):
        for mode in ["L", "RGB", "CMYK"]:
            im = hopper(mode)
            out = im.filter(filter_to_apply)
            assert out.mode == im.mode
            assert out.size == im.size

    apply_filter(ImageFilter.BLUR)
    apply_filter(ImageFilter.CONTOUR)
    apply_filter(ImageFilter.DETAIL)
    apply_filter(ImageFilter.EDGE_ENHANCE)
    apply_filter(ImageFilter.EDGE_ENHANCE_MORE)
    apply_filter(ImageFilter.EMBOSS)
    apply_filter(ImageFilter.FIND_EDGES)
    apply_filter(ImageFilter.SMOOTH)
    apply_filter(ImageFilter.SMOOTH_MORE)
    apply_filter(ImageFilter.SHARPEN)
    apply_filter(ImageFilter.MaxFilter)
    apply_filter(ImageFilter.MedianFilter)
    apply_filter(ImageFilter.MinFilter)
    apply_filter(ImageFilter.ModeFilter)
    apply_filter(ImageFilter.GaussianBlur)
    apply_filter(ImageFilter.GaussianBlur(5))
    apply_filter(ImageFilter.BoxBlur(5))
    apply_filter(ImageFilter.UnsharpMask)
    apply_filter(ImageFilter.UnsharpMask(10))

    with pytest.raises(TypeError):
        apply_filter("hello")
Esempio n. 15
0
def output_mobile_images(image_file, destination, percent_viewport, quality):
    widths = [math.ceil(w * (percent_viewport / 100.0)) \
        for w in MOBILE_FULL_WIDTHS_TO_TARGET]

    with Image.open(image_file) as image:
        ratio = image.height / float(image.width)

        for width in widths:
            resized = image.resize((width, round(width * ratio)),
                                   resample=Image.LANCZOS)
            # For example: some/path/mansfield.jpg => mansfield_1440.jpg
            filename = os.path.splitext(os.path.basename(image_file))[0] + \
                "-" + str(width) + ".jpg"
            save_to = os.path.join(destination, filename)
            resized.save(save_to, "jpeg", quality=quality, optimize=True)

        # Save a placeholder for lazy loading images.
        placeholder_width = widths[-1] // 2
        resized_for_placeholder = image.resize(
            (placeholder_width, round(placeholder_width * ratio)),
            resample=Image.LANCZOS)
        placeholder = resized_for_placeholder.filter(ImageFilter.BoxBlur(3))
        filename = os.path.splitext(os.path.basename(image_file))[0] + \
            "-placeholder.jpg"
        save_to = os.path.join(destination, filename)
        placeholder.save(save_to, "jpeg", quality=quality, optimize=True)
Esempio n. 16
0
def save_bblur():
    if request.method == "POST":
        image_src = 'static/uploads/img.png'
        im = Image.open(image_src)
        radius = int(request.get_data())
        im = im.filter(ImageFilter.BoxBlur(radius))
        im.save('static/uploads/img.png')
Esempio n. 17
0
def show_box_blur(filename, r=1):
  original = Image.open(os.path.join(INPUT_DIR, filename))
  filtered = original.filter(ImageFilter.BoxBlur(r))
    #show image side-by-side
  show_horizontal(original, filtered)
  filtered.save(
    os.path.join(OUTPUT_DIR, '{}_boxblur_{}.jpg'.format(filename[:filename.index('.' ), r] ) )
   )
Esempio n. 18
0
 def addBlur(self, pic: Image.Image):
     if self.settings["GaussianBlurRadius"]:
         pic = pic.filter(
             ImageFilter.GaussianBlur(self.settings["GaussianBlurRadius"]))
     if self.settings["BoxBlurRadiux"]:
         pic = pic.filter(
             ImageFilter.BoxBlur(self.settings["BoxBlurRadiux"]))
     return pic
Esempio n. 19
0
def NF_instance(parameter_blur, parameter_size):
    boxImage = OriImage.filter(ImageFilter.BoxBlur(parameter_blur))
    resizedImage = boxImage.resize(
        [int(parameter_size * s) for s in boxImage.size])
    mode = resizedImage.mode
    data = resizedImage.tobytes()
    size = resizedImage.size
    return data, size, mode
Esempio n. 20
0
def blur_and_print_image(image_full, image_name, output_path):
    file, ext = os.path.splitext(image_full)
    abrev_name, ext = os.path.splitext(image_name)
    image = PI.open(image_full)
    blur_ammount = random.randint(20, 60)
    image_blurred = image.filter(ImageFilter.BoxBlur(blur_ammount))
    image_blurred_final = image_blurred.filter(ImageFilter.DETAIL)
    print('File Made: ' + output_path + '/' + abrev_name + ".jpeg")
    image_blurred_final.save(output_path + '/' + abrev_name + ".jpeg", "JPEG")
Esempio n. 21
0
    def test_box_filter(self):
        for radius in range(6):
            pil_image = self.load_image(self.backends["PIL"])
            pil_image = pil_image.filter(ImageFilter.BoxBlur(radius))

            torchvision_image = self.load_image(self.backends["torchvision"])
            torchvision_image = tif.box_blur(torchvision_image, radius)

            self.assertImagesAlmostEqual(pil_image, torchvision_image)
Esempio n. 22
0
def vhstext(image,
            pos=(0, 0),
            text="PLAY",
            fill=0xffffff,
            shadow=None,
            shadowradius=3,
            shadowfactor=5.0,
            size=12,
            align=C):
    image = image.convert("RGBA")
    fnt = font.font_variant(size=size)
    text_layer = Image.new("RGBA", image.size)
    shadow_layer = text_layer.copy()
    text_draw = ImageDraw.Draw(text_layer)

    if isinstance(fill, int):
        fill = "#%.6x" % fill
    if isinstance(shadow, int):
        shadow = "#%.6x" % shadow

    text_w, text_h = text_draw.textsize(text, font=fnt)
    if align == L:
        real_pos = (pos[0], pos[1])
    if align == C:
        real_pos = (pos[0] - text_w // 2, pos[1])
    if align == R:
        real_pos = (pos[0] - text_w, pos[1])
    text_draw.multiline_text(real_pos, text, fill=fill, font=fnt, align=align)

    if shadow is not None:
        radius = shadowradius
        fil = ImageFilter.BoxBlur(radius)
        shadow_bbox = (text_w + radius * 2, text_h + radius * 2)
        if align == L:
            outpos = (pos[0] - radius, pos[1] - radius)
        if align == C:
            outpos = (pos[0] - shadow_bbox[0] // 2, pos[1] - radius)
        if align == R:
            outpos = (pos[0] - shadow_bbox[0] + radius, pos[1] - radius)

        shadow_box = Image.new("RGBA", shadow_bbox)
        shadow_draw = ImageDraw.Draw(shadow_box)
        shadow_draw.multiline_text((radius, radius),
                                   text,
                                   fill=shadow,
                                   font=fnt,
                                   align=align)
        shadow_box = shadow_box.filter(fil)
        chans = list(shadow_box.split())
        chans[3] = ImageEnhance.Brightness(chans[3]).enhance(shadowfactor)
        shadow_box = Image.merge("RGBA", chans)
        shadow_layer.paste(shadow_box, outpos)

    text_with_shadow = Image.alpha_composite(shadow_layer, text_layer)
    image = Image.alpha_composite(image, text_with_shadow)

    return image.convert("RGB")
Esempio n. 23
0
def do_work(parsed_image: dict,
            image_filename='image.jpg',
            metadata_filename='meta.json',
            path=Path(Path.home(), Path('.bing-desk'))):
    """Does the work"""
    image_path = Path(path, Path(image_filename))
    split_image_path = os.path.splitext(image_path)

    if BLUR and path.is_dir():
        blurred_image_path = Path(split_image_path[0] + '_blur' +
                                  split_image_path[1])
        if blurred_image_path.is_file():
            set_wallpaper(blurred_image_path)

    if HIRES:
        image = get_high_res(parsed_image)
    else:
        image = Image.open(BytesIO(r.get(parsed_image['image']).content))

    if not isinstance(path, Path):
        path = Path(path)
    if not path.is_dir():
        path.mkdir(parents=True, exist_ok=True)
        if WINDOWS:
            win.kernel32.SetFileAttributesW(str(path), 0x02)

    if BLUR:  # Excessive, but I like it
        blurred_image = image.filter(ImageFilter.BoxBlur(radius=4)).filter(
            ImageFilter.BoxBlur(radius=4))
        blurred_image.save(str(blurred_image_path))
        set_wallpaper(blurred_image_path)
        time.sleep(.5)

    image.save(str(image_path))

    metadata_path = Path(path, Path(metadata_filename))
    parsed_image.update({'fetched': str(datetime.now())})
    with metadata_path.open('wb') as file:
        file.write(json.dumps(parsed_image, ensure_ascii=False).encode('utf8'))

    set_wallpaper(image_path)

    return image_path, metadata_path
Esempio n. 24
0
def glowFx(image, radius=0, brt=1.5):
    if radius > 0:
        base = image.copy()
        image = image.filter(ImageFilter.BoxBlur(radius=radius))
        enhancer = ImageEnhance.Brightness(image)
        image = enhancer.enhance(brt)
        base.paste(image, (0, 0), image)
        return base
    else:
        return image
def test_main(xvfb, fs_with_data):
    main()

    # load and convert to gray
    # reference
    img_ref = Image.open("data/sitting.png").convert('LA')
    # compute/render image
    img_result = Image.open("output.png").convert('LA')

    # using blur (box or gaussian) for reducing the antialiasing differentiation
    img_ref = img_ref.filter(ImageFilter.BoxBlur(radius=4))
    img_result = img_result.filter(ImageFilter.BoxBlur(radius=4))

    diff = ImageChops.difference(img_ref, img_result)
    # evaluate difference with some energy quantification
    # not very precise and/or accurate, but enough for utest purpose
    max_energy = compute_energy(img_ref)
    diff_energy = compute_energy(diff)
    coef_error = diff_energy / max_energy
    assert coef_error <= 1e-3
Esempio n. 26
0
 def blurImage(self):
     text = self.blurRadius.text()
     if text and text.isnumeric() and self.img_pixmap:
         radius = int(text)
         if radius == 0:
             self.img_pixmap = self.img_pixmap_orig
         else:
             img = Image.fromqpixmap(self.img_pixmap)
             img = img.filter(ImageFilter.BoxBlur(radius))
             self.img_pixmap = img.toqpixmap()
         self.notifyImageChange()
def show_box_blur(filename, r=1):
    '''Aplica um filtro BoxBlur à imagem, exibe e salva o resultado'''

    original = Image.open(in_file(filename))
    filtered = original.filter(ImageFilter.BoxBlur(r))

    #Mostrar as imagens lado a lado
    show_horizontal(original, filtered)
    filtered.save(
        out_file('{}_boxblur_{}.jpg'.format(filename[:filename.index('.')],
                                            r)))
Esempio n. 28
0
def face_gaussian_blur(image, image_cv, radius=20):
	face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
	gray_image_cv = cv2.cvtColor(image_cv, cv2.COLOR_BGR2GRAY)
	faces = face_cascade.detectMultiScale(gray_image_cv, 1.1, 4)
	new_image = image
	for (x, y, w, h) in faces:
		box = (x, y, x+w, y+h)
		cropped_image = image.crop(box)
		cropped_image = cropped_image.filter(ImageFilter.BoxBlur(radius))
		new_image.paste(cropped_image, box)
	return new_image
Esempio n. 29
0
    def __call__(self, image):
        '''
            Arguments:
            image (numpy array or PIL Image)

            Returns:
            image (numpy array or PIL Image)
        '''
        img = Image.fromarray(image)
        img = img.filter(ImageFilter.BoxBlur(self.radius))
        return (np.array(img))
def applyBlurPG(img_path,blur_radius,blur_type):
    sharpimg = load_imgRGB(img_path)
    blurredimg=[]
    if blur_type is 'avg':
        blurredimg = sharpimg.filter(ImageFilter.BoxBlur(radius=blur_radius))
    elif blur_type is 'gaus':
        blurredimg = sharpimg.filter(ImageFilter.GaussianBlur(radius=blur_radius))
    else:
        raise ValueError("Unknown blur type. Please check the blur options in applyBlurPG function")
        return 0
    return sharpimg,blurredimg