【UE4】复杂背景人像抠图-飞浆AI-paddlepaddle深度训练模型

前言:运用到Python3.7,UEC++,蓝图;实现复杂背景人物使用PaddleHub深度训练模型进行抠像后在UE中使用(纯色背景人物仅材质就可实现)使用到的训练模型:deeplabv3p_xception65_humanseg


1.准备工作:

  • 安装Python3.7或者使用Anaconda套件进行安装(python3.7对应版本如图)【UE4】复杂背景人像抠图-飞浆AI-paddlepaddle深度训练模型_第1张图片
  • 安装Anaconda所有选项请全勾选(即使有红字提示)
  • 使用cmd验证是否安装成功:
    python
    【UE4】复杂背景人像抠图-飞浆AI-paddlepaddle深度训练模型_第2张图片
  • 使用pip install xxx进行所需模块的安装
  • 后续如遇到错误修复注意事项:
    //如在运行过程中命令行报错,尝试使用以下几种方法在cmd中解决:
    
    //1.模块xxx缺少(ModuleNotFoundError: No module named xxx)
    pip install xxx
    
    //2.模块xxx版本错误(如错误提示:xxx>=或>或<=或=x.x.x
    
    //3.模块xxx需要更新
    pip install xxx --upgrade

    2.编写py,bat,vbs代码并解决后续错误:

  • 1.py(C:/imgcut/1.py):

#!/usr/bin/env python
# coding: utf-8

#请使用ipython运行:ipython 1.py IMGname

#安装 paddlehub 库
get_ipython().system('pip install paddlehub==1.6.0 -i https://pypi.tuna.tsinghua.edu.cn/simple')
# 安装deeplabv3p_xception65_humanseg模型
get_ipython().system('hub install deeplabv3p_xception65_humanseg==1.0.0')

import sys
import paddlehub as hub
import matplotlib.image as mpimg
get_ipython().run_line_magic('matplotlib', 'inline')

module = hub.Module(name="deeplabv3p_xception65_humanseg")#预加载图像分割模型
test_img_path = ["./" + str(sys.argv[1])]#["./t6.png"] #传入图片名
input_dict = {"image": test_img_path}

# 执行模型分割方法展示结果
results = module.segmentation(data=input_dict)#根据图像分割模型对jpg进行分割
print(results)
  • run.bat(C:/imgcut/run.bat):

cd /d C:/imgcut/&&ipython 1.py t10.png
  • Run.vbs(C:/imgcut/Run.vbs)://便于UE中调用后台运行

    Set objShell = WScript.CreateObject("WScript.Shell")
    objShell.Run "C:\imgCut\Run.bat", 0,true
    

    此时cmd运行bat中的命令会报错,以下开始解决问题:

  1. pip install ipython

【UE4】复杂背景人像抠图-飞浆AI-paddlepaddle深度训练模型_第3张图片  安装好ipython,且根据warnning提示路径,复制Scripts文件夹,配置环境变量path新增ipython文件夹路径 

 2.提示缺少模块:

pip install 模块名

(安装命令如:pip install paddle)

(此时再报错如:No Moudle named 'common',请逐步进行安装所需的模块,再执行安装paddle模块,以此重复)

(如提示缺少 paddle.fluid 模块请执行: pip install paddlepaddle)
(如提示缺少 git 模块请执行: pip install gitpython)

 3.提示DLL load failed:找不到指定的模块。【UE4】复杂背景人像抠图-飞浆AI-paddlepaddle深度训练模型_第4张图片

此处提示导入core_avx失败:
ImportError: DLL load failed: 找不到指定的模块。
Error: Can not import avx core while this file exists: C:\Users\666\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.7_qbz5n2kfra8p0\LocalCache\local-packages\Python37\site-packages\paddle\fluid\core_avx.pyd
---------------------------------------------------------------------------
ImportError                               Traceback (most recent call last)

--进入python37安装目录:
复制Python37\site-packages\paddle\libs中的所有Dll文件
粘贴到:Python37\site-packages\paddle\fluid文件夹 

 4.错误提示JSONDecodeError: Expecting value: line 1 column 1 (char 0):

手动import paddlehub发现失败,是因为paddlepaddle并没有安装正确

So重新安装anaconda3,使用pip再次安装paddlepaddle==2.2.0


安装paddlepaddle:
1、手动下载whl:
https://mirror.baidu.com/pypi/packages/a1/c2/7809f9f170232611855ac857fbbc8bec26d63858e0ec1634afed6d2d931c/paddlepaddle_gpu-2.3.1-cp37-cp37m-win_amd64.whl
2、打开次文件进行安装

(如遇到下载whl文件失败时都可如此手动进行下载安装)

5.下载某个模块后安装仍然失败

pip install -i https://pypi.tuna.tsinghua.edu.cn/simple --trusted-host pypi.tuna.tsinghua.edu.cn --user 加你想要下载的模块

6.安装paddlehub模块时失败

错误为某些模块版本不兼容,重新安装提示的版本模块带--upgrade,拒绝访问加上参数--user即可:

如:ERROR:huggingface-hub 0.8.1 has requirement packaging>=20.9,butxxxxxxxxxxx

