2017-08-13 233 views
0

我目前正試圖實現OpenCV的功能,它使圖像的顏色變爲透明。我用這個thread作爲指導。 目前它不工作,我不確定是否因爲我轉移到C#或其他錯誤。Emgu C#OpenCV:使顏色黑色透明

public Image<Bgr, Byte> BlackTransparent(Image<Bgr, Byte> image) 
     { 
      Mat imageMat = image.Mat; 
      Mat finalMat = new Mat(imageMat.Rows, imageMat.Cols, Emgu.CV.CvEnum.DepthType.Cv8U, 4); 
      Mat tmp = new Mat(imageMat.Rows, imageMat.Cols, Emgu.CV.CvEnum.DepthType.Cv8U, 1); 
      Mat alpha = new Mat(imageMat.Rows, imageMat.Cols, Emgu.CV.CvEnum.DepthType.Cv8U, 1); 

      CvInvoke.CvtColor(imageMat, tmp, Emgu.CV.CvEnum.ColorConversion.Bgr2Gray); 
      CvInvoke.Threshold(tmp, alpha, 100, 255, Emgu.CV.CvEnum.ThresholdType.Binary); 


      VectorOfMat rgb = new VectorOfMat(3); 

      CvInvoke.Split(imageMat, rgb); 

      Mat[] rgba = { rgb[0], rgb[1], rgb[2], alpha }; 

      VectorOfMat vector = new VectorOfMat(rgba); 

      CvInvoke.Merge(vector, finalMat); 

      return finalMat.ToImage<Bgr, Byte>(); 
     } 

如果有人有想法或建議,我將不勝感激。

布魯諾

+0

定義「不工作」。 |兩個相當明顯的錯誤是,'tmp'和'alpha'被創建爲4通道,但'tmp'被用來保存轉換爲灰度的結果(僅1通道),'alpha'意味着透明通道(只有1個頻道)。這可能不會導致問題,但它無論如何都是誤導性和浪費的。 –

+0

該函數返回它收到的相同圖像作爲參數。但是,謝謝你與渠道tipp ...我會改變 – Bruno

+0

啊,只是注意到另一件事:因爲你增加透明度,不應該返回類型像'Image '(BGRA而不是BGR色彩空間)? –

回答

1
public Image<Bgra, Byte> BlackTransparent(Image<Bgr, Byte> image) 
     { 
      Mat imageMat = image.Mat; 
      Mat finalMat = new Mat(imageMat.Rows, imageMat.Cols, Emgu.CV.CvEnum.DepthType.Cv8U, 4); 
      Mat tmp = new Mat(imageMat.Rows, imageMat.Cols, Emgu.CV.CvEnum.DepthType.Cv8U, 1); 
      Mat alpha = new Mat(imageMat.Rows, imageMat.Cols, Emgu.CV.CvEnum.DepthType.Cv8U, 1); 

      CvInvoke.CvtColor(imageMat, tmp, Emgu.CV.CvEnum.ColorConversion.Bgr2Gray); 
      CvInvoke.Threshold(tmp, alpha, 100, 255, Emgu.CV.CvEnum.ThresholdType.Binary); 


      VectorOfMat rgb = new VectorOfMat(3); 

      CvInvoke.Split(imageMat, rgb); 

      Mat[] rgba = { rgb[0], rgb[1], rgb[2], alpha }; 

      VectorOfMat vector = new VectorOfMat(rgba); 

      CvInvoke.Merge(vector, finalMat); 

      return finalMat.ToImage<Bgra, Byte>(); 
     } 

函數的返回值類型是錯誤的...而不是BGR的顏色空間應該是BGRA色彩空間,