コード例 #1
0
ファイル: vimstudio.py プロジェクト: gilangarinata/phocart
def upload_file():
    if request.method == 'POST':
        if 'file' not in request.files:
            return {"code": 1210, "message": "No file part", "path": None}
        file = request.files['file']
        if file.filename == '':
            return {"code": 1211, "message": "no selected file", "path": None}
        if file and allowed_file(file.filename):
            filename = secure_filename(file.filename)
            file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
            img = cv2.cvtColor(cv2.imread("./imageuploads/" + filename),
                               cv2.COLOR_BGR2RGB)
            c2p = Photo2CartoonOnxx()
            cartoon = c2p.inference(img)
            if cartoon is not None:
                path = "./images/" + filename
                cv2.imwrite(path, cartoon)
                f = np.fromfile(path)
                result = remove(f)
                img = Image.open(io.BytesIO(result)).convert("RGBA")
                img.save("./images/" + "final" + filename + ".png")
                return {
                    "code":
                    2000,
                    "message":
                    "success",
                    "path":
                    request.base_url.replace("process", "") + "uploads/" +
                    "final" + filename + ".png"
                }
            return {"code": 1212, "message": "No face detected.", "path": None}
コード例 #2
0
def flutter_removebg():
    print(request.files)
    if request.method == 'POST' and 'file' in request.files:
        file = request.files['file']
        if file.filename != '' and (file and allowed_file(file.filename)):
            #filename = os.path.join('input', file.filename)
            #file.save(filename[-8:])             # Saves the uncropped image
            #input_path = filename[-8:]

            input_path = os.path.join("input", file.filename[-8:])
            str_filename = file.filename[-8:]
            file.save(input_path)

            output = 'image-' + str(int(time.time())) + '.png'
            file = np.fromfile(input_path)
            result = remove(file)
            img = Image.open(io.BytesIO(result)).convert('RGBA')
            #str(int(time.time()))
            output = 'image-' + str_filename.split(".")[0] + '.png'
            output_path = os.path.join("output", output)
            img.save(output_path)  # Saves the cropped image
            print(url_for('uploaded_file', filename=output))
            return url_for('uploaded_file', filename=output)
        else:
            return "bad_2"
    else:
        return "bad_1"
コード例 #3
0
ファイル: main.py プロジェクト: sirateck/removeBg
def removeBg(request):
    """HTTP Cloud Function used to remove image background using rembg (https://github.com/danielgatis/rembg).
    Args:
        request (flask.Request): The request object.
        <https://flask.palletsprojects.com/en/1.1.x/api/#incoming-request-data>
    Returns:
        The response text, or image bytes using `make_response`
        <https://flask.palletsprojects.com/en/1.1.x/api/#flask.make_response>.
    """
    request_args = request.args
    response = ''
    # check if parameters exists
    if request_args and 'image_url_source' in request_args:
        try:
            # Download taget url
            r = requests.get(request_args['image_url_source'])
            # Convert image bytes to numpy array
            f = np.frombuffer(r.content, dtype=np.uint8)
            # Call rembg remove method
            result = remove(f)
            # Transform rembg result to bytesIO
            img_bytesIO = io.BytesIO(result)
            # make response with images bytes as string
            response = make_response(img_bytesIO.getvalue())
            # Set headers
            response.headers.set('Content-Type', 'image/png')
        except Exception as e:
            response = str(e)
    else:
        response = 'Query parameter "image_url_source" is missing'

    return response
コード例 #4
0
async def remove_background(file: UploadFile = File(...)):
    f_content = await file.read()
    f = np.frombuffer(f_content, np.uint8)
    nobg_buff = remove(f)
    nobg_image = Image.open(io.BytesIO(nobg_buff)).convert("RGBA")
    filename = f'{file.filename}-nobg.png'
    nobg_image.save(filename)
    return nobg_image.tobytes()
コード例 #5
0
ファイル: views.py プロジェクト: Pratihar/spindia-print
def removeBg(image_path, bg_color):
    image_array = np.fromfile(image_path)
    result = remove(image_array)
    img = Image.open(io.BytesIO(result))

    bg = Image.new("RGB", img.size, bg_color)
    bg.paste(img, img)

    return bg