解决:pip install -i https://pypi.tuna.tsinghua.edu.cn/simple --trusted-host pypi.tuna.tsinghua.edu.cn --user --upgrade packaging>=20.9

解决所有错误问题后运行测试成功,图片输出到humanseg_output文件夹:

 3.创建UEC++项目并编写代码及控件蓝图:

  • 项目Build.cs中添加模块"ImageWrapper":
  • 创建新的蓝图函数库PYBPF类继承自BlueprintLibrary

PYBPF.h中:

// Fill out your copyright notice in the Description page of Project Settings.

#pragma once

#include "CoreMinimal.h"
#include "Kismet/BlueprintFunctionLibrary.h"
#include "Engine/Texture2D.h"
#include "PYBPF.generated.h"

/**
 * 
 */
UCLASS()
class NEWOPENCV_API UPYBPF : public UBlueprintFunctionLibrary
{
	GENERATED_BODY()
	

public:
	UFUNCTION(BlueprintCallable,Category = "BPF")//处理图片
	static void CutIMG(FString batCommand,bool& cuted);

	UFUNCTION(BlueprintCallable)//获取图片
	static UTexture2D* GetIMG(FString path, bool& IsValid, int& Width, int& Height);
	
};

PYBPF.cpp中:

// Fill out your copyright notice in the Description page of Project Settings.


#include "PYBPF.h"
#include "Runtime/Core/Public/HAL/FileManager.h"
#include "Runtime/Core/Public/Misc/FileHelper.h"
#include "IImageWrapper.h"
#include "IImageWrapperModule.h"
#include "Kismet/KismetStringLibrary.h"

const FString vbsPath = FString("C:/imgcut/Run.vbs");
const FString batPath = FString("C:/imgcut/run.bat");

void UPYBPF::CutIMG(FString batCommand, bool& cuted)
{
	FString unuse,pngname;
	UKismetStringLibrary::Split(batCommand," ",unuse, pngname,ESearchCase::IgnoreCase,ESearchDir::FromEnd);
	UKismetStringLibrary::Split(pngname,".", pngname, unuse,ESearchCase::IgnoreCase,ESearchDir::FromEnd);
	FString imgpath = "C:/imgcut/humanseg_output/"+ pngname + ".png";
	if (FPaths::FileExists(imgpath))
	{
		cuted = true;
		return;
	}
	cuted = false;
	//写入文本到bat文件
	FFileHelper::SaveStringToFile(batCommand, *batPath);
	
	//等待0.2秒
	FPlatformProcess::Sleep(0.2f);
	//执行vbs文件
	//FString cmd = TEXT("wscript.exe ");
	//FPlatformProcess::CreateProc(*cmd,*vbsPath, true, false, false, nullptr, 0, nullptr, nullptr);
	FPlatformProcess::LaunchFileInDefaultExternalApplication(*vbsPath);
}

UTexture2D* UPYBPF::GetIMG(FString path,bool& IsValid,int& Width,int& Height)
{
	IsValid = false;
	UTexture2D* LoadedT2D = NULL;

	IImageWrapperModule& ImageWrapperModule = FModuleManager::LoadModuleChecked(FName("ImageWrapper"));
	TSharedPtr ImageWrapper = ImageWrapperModule.CreateImageWrapper(EImageFormat::PNG);

	TArray RawFileData;
	FFileHelper::LoadFileToArray(RawFileData, *path);
	
	if (ImageWrapper.IsValid() && ImageWrapper->SetCompressed(RawFileData.GetData(), RawFileData.Num()))
	{
		TArray UncompressedBGRA;
		if (ImageWrapper->GetRaw(ERGBFormat::BGRA, 8, UncompressedBGRA))
		{
			LoadedT2D = UTexture2D::CreateTransient(ImageWrapper->GetWidth(), ImageWrapper->GetHeight(), PF_B8G8R8A8);
			
			Width = ImageWrapper->GetWidth();
			Height = ImageWrapper->GetHeight();

			void* TextureData = LoadedT2D->PlatformData->Mips[0].BulkData.Lock(LOCK_READ_WRITE);
			FMemory::Memcpy(TextureData, UncompressedBGRA.GetData(), UncompressedBGRA.Num());
			LoadedT2D->PlatformData->Mips[0].BulkData.Unlock();

			LoadedT2D->UpdateResource();
			if (LoadedT2D == nullptr)
			{return NULL;}
		}
	}
	// Success!
	IsValid = true;
	return LoadedT2D;
}
  • 编译打开项目;创建新的用户控件:【UE4】复杂背景人像抠图-飞浆AI-paddlepaddle深度训练模型_第5张图片

【UE4】复杂背景人像抠图-飞浆AI-paddlepaddle深度训练模型_第6张图片

  •  创建空白关卡;编辑关卡蓝图,开始运行时创建控件到视口:【UE4】复杂背景人像抠图-飞浆AI-paddlepaddle深度训练模型_第7张图片

 空白地图可自己添加个背景

 4.运行UE项目输入指定图片处理效果:

 

你可能感兴趣的:(UE4,python,ue4,paddlepaddle,人工智能,c++)