Example #1
0
    def resize_if_needed(self):
        if self.before_pic and not self.before_pic_resized:
            thumb = utils.create_thumbnail(self.before_pic.file)
            fn = utils.create_thumbnail_name(self.before_pic.name)
            self.before_pic_resized.save(fn, thumb)

        if self.after_pic and not self.after_pic_resized:
            thumb = utils.create_thumbnail(self.after_pic.file)
            fn = utils.create_thumbnail_name(self.after_pic.name)
            self.after_pic_resized.save(fn, thumb)
Example #2
0
 def create_thumbnail(self, size=(500, 333)):
     _, thumbnail_filename = create_thumbnail(self.fullpath, size)
     folder, filename = os.path.split(thumbnail_filename)
     thumbnail = Thumbnail(image_id=self.id,
                           width=size[0],
                           height=size[1],
                           folder=folder,
                           filename=filename)
     object_session(self).add(thumbnail)
     object_session(self).commit()
Example #3
0
 def create_thumbnail(self, size=(500, 333)):
     _, thumbnail_filename = create_thumbnail(self.fullpath, size)
     folder, filename = os.path.split(thumbnail_filename)
     thumbnail = Thumbnail(
         image_id=self.id, 
         width=size[0], 
         height=size[1], 
         folder=folder, 
         filename=filename
     )
     object_session(self).add(thumbnail)
     object_session(self).commit()
Example #4
0
def save_and_get_text(files):
    """
    Save image, perform ocr, save result to mongo
    :param files:
    :return:
    """

    print files
    text = []
    times = []
    filenames = []
    first_image = None
    storage = GoogleCloudStorage()

    for i, file in enumerate(files):

        # Check if the file is one of the allowed types/extensions
        if file and allowed_file(file.filename):

            start_time = time.time()

            # Make the filename safe, remove unsupported chars
            filename = unique_filename(file.filename)
            filenames.append(filename)

            # Image object
            img = Image.open(file)

            # Perform ocr to get text
            result = perform_ocr(img)
            text.append(result)

            # Save file to temporary folder
            filepath = os.path.join(app.config['UPLOAD_FOLDER'], filename)
            img.convert('RGB').save(filepath, optimize=True, quality=85)

            if i == 0:
                first_image = img
            else:
                img.close()

            # Save file to Cloud Storage
            storage.upload_to_cloud_storage(filepath)

            # Delete tmp file
            delete_file(filename)

            # Get time delta in seconds
            end_time = time.time()
            times.append(end_time - start_time)

    if first_image is None:
        return "", []

    # Join in unique text
    text = "\n".join(text)

    # Create thumbnail of first image
    thumbnail = create_thumbnail(first_image)
    first_image.close()

    # Save to mongo
    save_history(text, thumbnail, filenames)

    return text, times
Example #5
0
                import traceback; traceback.print_exc()
                f=file(fname, "w+b")
                f.write(output.read())
                f.close()
                return 200
        try:
                im = Image.open(output)
        except IOError, e:
                return getJSResponse("result=-1; message='Not a valid image file';")
        #print f.name
        size=f.size
        max_width=int(options["dbapp.max_photo_width"])
        if im.size[0]>max_width:
                width=max_width
                height=int(im.size[1]*max_width/im.size[0])
                im=im.resize((width, height), Image.ANTIALIAS)
        try:
                im.save(fname);
        except IOError:
                im.convert('RGB').save(fname)
        
        fns=get_model_filename(model, file_name, catalog+"_thumbnail")
        fn=os.path.split(fns[0])
        try:
                os.makedirs(fn[0])
        except: pass
        create_thumbnail(fname, fns[0])
        return size        


Example #6
0
        import traceback
        traceback.print_exc()
        f = file(fname, "w+b")
        f.write(output.read())
        f.close()
        return 200
    try:
        im = Image.open(output)
    except IOError, e:
        return getJSResponse("result=-1; message='Not a valid image file';")
    #print f.name
    size = f.size
    max_width = int(options["dbapp.max_photo_width"])
    if im.size[0] > max_width:
        width = max_width
        height = int(im.size[1] * max_width / im.size[0])
        im = im.resize((width, height), Image.ANTIALIAS)
    try:
        im.save(fname)
    except IOError:
        im.convert('RGB').save(fname)

    fns = get_model_filename(model, file_name, catalog + "_thumbnail")
    fn = os.path.split(fns[0])
    try:
        os.makedirs(fn[0])
    except:
        pass
    create_thumbnail(fname, fns[0])
    return size
