Comments (2)
from u-2-net.
@xuebinqin hi bro..
here is my file
import os
from skimage import io, transform
from skimage.filters import gaussian
import torch
import torchvision
from torch.autograd import Variable
import torch.nn as nn
import torch.nn.functional as F
from torch.utils.data import Dataset, DataLoader
from torchvision import transforms # , utils
# import torch.optim as optim
import numpy as np
from PIL import Image
import glob
from data_loader import RescaleT
from data_loader import ToTensor
from data_loader import ToTensorLab
from data_loader import SalObjDataset
from model import U2NET # full size version 173.6 MB
from model import U2NETP # small version u2net 4.7 MB
import argparse
# normalize the predicted SOD probability map
def normPRED(d):
ma = torch.max(d)
mi = torch.min(d)
dn = (d - mi) / (ma - mi)
return dn
def save_output(image_name, pred, d_dir, sigma=2, alpha=0.5):
predict = pred
predict = predict.squeeze()
predict_np = predict.cpu().data.numpy()
image = io.imread(image_name)
pd = transform.resize(predict_np, image.shape[0:2], order=2)
pd = pd / (np.amax(pd) + 1e-8) * 255
pd = pd[:, :, np.newaxis]
print(image.shape)
print(pd.shape)
## fuse the orignal portrait image and the portraits into one composite image
## 1. use gaussian filter to blur the orginal image
sigma = sigma
image = gaussian(image, sigma=sigma, preserve_range=True)
## 2. fuse these orignal image and the portrait with certain weight: alpha
alpha = alpha
im_comp = image * alpha + pd * (1 - alpha)
print(im_comp.shape)
img_name = image_name.split(os.sep)[-1]
aaa = img_name.split(".")
bbb = aaa[0:-1]
imidx = bbb[0]
for i in range(1, len(bbb)):
imidx = imidx + "." + bbb[i]
io.imsave(d_dir + '/' + imidx + '_sigma_' + str(sigma) + '_alpha_' + str(alpha) + '_composite.png', im_comp)
def main():
parser = argparse.ArgumentParser(description="image and portrait composite")
parser.add_argument('-s', action='store', dest='sigma')
parser.add_argument('-a', action='store', dest='alpha')
args = parser.parse_args()
print(args.sigma)
print(args.alpha)
print("--------------------")
# --------- 1. get image path and name ---------
model_name = 'u2net_portrait' # u2netp
image_dir = 'D:\\image folder'
prediction_dir = 'D:\\image folder'
if (not os.path.exists(prediction_dir)):
os.mkdir(prediction_dir)
model_dir = 'D:\4K Video Downloader\u2net_portrait.pth'
img_name_list = glob.glob(image_dir + '/*')
print("Number of images: ", len(img_name_list))
# --------- 2. dataloader ---------
# 1. dataloader
test_salobj_dataset = SalObjDataset(img_name_list=img_name_list,
lbl_name_list=[],
transform=transforms.Compose([RescaleT(512),
ToTensorLab(flag=0)])
)
test_salobj_dataloader = DataLoader(test_salobj_dataset,
batch_size=1,
shuffle=False,
num_workers=1)
# --------- 3. model define ---------
print("...load U2NET---173.6 MB")
net = U2NET(3, 1)
net.load_state_dict(torch.load(model_dir))
if torch.cuda.is_available():
net.cuda()
net.eval()
# --------- 4. inference for each image ---------
for i_test, data_test in enumerate(test_salobj_dataloader):
print("inferencing:", img_name_list[i_test].split(os.sep)[-1])
inputs_test = data_test['image']
inputs_test = inputs_test.type(torch.FloatTensor)
if torch.cuda.is_available():
inputs_test = Variable(inputs_test.cuda())
else:
inputs_test = Variable(inputs_test)
d1, d2, d3, d4, d5, d6, d7 = net(inputs_test)
# normalization
pred = 1.0 - d1[:, 0, :, :]
pred = normPRED(pred)
# save results to test_results folder
save_output(img_name_list[i_test], pred, prediction_dir, sigma=float(args.sigma), alpha=float(args.alpha))
del d1, d2, d3, d4, d5, d6, d7
if __name__ == "__main__":
main()
when try to run above code face below error..
from model import U2NET # full size version 173.6 MB
^^^^^^^^^^^^^^^^^^^^^^^
ImportError: cannot import name 'U2NET' from 'model' (unknown location)
from u-2-net.
Related Issues (20)
- 对u2netp模型进行qat量化
- How can I input video or webcam in the test.py script?
- 能否麻烦将整个项目打个包(包含运行文件和预训练模型),集成一个 .bat 文件,点击运行即可使用? HOT 2
- 请问该模型只能输出二分类结果么?可以输出为多分类么?比如三分类 HOT 1
- Is it support person segmentation now? HOT 2
- 如何添加评价指标
- Can' Access Human Segmentation Model Weights HOT 1
- Usage on cross platform mobile devices using tenser flow or pytourch ( Special on Flutter )
- 请问大家,我需要前景而非mask,该怎样修改代码呢,感谢
- /alueror: At least one stride in the given numpy aray is mepative, ad tensors with nepative strides are not curently suported. (You can probably work around this by making a copy of your array with array.copy( ).)
- u2net_train.py returning ValueError HOT 1
- the effect of replacing background with U-2-Net is not as expected, anyone can offer a help
- can tell me , label mask must be 0 or 1,if 0 or 1,why binary is smooth, if dataset mask edge in (0,1),it can work? HOT 1
- The results are not good when the object has small holes. HOT 1
- 有什么办法只保留抠图部分尺寸,不需要原图尺寸大小,谢谢 HOT 1
- num_workers=1
- u2net for semantic segmentation
- 自己数据训练的u2net,归一化尺寸320,但是抠图效果边缘锯齿明显
- Paddlehub is no longer under maintenance, what should I do if an error message is installed
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from u-2-net.