2017-08-13 232 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色彩空间,