コード例 #6
0
def upload_Image():
    data = {"error": '', 'nonbackground': '', 'background': ''}
    token = request.form['token']
    if request.method == "POST" and token == 'hello':
        # for file in os.listdir(os.getcwd()+"/static/Background-Images"):
        #     os.remove(os.path.join(os.getcwd()+"/static/Background-Images", file))
        # for file in os.listdir(os.getcwd()+"/"+"static/Non-Background-Images"):
        #     os.remove(os.path.join(os.getcwd()+"/"+"static/Non-Background-Images",file))
        image = request.files['image']
        imgfilename = request.form['name']
        #print(image)
        if imgfilename == "":
            # data={"error":"No filename"}
            data['error'] = "No filename"
            res = app.response_class(response=json.dumps(data),
                                     status=400,
                                     mimetype='application/json')

            print("No filename")
            #return redirect(request.url)
            return res
        if allowed_image(imgfilename):
            filename = secure_filename(imgfilename)
            filepath = os.path.join(app.config['UPLOAD_FOLDER'], filename)
            print(filepath)

            image.save(filepath)

            output_path = os.path.join(app.config['DOWNLOAD_FOLDER'], filename)

            f = np.fromfile(filepath)
            result = remove(f)
            img = Image.open(io.BytesIO(result)).convert("RGB")
            img.save(output_path)
            data[
                'nonbackground'] = request.url_root + "static/Non-Background-Images/" + filename
            data['nonbackgroundurl'] = output_path
            res = app.response_class(response=json.dumps(data),
                                     status=200,
                                     mimetype='application/json')
            return res
    else:
        data['error'] = "Token Invalid "
        res = app.response_class(response=json.dumps(data),
                                 status=200,
                                 mimetype='application/json')
        #print("That file extension is not allowed")
        #return redirect(request.url)
        return res

    data['error'] = "Please send post Request"
    res = app.response_class(response=json.dumps(data),
                             status=403,
                             mimetype='application/json')
    print("That file extension is not allowed")
    return res
コード例 #7
0
def rembg_detector(file_path):
    with open(file_path, "rb") as input:
        if hasattr(input, "buffer"):
            ss = input.buffer.read()
        else:
            ss = input.read()
    result = remove(ss)
    print('type result: ', type(result))
    img = Image.open(io.BytesIO(result)).convert("RGBA")
    return np.array(img)
コード例 #8
0
def remove_bg():
    if request.method == "POST":
        file = request.files["file"]
        file.save(input_path)
        file = np.fromfile(input_path)
        result = remove(file)
        img = Image.open(io.BytesIO(result)).convert("RGBA")
        img.save(output_path)
        return "file_uploaded"
    return """<!doctype html>
コード例 #9
0
def remove_bg():
    if request.method == "POST":
        file = request.files["file"]
        file.save("input\\" + file.filename)
        file = np.fromfile(file.filename)
        result = remove(file)
        output = 'image-' + str(int(time.time())) + '.png'  # Must be a .png
        img = Image.open(io.BytesIO(result)).convert("RGBA")
        img.save("output\\" + output)
        return "file_uploaded"
    return """<!doctype html>
コード例 #10
0
ファイル: image.py プロジェクト: johndpope/Alter-Ego
def remove_background(file):
    alpha = io.BytesIO(remove(file.read()))
    image = Image.open(alpha)
    image.load()
    
    black = Image.new("RGB", image.size, color=0)
    black.paste(image, mask=image.split()[3])

    finalImage = io.BytesIO()
    black.save(finalImage, "JPEG")
    return finalImage.getbuffer()
コード例 #11
0
def remove_image_background(image: bytes) -> bytes:

    """
    Return image with removed background
    :param image: image to remove background on
    :return: image with removed background
    """

    logging.info("Starting to remove background from photo")
    image_with_removed_background = remove(image)
    logging.info("Successfully removed background")

    return image_with_removed_background.tobytes()
