Exemplo n.º 1
0
def process(input_path, output_path, model_name="u2net",
            preprocessing_method_name="bbd-fastrcnn", postprocessing_method_name="rtb-bnb"):
    """
    Processes the file.
    :param input_path: The path to the image / folder with the images to be processed.
    :param output_path: The path to the save location.
    :param model_name: Model to use.
    :param postprocessing_method_name: Method for image preprocessing
    :param preprocessing_method_name: Method for image post-processing
    """
    if input_path is None or output_path is None:
        raise Exception("Bad parameters! Please specify input path and output path.")

    model = model_detect(model_name)  # Load model
    if not model:
        logger.warning("Warning! You specified an invalid model type. "
                       "For image processing, the model with the best processing quality will be used. "
                       "(u2net)")
        model_name = "u2net"  # If the model line is wrong, select the model with better quality.
        model = model_detect(model_name)  # Load model
    preprocessing_method = preprocessing.method_detect(preprocessing_method_name)
    postprocessing_method = postprocessing.method_detect(postprocessing_method_name)
    wmode = __work_mode__(input_path)  # Get work mode
    if wmode == "file":  # File work mode
        image = model.process_image(input_path, preprocessing_method, postprocessing_method)
        __save_image_file__(image, os.path.basename(input_path), output_path, wmode)
    elif wmode == "dir":  # Dir work mode
        # Start process
        files = os.listdir(input_path)
        for file in tqdm.tqdm(files, ascii=True, desc='Remove Background', unit='image'):
            file_path = os.path.join(input_path, file)
            image = model.process_image(file_path, preprocessing_method, postprocessing_method)
            __save_image_file__(image, file, output_path, wmode)
    else:
        raise Exception("Bad input parameter! Please indicate the correct path to the file or folder.")
Exemplo n.º 2
0
def process(input_path,
            output_path,
            model_name="u2net",
            preprocessing_method_name="bbd-fastrcnn",
            postprocessing_method_name="rtb-bnb"):
    """
    Processes the file.
    :param input_path: The path to the image / folder with the images to be processed.
    :param output_path: The path to the save location.
    :param model_name: Model to use.
    :param postprocessing_method_name: Method for image preprocessing
    :param preprocessing_method_name: Method for image post-processing
    """
    # if input_path is None or output_path is None:
    #     raise Exception("Bad parameters! Please specify input path and output path.")

    model = model_detect(model_name)  # Load model
    if not model:
        logger.warning(
            "Warning! You specified an invalid model type. "
            "For image processing, the model with the best processing quality will be used. "
            "(u2net)")
        model_name = "u2net"  # If the model line is wrong, select the model with better quality.
        model = model_detect(model_name)  # Load model
    preprocessing_method = preprocessing.method_detect(
        preprocessing_method_name)
    postprocessing_method = postprocessing.method_detect(
        postprocessing_method_name)

    folder = "images"
    if not os.path.exists(folder):
        os.mkdir(folder)

    print("img bg rm service is running!")
    while True:
        time.sleep(0.5)
        img_files = [
            f for f in listdir(folder)
            if isfile(join(folder, f)) and f.endswith("jpg")
        ]
        if len(img_files) == 0:
            continue

        img_files.sort()
        # has images to rm bg
        for img in img_files:
            input_path = join(folder, img)
            output_path = join(folder, img.replace("jpg", "png"))
            img = cv2.imread(input_path)
            if img is None:
                # check valid img file
                continue

            print(f"processing ", input_path)
            image = model.process_image(input_path, preprocessing_method,
                                        postprocessing_method)
            __save_image_file__(image, os.path.basename(input_path),
                                output_path, "file")
            os.remove(input_path)
Exemplo n.º 3
0
def save():
    start = time.time()
    logging.info(' CUT')
    print("here")

    # Convert string of image data to uint8.
    print(request.files)
    if 'data' not in request.files:
        return jsonify({
            'status': 'error',
            'error': 'missing file param `data`'
        }), 400
    data = request.files['data'].read()
    if len(data) == 0:
        return jsonify({'status:': 'error', 'error': 'empty image'}), 400

    # Save debug locally.
    with open('imgtmp.jpg', 'wb') as f:
        f.write(data)

    image = Image.open("imgtmp.jpg")
    print(image.size)

    input_path = 'imgtmp.jpg'
    output_path = 'imgtmp.png'
    model_name = 'u2net'
    preprocessing_method_name = 'none'
    postprocessing_method_name = 'fba'

    model = model_detect(model_name)  # Load model
    print("--model start--")

    preprocessing_method = preprocessing.method_detect(
        preprocessing_method_name)
    postprocessing_method = postprocessing.method_detect(
        postprocessing_method_name)
    wmode = "file"  # Get work mode
    image = model.process_image(input_path, preprocessing_method,
                                postprocessing_method)

    image.save('imgtmp.png')

    with open("imgtmp.png", "rb") as img_file:
        my_string = base64.b64encode(img_file.read())

    socketio.emit('req', {'base64': my_string})

    # Save to buffer
    buff = io.BytesIO()
    image.save(buff, 'PNG')
    buff.seek(0)
    print("--model end--")

    # Print stats
    logging.info(f'Completed in {time.time() - start:.2f}s')
    print(f'Completed in {time.time() - start:.2f}s')

    return send_file(buff, mimetype='image/png')
