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

    # Extract specific number of key frames from video
    img_module = Image()

    # folder to save extracted images
    output_folder_cropped_image = "resizedimages"

    if not os.path.isdir(os.path.join(".", output_folder_cropped_image)):
        os.mkdir(os.path.join(".", output_folder_cropped_image))

    # crop dimentions
    resize_width = 500
    resize_height = 600

    # Image file path
    image_file_path = os.path.join(".", "tests", "data",
                                   "bird_img_for_crop.jpg")
    print(f"image_file_path = {image_file_path}")

    resized_image = img_module.resize_image(
        file_path=image_file_path,
        target_width=resize_width,
        target_height=resize_height,
        down_sample_factor=8,
    )
    # cv2.imshow("resizedImage", resized_image)
    # cv2.waitKey(0)

    img_module.save_image_to_disk(
        resized_image,
        file_path=output_folder_cropped_image,
        file_name="resized_image",
        file_ext=".jpeg",
    )
Пример #2
0
def main():

    img_module = Image()

    # folder to save resized images
    output_folder_resized_image = "resizedimages"

    if not os.path.isdir(os.path.join(".", output_folder_resized_image)):
        os.mkdir(os.path.join(".", output_folder_resized_image))

    # resized image dimensions
    resize_width = 500
    resize_height = 600

    # Input folder file path
    input_folder_path = os.path.join(".", "tests", "data")
    print(f"input_folder_path = {input_folder_path}")

    resized_images = img_module.resize_image_from_dir(
        dir_path=input_folder_path,
        target_width=resize_width,
        target_height=resize_height,
        down_sample_factor=8,
    )

    for filepath, resized_image in resized_images.items():
        # name of the image file
        filename = ntpath.basename(filepath)
        name = filename.split(".")[0]
        # folder path where the images will be stored
        img_module.save_image_to_disk(resized_image,
                                      output_folder_resized_image,
                                      name + "_resized" + "_", ".jpeg")
Пример #3
0
def image_object():
    """fixture for image object
    
    Returns:
        Image -- an instantiated Image object
    """
    from Katna.image import Image

    return Image()
Пример #4
0
    def _poster(self):
        """Create a poster sized crop of the thumbnail"""
        import cv2
        from Katna.image import Image

        img = Image()

        def _do_crop(_filter):
            _crop = img.crop_image_with_aspect(
                file_path=fanart_file,
                crop_aspect_ratio=self.poster_aspect_ratio,
                num_of_crops=1,
                filters=_filter,
                down_sample_factor=4,
            )
            return _crop

        fanart_file = f"{self.working_path}/{self.fanart_filename}.{self.fanart_format}"
        logger.debug(f"Creating a poster from {fanart_file}.")
        crop = _do_crop(["text"])
        if len(crop) == 0:
            logger.debug(
                "Unable to find a good crop with the text filter. Cropping without a filter."
            )
            crop = _do_crop([])
        poster = cv2.imread(fanart_file)
        logger.debug(f'WORKING PATH: {str(str(self.working_path) + "/")}')
        logger.debug(f"POSTER FILENAME: {self.poster_filename}")
        logger.debug(f"POSTER FORMAT: {self.poster_format}")
        img.save_crop_to_disk(
            crop[0],
            poster,
            file_path=str(str(self.working_path) + "/"),
            file_name=self.poster_filename,
            file_ext=f".{self.poster_format}",
        )
        return True
