2017-10-18 139 views
0

在cv :: mat中繪製矩形時出現問題。我正在Unity和C++之間進行通信以生成Android應用程序。在C++中使用cv :: Rectangle的問題

我使用統一的webcamtexture攝像頭,並使用PInvoke方法將信息發送到C++。一旦在C++代碼中,我想繪製一個矩形,但我在圖像中獲得了不止一個(見圖),我真的不明白爲什麼。我希望你能幫助我附上C++和C#代碼。

introducir la descripción de la imagen aquí

C#

void Update() 
{ 
    //texto.text = texto.text + "/"+ testo().ToString(); 
    imgData = null; 
    imgData = new byte[width * height * 3]; 
    resultado = null; 
    resultado = new byte[width * height * 3]; 
    color = webcam.GetPixels32(); 
    int bytesPerPixel = 3; 
    const int indexR = 0; 
    const int indexG = 1; 
    const int indexB = 2; 
    for (var i = 0; i < color.Length; i++) 
    { 
     imgData[(i * bytesPerPixel) + indexR] = color[i].r; 
     imgData[(i * bytesPerPixel) + indexG] = color[i].g; 
     imgData[(i * bytesPerPixel) + indexB] = color[i].b; 
    } 
    color = null; 
    ProcessFrame(imgData, resultado, 0, 0, 0,0, nuevo); 
    nuevo = false; 
    textura2 = new Texture2D(width, height, TextureFormat.RGB24, false); 
    textura2.LoadRawTextureData(resultado); 
    textura2.Apply(); 
    renderer.material.mainTexture = textura2; 
    textura2 = null; 
    Resources.UnloadUnusedAssets(); 
} 

C++

void ProcessFrame(unsigned char* arr, unsigned char* resu,int posx, int posy, int poswidth, int posheight,bool nuevo) { 
    Mat dst;//dst image 
    trueRect.x = 150; 
    trueRect.y = 150; 
    trueRect.width = 100; 
    trueRect.height = 100; 
    wi = poswidth; 
    he = posheight; 
    mal = 20; 
    dst = Mat(tamWid,tamHeid,CV_8UC3, arr); 
    rectangle(dst, Point(50,50), Point(100,100), cv::Scalar(0, 255, 255)); 
    copy(dst.datastart, dst.dataend, resu); 
} 
+0

我不能肯定地說,但我的猜測是你已經將行移動了列,那就是OpenCV按行存儲圖像數據和按照其他方式存儲Unity(OpenGL)。你能調試這個C++代碼並用ImageWatch插件檢查矩陣嗎?或者簡單地用'cv :: imwrite'保存dst。此外,你應該先複製dst,然後再繪製它。至於現在你改變原始圖像並複製它,所以兩者都會有矩形。 – R2RT

+0

對不起,但我不確定你在告訴我什麼。我在前一個函數中傳遞了圖像大小的信息,它的分辨率爲640x480。我不太清楚你想要說些什麼,並且更不用說你可以如何解決它。 關於調試,我不能使用,因爲我使用統一的共享庫來創建一個Android應用程序。 –

+0

@ R2RT opencv是行主要。問題是'dst = Mat(tamWid,tamHeid,CV_8UC3,arr);'它是行,列,在構造函數中,所以它應該是'dst = Mat(tamHeid,tamWid,CV_8UC3,arr);'那麼你有還要檢查數據是列式還是行式,如果列式明智,您需要像以前一樣離開,並將墊子轉位 – api55

回答

1

只是爲了完整性,我將發佈答案的緣故。

的問題是在該行

dst = Mat(tamWid,tamHeid,CV_8UC3, arr); 

constructor of Mat需要作爲前兩個參數行,然後列,你的情況是列和行。

所以它應該是:

dst = Mat(tamHeid,tamWid,CV_8UC3, arr); 

其他考慮

正如我在評論中說,你應該知道錯誤的某些可能的來源,因爲該公約沒有在OpenCV中相同,統一。其中之一就是2D座標系的原點。在OpenCV的左上方和Unity中,或者至少GetPixels32函數位於圖像的左下角。

另一個可能的問題是色彩空間。 OpenCV在加載,保存和其他功能時需要BGR圖像,而在其他框架中,它們使用RGB或RGBA,這是32位。