Example #7
0
    def set_resource_image(self, filelikeobj):
        """This is the main method for setting an image. Just give it the file
        like object for reading the image contents and this method will peform
        the following:
            * Save the original image in original_image field.
            * Look at the thumbnail_details property and generate thumbnails specified there.
        It pushes all images to S3 in separate threads to speed up the IO.
        """

        if (not filelikeobj):
            return

        def push_image(attr_name, img, quality=80):
            """A unit of work in terms of pushing image to S3."""
            image_id = str(bson.objectid.ObjectId())
            filelikeobj = StringIO()
            img.save(filelikeobj, "JPEG", quality=quality)
            add_to_s3(image_id + ".jpg", filelikeobj.getvalue())
            setattr(
                self, attr_name,
                Image(image_id=image_id, width=img.size[0],
                      height=img.size[1]))

        image_dict = {}

        orig_content = filelikeobj.read()

        filelikeobj = StringIO(orig_content)
        orig_img = PILImage.open(filelikeobj)
        if orig_img.mode != "RGB":
            orig_img = orig_img.convert("RGB")

        image_list = [("original_image", orig_img, 100)]

        for thumbnail_name in self.thumbnail_details.keys():
            d = self.thumbnail_details[thumbnail_name]
            width = d.get('w', 0)
            height = d.get('h', 0)

            image_width, image_height = orig_img.size

            if (width and height):
                dimensions = (width, height)
            elif (width):
                dimensions = (width,
                              int(float(image_height * width) / image_width))
            elif (height):
                dimensions = (int(float(height * image_width) / image_height),
                              height)
            else:
                logger.error(
                    "Cannot have zero dimensions for a thumbnail in class: %s"
                    % self.__class__.__name__)
                continue

            thumb_img = create_thumbnail(StringIO(orig_content), dimensions)
            if thumb_img.mode != "RGB":
                thumb_img = thumb_img.convert("RGB")

            image_list.append((thumbnail_name, thumb_img, 80))

        thread_list = []
        for item in image_list:
            t = threading.Thread(target=push_image, args=item)
            t.start()
            thread_list.append(t)

        for t in thread_list:
            t.join()
Example #8
0
    def set_resource_image( self, filelikeobj):
        """This is the main method for setting an image. Just give it the file
        like object for reading the image contents and this method will peform
        the following:
            * Save the original image in original_image field.
            * Look at the thumbnail_details property and generate thumbnails specified there.
        It pushes all images to S3 in separate threads to speed up the IO.
        """

        if( not filelikeobj):
            return

        def push_image( attr_name, img, quality=80):
            """A unit of work in terms of pushing image to S3."""
            image_id = str( bson.objectid.ObjectId())
            filelikeobj = StringIO()
            img.save ( filelikeobj, "JPEG", quality=quality )
            add_to_s3( image_id + ".jpg", filelikeobj.getvalue())
            setattr( self, attr_name, Image( image_id=image_id, width=img.size[0], height=img.size[1]))

        image_dict = {}

        orig_content = filelikeobj.read()

        filelikeobj = StringIO(orig_content)
        orig_img = PILImage.open ( filelikeobj )
        if orig_img.mode != "RGB":
            orig_img = orig_img.convert("RGB")

        image_list = [ ("original_image", orig_img, 100)]

        for thumbnail_name in self.thumbnail_details.keys():
            d = self.thumbnail_details[ thumbnail_name]
            width = d.get( 'w', 0)
            height = d.get( 'h', 0)

            image_width, image_height = orig_img.size

            if( width and height):
                dimensions = (width, height)
            elif( width):
                dimensions = ( width, int( float( image_height*width)/image_width))
            elif( height):
                dimensions = ( int( float( height*image_width)/image_height), height)
            else:
                logger.error( "Cannot have zero dimensions for a thumbnail in class: %s" % self.__class__.__name__)
                continue

            thumb_img = create_thumbnail( StringIO( orig_content), dimensions)
            if thumb_img.mode != "RGB":
                thumb_img = thumb_img.convert("RGB")

            image_list.append( (thumbnail_name, thumb_img, 80))

        thread_list = []
        for item in image_list:
            t = threading.Thread( target=push_image, args=item)
            t.start()
            thread_list.append( t)

        for t in thread_list:
            t.join()
Example #9
0
        t : contrast
        b : brightness
        s : sharpness
            """)
            opt = input("       Choose option: ")
            factor = float(input("Enter factor(1.0 is default): "))
            edit_image(path, opt, factor)

        elif choice == "x":
            path = get_directory()
            ext = input("Enter the new extension(e.g. png): ")
            change_extension(path, ext)

        elif choice == "t":
            path = get_directory()
            create_thumbnail(path)

        elif choice == "r":
            path = get_directory()
            print("""
        options:
        r : rotate by an angle
        v : invert image(s) vertically
        h : invert image(s) horizontally
            """)
            opt = input("       Choose option:")
            if opt == "r":
                opt = input("Enter angle(in degree) to rotate image(s) anti-clockwise: ")
                rotate_image(path, opt)
            else:
                rotate_image(path, opt)