Как исправить визуализацию изображения в оттенках серого в Unity3d с помощью OpenCV4? - PullRequest
0 голосов
/ 23 апреля 2019

Я подключил OpenCV 4.1.0 к проекту Unity3d, создавая DLL с Android Studio (как сказано в этой статье LINK ).Я хотел бы преобразовать текстуру в оттенках серого, используя DLL на платформе Android.

У меня есть плоскость gameObject в сцене с текстурой.

Просмотр сцены View Scene

Настройки текстуры Texture Settings

Здесь код в:

C ++

extern "C" {
    uint8_t *resultBuffer;
    int bufferWidth;
    int bufferHeight;

    int InitCV_Internal(int width, int height) {
        size_t size = width * height * 4;
        resultBuffer = new uint8_t[size];

        bufferWidth = width;
        bufferHeight = height;

        return 0;
    }

    // Convert the image in grayscale.
    uint8_t *SubmitFrame_Internal(int width, int height, uint8_t *buffer) {
        Mat inFrame = Mat(height, width, CV_8UC4, buffer);
        Mat outFrame(inFrame.rows, inFrame.cols, CV_8UC4, Scalar(0,0,0));

        cvtColor(inFrame, outFrame, COLOR_RGBA2GRAY);

        size_t size = bufferWidth * bufferHeight * 4;
        memcpy(resultBuffer, outFrame.data, size);

        inFrame.release();
        outFrame.release();

        return resultBuffer;
    }

C #

NativeLibAdapter класс для обработки функций DLL.

using System.Runtime.InteropServices;
using System;
using UnityEngine;

public class NativeLibAdapter {

    [DllImport("native-lib")]
    private static extern int InitCV_Internal(int width, int height);

    [DllImport("native-lib")]
    private static extern IntPtr SubmitFrame_Internal(int width, int height, IntPtr buffer);

    public static int InitCVAdapter(int width, int height)
    {
        int result = InitCV_Internal(width, height);

        return result;
    }

    public static IntPtr SubmitFrameAdapter(int width, int height, IntPtr buffer)
    {
        IntPtr bufferResult = SubmitFrame_Internal(width, height, buffer);

        return bufferResult;
    }
}

Test класс прикреплен к объекту Plane сцены.

using System;
using System.Runtime.InteropServices;
using UnityEngine;
using UnityEngine.UI;

public class Test : MonoBehaviour
{
    private Texture2D texIn;
    private Color32[] pixel32;
    private GCHandle pixelHandle;
    private IntPtr pixelPtr;

    public Text text;

    void Start()
    {
        texIn = (Texture2D)GetComponent<Renderer>().material.mainTexture;
        InitTexture();
    }

    void InitTexture()
    {
        pixel32 = texIn.GetPixels32();
        // Pin pixel32 array
        pixelHandle = GCHandle.Alloc(pixel32, GCHandleType.Pinned);
        // Get the pinned address
        pixelPtr = pixelHandle.AddrOfPinnedObject();

        NativeLibAdapter.InitCVAdapter(texIn.width, texIn.height);

        // MatToTexture2D
        IntPtr result = NativeLibAdapter.SubmitFrameAdapter(texIn.width, texIn.height, pixelPtr);
        int bufferSize = texIn.width * texIn.height * 4;
        byte[] rawData = new byte[bufferSize];

        if (result != IntPtr.Zero)
        {
            Marshal.Copy(result, rawData, 0, bufferSize);
            texIn.LoadRawTextureData(rawData);
            texIn.Apply();
            // text.text = result.ToString();
        }
    }

    void OnApplicationQuit()
    {
        // Free handle
        pixelHandle.Free();
    }
}

После сборки After build Слева мой результат на Android-устройстве, справа ожидаемый результат (сгенерированный с помощью Photoshop).Текст "-1068498944" я вставил только для отладки.

Что не так?Есть идеи?Большое вам спасибо!

...