コード例 #12
0
def removebackground():
    input_path = glob.glob("./media" + "/**/*.png", recursive = True)
    global y
    y = 1

    # input 이미지 삽입
    for i in range(len(input_path)):
        f = np.fromfile(input_path[i+lenI])
        # input 이미지 배경 제거
        result = remove(f)
        # 배경 제거한 이미지 변환
        img = Image.open(io.BytesIO(result)).convert("RGBA")
        # 이미지 저장
        img.save('./output/output' + str(y+lenI) + '.png')
        y += 1
コード例 #13
0
def remove_bg():
    if request.method == "POST":
        file = request.files["file"]
        input_path = os.path.join("input", file.filename[-8:])
        str_filename = file.filename[-8:]
        file.save(input_path)
        file = np.fromfile(input_path)
        result = remove(file)
        output = 'image-' + str_filename.split(".")[0] + str(int(
            time.time())) + '.png'  # Must be a .png
        img = Image.open(io.BytesIO(result)).convert("RGBA")
        output_path = os.path.join("output", output)
        img.save(output_path)
        return redirect(url_for("uploaded_file", filename=output))
    return """<!doctype html>
コード例 #14
0
def upload_file(isRemove):
    if request.method == 'POST':
        if 'file' not in request.files:
            return {"code": 1210, "message": "No file part", "path": None}
        file = request.files['file']
        if file.filename == '':
            return {"code": 1211, "message": "no selected file", "path": None}
        if file and allowed_file(file.filename):
            filename = secure_filename(file.filename)
            file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
            img_path = UPLOAD_FOLDER + '/' + filename
            model_path = MODEL_PATH
            save_folder = SAVED_FOLDER
            if not os.path.exists(save_folder):
                os.mkdir(save_folder)
            cartoonize(img_path, save_folder, model_path, filename)
            path = "./images/" + filename
            f = np.fromfile(path)
            if isRemove == '1':
                respon = {
                    "code":
                    2000,
                    "message":
                    "success",
                    "path":
                    request.base_url.replace("process", "").replace(
                        "/0", "").replace("/1", "") + "uploads/" + filename
                }
                print(respon)
                return respon
            else:
                result = remove(f)
                img = Image.open(io.BytesIO(result)).convert("RGBA")
                img.save("./images/" + "final" + filename + ".png")
                respon = {
                    "code":
                    2000,
                    "message":
                    "success",
                    "path":
                    request.base_url.replace("process", "").replace(
                        "/0", "").replace("/1", "") + "uploads/" + "final" +
                    filename + ".png"
                }
                print(respon)
                return respon
        return {"message": "failed"}
コード例 #15
0
def rembg_detector(file_path):
    """ Rembg is a tool to remove images background. https://github.com/danielgatis/rembg"""
    with open(file_path, "rb") as input:
        if hasattr(input, "buffer"):
            ss = input.buffer.read()
        else:
            ss = input.read()
    result = remove(ss)
    img = Image.open(io.BytesIO(result)).convert("RGBA")
    img = np.array(img)
    # alpha value
    mask_binary = img[:, :, 3]
    mask_binary[mask_binary > 10] = 255
    mask_binary[mask_binary <= 10] = 0
    # plt.imshow(img)
    # plt.show()
    return mask_binary
コード例 #16
0
def image_process(filename):
    print(filename, "imageprocessicinde")
    ImageFile.LOAD_TRUNCATED_IMAGES = True
    print(UPLOAD_FOLDER, filename)
    f = np.fromfile(UPLOAD_FOLDER + filename)
    result = remove(f,
                    alpha_matting=True,
                    alpha_matting_foreground_threshold=240,
                    alpha_matting_background_threshold=10,
                    alpha_matting_erode_structure_size=6)
    img = Image.open(io.BytesIO(result)).convert("RGB")  #.convert("RGBA")
    print(img.format, img.mode)

    # https://stackoverflow.com/questions/9166400/convert-rgba-png-to-rgb-with-pil/9459208#9459208
    #img.save("process/background_subtract"+filename,'JPEG', quality=80)
    img.save("process/background_subtract.jpg")
    print("Resim kaydedildi")
    return img
