지난 포스트에서 OpenCV 개발환경을 구축하였고 비주얼스튜디오에서 OpenCV를 이용한 mp4 동영상 프로젝트도 만들어 보았다. 이제 유니티를 위한 플러그 인을 만들어 보자. 먼저 비주얼스튜디오에서 플러그인 dll 프로젝트를 만들자. 유니티에서 텍스처로 보내오는 이미지를 이용하여 동영상 파일을 만드는 플러그인을 제작하려고 한다.
1. 비주얼스튜디오에서 dll 프로젝트를 만든다.
2. exe가 아닌 dll 프로젝트를 설정하자.
3. OpenCV 개발환경을 만든다. include 디렉토리와 Lib 디렉토리를 설정해주고 필요한 lib파일을 추가한다.
- 유니티에서 RGBA 이미지 포맷으로 받고 이를 BGR포맷으로 변경하여 사용한다. OpenCV에는 RGBA가 없다. 다음은 플러그인 프로그램이다.
#include <iostream>
#include "opencv2/highgui.hpp"
#include "opencv2/core.hpp"
#include "opencv2/opencv.hpp"
using namespace cv;
using namespace std;
cv::VideoWriter videoWriter;
double videoFPS = 30.0;
int imageWidth = 256;
int imageHeight = 256;
struct Color32
{
uchar red;
uchar green;
uchar blue;
uchar alpha;
};
//videoWriter는 image must be in BGR format이어야 한다.
//OpenCV doesn't support ARGB or ABGR formats
extern "C"
{
__declspec(dllexport) int myOpenVideo(char* filename, int width, int height, float fps)
{
videoFPS = (double) fps;
imageWidth = width;
imageHeight = height;
videoWriter.open(filename, cv::VideoWriter::fourcc('M', 'J', 'P', 'G'), videoFPS, cv::Size(imageWidth, imageHeight), true);
if (!videoWriter.isOpened())
{
std::cout << "Can't write video !!! check setting" << std::endl;
return -1;
}
std::cout << "Open Video file operation is success!!" << std::endl;
return 0;
}
__declspec(dllexport) void myAddFrame(Color32 **rawImage)
{
Mat im(imageHeight, imageWidth, CV_8UC4, *rawImage);
cv::cvtColor(im,im, cv::COLOR_RGBA2BGR);
cv::flip(im, im, -1);
videoWriter << im;
}
__declspec(dllexport) int myCloseVideo()
{
videoWriter.release();
return 0;
}
}
- 유니티의 프로젝트의 Assets 폴더 아래에 Plugin 폴더를 만들고 거기에 위에서 작성한 lib와 dll 파일을 복사하여 준다. 안드로이드나 iOS에서 사용할 예정이라면 Plugin 아래에 추가로 폴더를 더 만들고 각각의 플랫폼에 맞는 확장자를 만들어 줘야 한다. 유니티에서는 다음과 같이 호출할 수 있다.
using System.Runtime.InteropServices;//추가
public class MyVideoCapture : MonoBehaviour
{
[DllImport("MyVideoWriter")] //추가
public static extern int myOpenVideo(string filename, int width, int height, float fps);
[DllImport("MyVideoWriter")]//추가
public static extern void myAddFrame(ref Color32[] rawImage);
[DllImport("MyVideoWriter")]//추가
public static extern void myCloseVideo();
void Start()
{
myOpenVideo("capture4.mp4", 256, 256, 30.0f);
}
void Update()
{
Texture2D tex = getFrame();// 각자 작성
Color32[] pixels = tex.GetPixels32();
if (pixels != null)
{
myAddFrame(ref pixels);//Plugin
}
}
...
void OnDestroy()
{
myCloseVideo();//Plugin
}
}
위 OpenCV를 이용하는 플러그인은 유니티에서 매우 다양한 기능을 쉽게 구현하게 만들어 준다.
반응형