Пример #5
0
def main():

    # Extract specific number of key frames from video
    img_module = Image()

    # folder to save extracted images
    output_folder_cropped_image = "selectedcrops"

    if not os.path.isdir(os.path.join(".", output_folder_cropped_image)):
        os.mkdir(os.path.join(".", output_folder_cropped_image))

    # number of images to be returned
    no_of_crops_to_returned = 3

    # crop dimentions
    crop_width = 1100
    crop_height = 600
    crop_aspect_ratio = "4:3"

    # Filters
    filters = ["text"]
    # Image file path
    image_file_path = os.path.join(".", "tests", "data",
                                   "bird_img_for_crop.jpg")
    print(f"image_file_path = {image_file_path}")

    # crop_image_with_aspect(
    #     self, file_path, crop_aspect_ratio, num_of_crops, filters=[], down_sample_factor=8
    # )

    crop_list = img_module.crop_image_with_aspect(
        file_path=image_file_path,
        crop_aspect_ratio=crop_aspect_ratio,
        num_of_crops=no_of_crops_to_returned,
        filters=filters,
        down_sample_factor=8,
    )
    # im = cv2.imread(image_file_path)
    # print(im.shape)
    # crop_list = img_module.crop_image(
    #     file_path=image_file_path,
    #     crop_width=crop_width,
    #     crop_height=crop_height,
    #     num_of_crops=no_of_crops_to_returned,
    #     filters=filters,
    #     down_sample_factor=8
    # )
    # print(crop_list)
    if len(crop_list) > 0:
        img = cv2.imread(image_file_path)
        for counter, crop in enumerate(crop_list):
            img_module.save_crop_to_disk(
                crop,
                img,
                file_path=output_folder_cropped_image,
                file_name="cropped_image_" + str(counter),
                file_ext=".jpeg",
            )
        # print("Top Crop Corrected", top_crop, top_crop.score)

    else:
        print("No Perfect crop found for {0}x{1} with for Image {2}".format(
            crop_width, crop_height, image_file_path))
Пример #6
0
def process(src, dest, target_res=(1280, 800), max_crop_aspect_delta=0.2, inpaint=False):
    global kimage

    img = Image.open(src)
    img = ImageOps.exif_transpose(img)

    target_w, target_h = target_res
    source_w, source_h = img.width, img.height

    target_aspect = target_w/target_h
    source_aspect = source_w/source_h

    blur_radius = max(target_w, target_h) * .05 

    target = Image.new('RGB', (target_w, target_h), (0, 0, 0))

    if target_aspect > source_aspect:
        # Source is taller than target
        fitted_scale = target_h / source_h
        fitted_w = round(source_w * fitted_scale)
        fitted_h = target_h
        
        filled_scale = target_w / source_w
        filled_w = target_w
        filled_h = round(source_h * filled_scale)
    else:
        # Source is wider than target
        fitted_scale = target_w / source_w
        fitted_w = target_w
        fitted_h = round(source_h * fitted_scale)

        filled_scale = target_h / source_h
        filled_w = round(source_w * filled_scale)
        filled_h = target_h

    image_pasted = False

    if target_aspect * (1 - max_crop_aspect_delta) <= source_aspect <= target_aspect * (1 + max_crop_aspect_delta):
        log.debug(
            f"Source aspect ratio of {source_aspect:.2f} is within {max_crop_aspect_delta:.1%} "
            f"of target aspect ratio {target_aspect:.2f}; using Katna to find best crop"
        )
        # Aspect ratio difference is OK; try smart crop
        if kimage is None:
            kimage = KImage()
        filled = img.resize((filled_w, filled_h), Image.ANTIALIAS)
        crop_list = kimage.crop_image_from_cvimage(
            input_image=pillow_rgb_to_opencv(filled), crop_width=target_w, crop_height=target_h, num_of_crops=1, down_sample_factor=4
        )

        if len(crop_list) > 0:
            crop = crop_list[0]
            x, y = crop.x, crop.y
            log.debug(f"Katna found crop of source {filled_w}x{filled_h} to {x},{y}+{target_w},{target_h}")
            if x + target_w > filled_w:
                x = filled_w - target_w
            if x < 0: x = 0
            if y + target_h > filled_h:
                y = filled_h - target_h
            if y < 0:
                y = 0
            target.paste(filled, (-x, -y))
            image_pasted = True
        else:
            log.warning("Katna found no appropriate crop")

    if not image_pasted:
        log.debug("Fitting image to frame")
        # As final solution, just paste in the middle of the target
        fitted = img.resize((fitted_w, fitted_h), Image.ANTIALIAS)
        x_pos, y_pos = round((target_w - fitted_w) / 2), round((target_h - fitted_h) / 2)
        target.paste(fitted, (x_pos, y_pos))

        if inpaint:
            # Create a stretched blurred version to give the inpainting algorithm some edges to work towards,
            # otherwise it will always fade to solid grey towards the edges. This is especially noticeable
            # in photos with a solid background that is far from black.
            # We don't fully stretch the image to the target aspect ratio, but we also don't leave it
            # as-is; we keep 20% of the original aspect ratio. This finds a bit of a middle ground
            # between keeping sky and ground colors (pure stretching would do this perfectly) and
            # creating large straight (horizontal/vertical) lines in the result (which pure zooming
            # would result in)
            zoom_w, zoom_h = round(filled_w * .2 + target_w * .8), round(filled_h * .2 + target_w * .8)
            zoom_crop_x, zoom_crop_y = round((zoom_w - target_w)/2), round((zoom_h - target_h)/2)
            target = img\
                    .resize((zoom_w, zoom_h), Image.ANTIALIAS)\
                    .filter(ImageFilter.GaussianBlur(round(target_w * 0.02)))\
                    .crop((zoom_crop_x, zoom_crop_y, zoom_crop_x + target_w, zoom_crop_y + target_h))
            target.paste(fitted, (x_pos, y_pos))

            # Mark everything but the original image and a 1 pixel wide edge all around (containing the 
            # stretched blurred version we created above) for inpainting.
            mask = np.full((target_w, target_h), fill_value=1, dtype=np.uint8)
            mask[x_pos:x_pos+fitted_w, y_pos:y_pos + fitted_h] = 0
            mask[0,:] = 0
            mask[target_w-1,:] = 0
            mask[:,0] = 0
            mask[:,target_h-1] = 0

            # Do the inpainting
            target = opencv_to_pillow(cv2.inpaint(pillow_rgb_to_opencv(target), mask.T, 3, cv2.INPAINT_TELEA))

            # Blur the inpainting result; we're not getting nor looking for a pixel-perfect continuation of the
            # image, just some soft filler for the edge that doesn't contrast too much with the original
            # scaled-down image in the center.
            target = target.filter(ImageFilter.GaussianBlur(round(target_w * 0.05)))

            # Paste the original (scaled) image in the center.
            target.paste(fitted, (x_pos, y_pos))

    target.save(dest, "JPEG", quality=85)