コード例 #17
0
ファイル: main.py プロジェクト: mathix420/comrade_bot
def get_chart(bg_id, username):
    filter = filters[int(bg_id)]
    bg = filter[0].copy()

    r = get(f'https://cdn.intra.42.fr/users/medium_{username}.jpg')

    image = Image.open(BytesIO(remove(r.content)))

    bg.paste(image, filter[1](bg.size, image.size), image)

    img_bytes = BytesIO()
    bg.save(img_bytes, format='JPEG', quality=70)
    img_bytes.seek(0)

    return send_file(
        img_bytes,
        mimetype='image/jpeg',
        # as_attachment=True,
        # attachment_filename='comrade.jpg'
    )
コード例 #18
0
ファイル: app.py プロジェクト: FreeFriday/espresso-backend
def random():
    """
    - img: base64-encoded file
    """

    print(request)
    print(request.files)
    print(request.args)
    if request.method == 'GET':
        t0 = time()
        opt = request.args
        img_path = data_paths[randint(0, len(data_paths) - 1)]
        img_ori = Image.open(img_path).convert('RGBA')
        img_pad, pad_W, pad_H = pad_factor(img_ori, factor=16)
        img_bytes = io.BytesIO()
        img_pad.save(img_bytes, 'PNG')
        img_bytes = img_bytes.getvalue()
        encoded_in = base64.encodebytes(img_bytes).decode(
            'ascii')  # encode as base64

        if opt.get('bgrmv') == 'false':
            output_img = model.inference(img_bytes)
            output_img = np.array(output_img)
            output_img = original_region(output_img, pad_H, pad_W)
            output_img = Image.fromarray(output_img)
            byte_arr = io.BytesIO()
            output_img.save(byte_arr, 'PNG')
        else:
            # remove background
            img_bytes_nobg = remove(
                img_bytes,
                alpha_matting=opt.get('am').lower() == 'true',
                alpha_matting_foreground_threshold=int(opt.get('amft')),
                alpha_matting_background_threshold=int(opt.get('ambt')),
                alpha_matting_erode_structure_size=int(opt.get('amess')))
            # get alpha channel
            img_nobg = np.array(
                Image.open(io.BytesIO(img_bytes_nobg)).convert('RGBA'))
            Image.fromarray(img_nobg).save('tmp.png')
            assert img_nobg.shape[-1] == 4  # must have alpha channel
            alpha = np.expand_dims(img_nobg[:, :, -1], axis=-1)

            # inference
            output_img = model.inference(img_bytes)
            output_img = np.array(output_img)
            output_img = np.concatenate([output_img, alpha], axis=-1)
            output_img = original_region(output_img, pad_H, pad_W)
            output_img = Image.fromarray(output_img)
            byte_arr = io.BytesIO()
            output_img.save(byte_arr, 'PNG')

        encoded_out = base64.encodebytes(byte_arr.getvalue()).decode(
            'ascii')  # encode as base64

        t1 = time()
        res = {
            'status': True,
            'elapsed_time': t1 - t0,
            'img_in': encoded_in,
            'img_out': encoded_out,
        }
    else:
        res = {
            'status': False,
            'message': 'please request with image using GET method'
        }

    return jsonify(res)
コード例 #19
0
from rembg.bg import remove
import numpy as np
import io
from PIL import Image

input_path = 'profil.png'
output_path = 'cutout.png'

f = np.fromfile(input_path)
result = remove(f,
                alpha_matting=True,
                alpha_matting_foreground_threshold=240,
                alpha_matting_background_threshold=10,
                alpha_matting_erode_structure_size=6)
