rembg
Çok kısa bir şekilde resimlerinizin arka planını silebilirsiniz.
#pip install rembg
from rembg import remove
from PIL import Image
input_path = 'korunga.jpg'
output_path = 'korunga-t10.png'
input = Image.open(input_path)
output = remove(input, alpha_matting=True, alpha_matting_background_threshold=60,)
output.save(output_path)
print(output_path)
rembg ve pillow
Resimlerinizin arka planını silmek için 2. yöntem
#pip install rembg
#pip install pillow
#pip install -U pillow
from rembg import remove
import requests
from PIL import Image
from io import BytesIO
import os
os.makedirs("orginal", exist_ok=True)
os.makedirs("masked", exist_ok=True)
img_url="https://static8.depositphotos.com/1004037/969/i/450/depositphotos_9695849-stock-photo-red-horse-runs-front-in.jpg"
img_name=img_url.split('/')[-1]
print(img_name)
response = requests.get(img_url)
if response.status_code == 200:
try:
img = Image.open(BytesIO(response.content))
img.save('orginal/' + img_name, format='jpeg')
except Exception as e:
print(f"Error: {e}")
else:
print(f"Error: Unable to fetch image. Status code: {response.status_code}")
img= Image.open(BytesIO(requests.get(img_url).content))
img.save('orginal/'+img_name, format='jpeg')
input_path='orginal/' + img_name
output_path= 'masked/'+img_name
print(output_path)
with open(output_path, 'wb') as f:
input = open('orginal/'+img_name, 'rb').read()
print(input)
subject = remove(input, alpha_matting=True, alpha_matting_background_threshold=50, )
f.write(subject)
U2Net

Python ile bir resmin arka planını kaldırabilirsiniz, bunun için Github'da bulunan bir U2Net adında proje kullanacağız. Öncelikle dosyaları buradan indirebilirsiniz. Arkaplan %100 çalışıyor diyemem fakat güzel sonuçlar elde edebiliyorsunuz ayrıca .jpg ve .png uzantılı dosyaları desktekliyor.
Projeyi indirdikten sonra dizin yapısı aşağıdaki gibi olmalı:
Kodlar ise şu şekilde:
import torch
import torch.nn as nn
import torch.optim as optim
import numpy as np
import cv2
import uuid
import os
from model import U2NET
from torch.autograd import Variable
from skimage import io, transform
from PIL import Image
import easygui
# Get The Current Directory
currentDir = os.path.dirname(__file__)
# Functions:
# Save Results
def save_output(image_name, output_name, pred, d_dir, type):
predict = pred
predict = predict.squeeze()
predict_np = predict.cpu().data.numpy()
im = Image.fromarray(predict_np*255).convert('RGB')
image = io.imread(image_name)
imo = im.resize((image.shape[1], image.shape[0]))
pb_np = np.array(imo)
if type == 'image':
# Make and apply mask
mask = pb_np[:, :, 0]
mask = np.expand_dims(mask, axis=2)
imo = np.concatenate((image, mask), axis=2)
imo = Image.fromarray(imo, 'RGBA')
imo.save(d_dir+output_name)
# Remove Background From Image (Generate Mask, and Final Results)
def removeBg(imagePath):
inputs_dir = os.path.join(currentDir, 'static/inputs/')
results_dir = os.path.join(currentDir, 'static/results/')
masks_dir = os.path.join(currentDir, 'static/masks/')
# convert string of image data to uint8
with open(imagePath, "rb") as image:
f = image.read()
img = bytearray(f)
nparr = np.frombuffer(img, np.uint8)
if len(nparr) == 0:
return '---Empty image---'
# decode image
try:
img = cv2.imdecode(nparr, cv2.IMREAD_COLOR)
except:
# build a response dict to send back to client
return "---Empty image---"
# save image to inputs
unique_filename = str(uuid.uuid4())
cv2.imwrite(inputs_dir+unique_filename+'.jpg', img)
# processing
image = transform.resize(img, (320, 320), mode='constant')
tmpImg = np.zeros((image.shape[0], image.shape[1], 3))
tmpImg[:, :, 0] = (image[:, :, 0]-0.485)/0.229
tmpImg[:, :, 1] = (image[:, :, 1]-0.456)/0.224
tmpImg[:, :, 2] = (image[:, :, 2]-0.406)/0.225
tmpImg = tmpImg.transpose((2, 0, 1))
tmpImg = np.expand_dims(tmpImg, 0)
image = torch.from_numpy(tmpImg)
image = image.type(torch.FloatTensor)
image = Variable(image)
d1, d2, d3, d4, d5, d6, d7 = net(image)
pred = d1[:, 0, :, :]
ma = torch.max(pred)
mi = torch.min(pred)
dn = (pred-mi)/(ma-mi)
pred = dn
save_output(inputs_dir+unique_filename+'.jpg', unique_filename +
'.png', pred, results_dir, 'image')
save_output(inputs_dir+unique_filename+'.jpg', unique_filename +
'.png', pred, masks_dir, 'mask')
return "---Success---"
# ------- Load Trained Model --------
print("---Loading Model---")
model_name = 'u2net'
model_dir = os.path.join(currentDir, 'saved_models',
model_name, model_name + '.pth')
net = U2NET(3, 1)
if torch.cuda.is_available():
net.load_state_dict(torch.load(model_dir))
net.cuda()
else:
net.load_state_dict(torch.load(model_dir, map_location='cpu'))
# ------- Load Trained Model --------
print("---Removing Background...")
# ------- Call The removeBg Function --------
imgPath = easygui.fileopenbox()
#imgPath = "C:\\Users\\MAHMUT\\Desktop\\core\\calismadizini\\ImageBackgroundRemover\\images\\cicek.jpg" # Change this to your image path
print(removeBg(imgPath))
Kaynaklar
- https://github.com/xuebinqin/U-2-Net
- https://learnwithhasan.com/remove-image-background-with-python/
- https://www.youtube.com/watch?v=KkhPN7Z4Fy8