Пример #7
0
from Katna.image import Image as KatnaImage
from PIL import Image
import os
import matplotlib.pyplot as plt

img = KatnaImage()




import cv2
import numpy as np

import cv2
import numpy as np

'''
# Load image, convert to grayscale, Gaussian blur, Otsu's threshold
image = cv2.imread('wideShot.jpg')
original = image.copy()
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
blur = cv2.GaussianBlur(gray, (3,3), 0)
thresh = cv2.threshold(blur, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)[1]

# Obtain bounding rectangle and extract ROI
x,y,w,h = cv2.boundingRect(thresh)
cv2.rectangle(image, (x, y), (x + w, y + h), (36,255,12), 2)
ROI = original[y:y+h, x:x+w]

# Add alpha channel
b,g,r = cv2.split(ROI)
Пример #8
0
from os import path
from cv2 import cv2
from Katna.image import Image
from glob import glob
import operator
from PIL import Image as pil
from util import conf
from util.log_it import get_logger

logger = get_logger(__name__)

img_module = Image()

thumbnail_height = 180
thumbnail_width = 360

banner_ratios = ['%d:1' % width for width in range(3, 7)]
thumbnail_ratios = ['4:3', '5:3']

movie_thumbnails = ['fanart.jpg']

movie_thumbnail_order = [
    'clearart.png', 'logo.png', 'folder.jpg', 'poster.jpg', 'disc.png'
]

movie_banners = ['logo.png']

movie_banner_order = ['fanart.jpg', 'folder.jpg', 'poster.jpg', 'disc.png']

show_thumbnails = ['fanart.jpg']
show_thumbnail_order = [