img = Image.open(io.BytesIO(result)).convert("RGBA")
img.save(output_path)
コード例 #20
0
#Process frames with rembg
if not args.skip_process:
    if not os.path.isdir(
            str(pathlib.Path(__file__).parent.absolute()) + "\\" +
            "processed"):
        os.mkdir(
            str(pathlib.Path(__file__).parent.absolute()) + "\\" + "processed")
    files_dir = str(pathlib.Path(__file__).parent.absolute()) + "\\" + "frames"
    processed_dir = str(
        pathlib.Path(__file__).parent.absolute()) + "\\" + "processed"

    for file in os.listdir(files_dir):
        with open(os.path.join(files_dir, file), "rb") as i:
            with open(os.path.join(processed_dir, file), "wb") as o:
                input = i.read()
                output = remove(input,
                                alpha_matting=args.a,
                                alpha_matting_foreground_threshold=args.af,
                                alpha_matting_background_threshold=args.ab,
                                alpha_matting_erode_size=args.ae)
                o.write(output)

#Output video
stream = ffmpeg.input("processed\\%04d.png",
                      r=framerate,
                      f='image2',
                      s=whstr,
                      pix_fmt='yuv420p')
stream = ffmpeg.output(stream, "output.mp4", vcodec='libx264', crf=25)
ffmpeg.run(stream)
コード例 #21
0
def test_remove_background_task(celery_image_app, image_for_test):

    remove_image_background_task = remove_image_background.delay(image_for_test)
    result_from_celery = remove_image_background_task.get(timeout=5)
    result = remove(image_for_test).tobytes()
    assert result_from_celery == result
コード例 #22
0
#Process frames with rembg
if not args.skip_process:
    if not os.path.isdir(
            str(pathlib.Path(__file__).parent.absolute()) + "\\" +
            "processed"):
        os.mkdir(
            str(pathlib.Path(__file__).parent.absolute()) + "\\" + "processed")
    files_dir = str(pathlib.Path(__file__).parent.absolute()) + "\\" + "frames"
    processed_dir = str(
        pathlib.Path(__file__).parent.absolute()) + "\\" + "processed"

    for file in os.listdir(files_dir):
        img = open(os.path.join(files_dir, file), "rb")
        img_bytes = bytearray(img.read())
        processed_bytes = remove(img_bytes,
                                 alpha_matting=args.a,
                                 alpha_matting_foreground_threshold=args.af,
                                 alpha_matting_background_threshold=args.ab,
                                 alpha_matting_erode_structure_size=args.ae)
        processed_img = open(os.path.join(processed_dir, file), "wb")
        processed_img.write(processed_bytes)

#Output video
stream = ffmpeg.input("processed\\%04d.png",
                      r=framerate,
                      f='image2',
                      s=whstr,
                      pix_fmt='yuv420p')
stream = ffmpeg.output(stream, "output.mp4", vcodec='libx264', crf=25)
ffmpeg.run(stream)
コード例 #23
0
ファイル: test.py プロジェクト: johndpope/Alter-Ego
def testBackgroundRemoveOld():
    with open("test/output/faces/pre/hummels2.jpg", 'rb') as img:
        with open("test/output/faces/pre/hummels_t.png", 'wb+') as finalimg:
            finalimg.write(remove(img.read()))
コード例 #24
0
        img = Image.open(io.BytesIO(result)).convert("RGBA")
        img.save(output)
        return "file_uploaded"
    return """<!doctype html>
        <title>Upload new File</title>
        <h1>Upload new File</h1>
        <form method=post enctype=multipart/form-data>
          <input type=file name=file>
          <input type=submit value=Upload>
        </form>"""
print("hi")
app.run(host = "0.0.0.0")


# If file exists and is an acceptable file type
        # Specified by ALLOWED_EXTENSIONS
        if file and allowed_file(file.filename):
            filename = os.path.join(app.config['UPLOAD_FOLDER'], file.filename)
            file.save(filename)             # Saves the uncropped image

            input_path = filename
            image_file_name = 'image-' + str(int(time.time())) + '.png' # Must be a .png
            output_path = os.path.join(app.config['CROP_FOLDER'], image_file_name)

            file = np.fromfile(input_path)
            result = remove(file)
            img = Image.open(io.BytesIO(result)).convert('RGBA')
            img.save(output_path)           # Saves the cropped image

            return redirect(url_for('uploaded_file', filename=image_file_name))
コード例 #25
0
ImageFile.LOAD_TRUNCATED_IMAGES = True