Exemplo n.º 4
0
def process(input_path, output_path, model_name="u2netp",model_dir='models',
            preprocessing_method_name=None, postprocessing_method_name="rtb-bnb"):
    """
    Processes the file.
    :param input_path: The path to the image / folder with the images to be processed.
    :param output_path: The path to the save location.
    :param model_name: Model to use.
    :param postprocessing_method_name: Method for image preprocessing
    :param preprocessing_method_name: Method for image post-processing
    """
    if input_path is None or output_path is None:
        raise Exception("Bad parameters! Please specify input path and output path.")

    model = model_detect(model_name,model_dir)  # Load model
    if not model:
        logger.warning("Warning! You specified an invalid model type. "
                       "For image processing, the model with the best processing quality will be used. "
                       "(u2net)")
        model_name = "u2net"  # If the model line is wrong, select the model with better quality.
        model = model_detect(model_name)  # Load model
    preprocessing_method = preprocessing.method_detect(preprocessing_method_name)
    postprocessing_method = postprocessing.method_detect(postprocessing_method_name)
    image = model.process_image(input_path, preprocessing_method, postprocessing_method)
    return image
 def test_postprocess_method(self):
     for method in strings.POSTPROCESS_METHODS:
         method = postprocessing.method_detect(method)
         if method is False:
             self.fail("Unknown model in POSTPROCESS_METHODS!!!")
Exemplo n.º 6
0
def process(input_path, output_path, model_name="u2net",\
            preprocessing_method_name="bbd-fastrcnn", postprocessing_method_name="rtb-bnb"):
    """
    Processes the file.
    :param input_path: The path to the image / folder with the images to be processed.
    :param output_path: The path to the save location.
    :param model_name: Model to use.
    :param postprocessing_method_name: Method for image preprocessing
    :param preprocessing_method_name: Method for image post-processing
    """
    logging.info("process.task >>> started")
    returnData = False
    if input_path is None or output_path is None:
        raise Exception(
            "Bad parameters! Please specify input path and output path.")

    model = model_detect(model_name)  # Load model
    logging.info("going to run process by model %s" % model)
    if not model:
        logging.info(
            "Warning! You specified an invalid model type. "
            "For image processing, the model with the best processing quality will be used. "
            "(u2net)")
        model_name = "u2net"  # If the model line is wrong, select the model with better quality.
        logging.info("model name is {}".format(model_name))
        model = model_detect(model_name)  # Load model
    logging.info("preprocessing_method background removal process started")
    preprocessing_method = preprocessing.method_detect(
        preprocessing_method_name)
    logging.info("postprocessing_method background process started")
    postprocessing_method = postprocessing.method_detect(
        postprocessing_method_name)
    wmode = __work_mode__(input_path)  # Get work mode

    logging.info(">>>task.process processing completed. task.status success")

    returnData = False
    if wmode == "file":  # File work mode
        image = model.process_image(input_path, preprocessing_method,
                                    postprocessing_method)
        __save_image_file__(image, os.path.basename(input_path), output_path,
                            wmode)
        returnData = True
        logging.info("sucess.task >>>> True ")

    elif wmode == "dir":  # Dir work mode
        # Start process
        files = os.listdir(input_path)
        for file in tqdm.tqdm(files,
                              ascii=True,
                              desc='Remove Background',
                              unit='image'):
            file_path = os.path.join(input_path, file)
            image = model.process_image(file_path, preprocessing_method,
                                        postprocessing_method)
            __save_image_file__(image, file, output_path, wmode)
            logging.info("sucess.task >>>> True ")
            returnData = True
    else:
        logging.info(
            "Bad input parameter! Please indicate the correct path to the file or folder."
        )
        returnData = False
        logging.info("task.status >>>> failed")
    print("Image Editor task.status True")

    print(returnData)
    if returnData is True:
        url = os.getenv("APIURL", "Error Found in url")
        logging.info("API url >> {}".format(url))
        image = finalresponse[0]
        logging.info("o/p image and file id is {} ".format(image, fileId))
        #    now = datetime.now()
        #   createdBy = now.strftime("%d/%m/%Y %H:%M:%S")

        data = MultipartEncoder(
            fields={
                'id': fileId,
                'file': (os.path.basename(image), open(image, 'rb'),
                         'text/plain')
            })
        logging.info("content type is {}".format(data.content_type))
        response = requests.post(url,
                                 data=data,
                                 headers={'Content-Type': data.content_type})

        logging.info(response.status_code)
        json_res = json.loads(response.text)

        print(json_res)
        logging.info("API response {}".format(json_res))
        if response.status_code != 200:
            #payload["error"] = logs
            logging.error("error found %s" % str(logs), 100, ex=True)

        else:
            logging.info("total operation performed {}".format(logs))
            logging.info("API response.status success")
            #responseApi = requests.post(url=url, data=payload, headers=headers)
            #logging.info(" {}".format(json.dumps(responseApi.text)))
            #}
    else:
        logging.info("script task.status >>  failed")