parser = argparse.ArgumentParser(description="Remove background of images")
parser.add_argument("target_path", help="Target folder path")
parser.add_argument("destination_path", help="Destination folder path")
args = parser.parse_args()

target = args.target_path
destination = args.destination_path

p = pathlib.Path(target)
p_list = list(p.glob("*"))

os.makedirs(destination, exist_ok=True)

count = 0
print("******* Start removing background... *******")
for p in p_list:
    count += 1

    f = np.fromfile(p)
    result = remove(f)
    img = Image.open(io.BytesIO(result)).convert("RGBA")
    img.save("{}/removed_{}.png".format(destination,
                                        pathlib.Path(p.name).stem))

    if count % 10 == 0:
        print("Removing {}th image's background...\n".format(count))
print("\n******* Finish removing background! *******")
コード例 #26
0
ファイル: app.py プロジェクト: FreeFriday/espresso-backend
def inference():
    """
    - img: base64-encoded file
    """

    print(request)
    print(request.files)
    print(request.args)
    if request.method == 'POST' and request.files.get('img'):
        t0 = time()
        opt = request.args
        img_bytes = request.files['img'].read()
        extention = magic.from_buffer(img_bytes).split()[0].upper()

        if extention not in ['JPEG', 'PNG', 'JPG']:
            res = {
                'status':
                True,
                'message':
                'please request with valid image (only supports JPEG or PNG)'
            }
            return jsonify(res)

        # resize and padding
        img = Image.open(io.BytesIO(img_bytes)).convert('RGBA')
        W, H = img.size
        if W >= SIZE_THRESHOLD or H >= SIZE_THRESHOLD:
            if W > H:
                img = img.resize((SIZE_THRESHOLD, int(H * SIZE_THRESHOLD / W)),
                                 Image.ANTIALIAS)
            else:
                img = img.resize((int(W * SIZE_THRESHOLD / H), SIZE_THRESHOLD),
                                 Image.ANTIALIAS)
        img_pad, pad_W, pad_H = pad_factor(img, factor=16)
        img_bytes = io.BytesIO()
        img_pad.save(img_bytes, 'PNG')
        img_bytes = img_bytes.getvalue()

        if opt.get('bgrmv') == 'false':
            output_img = model.inference(img_bytes)
            output_img = np.array(output_img)
            output_img = original_region(output_img, pad_H, pad_W)
            output_img = Image.fromarray(output_img)
            byte_arr = io.BytesIO()
            output_img.save(byte_arr, 'PNG')
        else:
            # remove background
            img_bytes_nobg = remove(
                img_bytes,
                alpha_matting=opt.get('am').lower() == 'true',
                alpha_matting_foreground_threshold=int(opt.get('amft')),
                alpha_matting_background_threshold=int(opt.get('ambt')),
                alpha_matting_erode_structure_size=int(opt.get('amess')))
            # get alpha channel
            img_nobg = np.array(
                Image.open(io.BytesIO(img_bytes_nobg)).convert('RGBA'))
            Image.fromarray(img_nobg).save('tmp.png')
            assert img_nobg.shape[-1] == 4  # must have alpha channel
            alpha = np.expand_dims(img_nobg[:, :, -1], axis=-1)
            alpha[alpha < ALPHA_THRESHOLD] = 0

            output_img = model.inference(img_bytes)
            output_img = np.array(output_img)
            output_img = np.concatenate([output_img, alpha], axis=-1)
            output_img = original_region(output_img, pad_H, pad_W)
            output_img = Image.fromarray(output_img)
            output_img = output_img.crop(
                output_img.getbbox())  # crop bounding box
            byte_arr = io.BytesIO()
            output_img.save(byte_arr, 'PNG')

        encoded_img = base64.encodebytes(byte_arr.getvalue()).decode(
            'ascii')  # encode as base64

        t1 = time()
        res = {'status': True, 'elapsed_time': t1 - t0, 'img': encoded_img}
    else:
        res = {
            'status': False,
            'message': 'please request with image using POST method'
        }

    return jsonify(res)