Skip to content

Instantly share code, notes, and snippets.

@tosinamuda
Created March 27, 2019 09:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tosinamuda/b4c56f00322ff15aff89db7df0570ab5 to your computer and use it in GitHub Desktop.
Save tosinamuda/b4c56f00322ff15aff89db7df0570ab5 to your computer and use it in GitHub Desktop.
Convert Image File to Matrix with EmguCV C# and Save Matrix as ImageFile
using OpenCV = Emgu.CV;
public class Utilities{
public static MathNet.Numerics.LinearAlgebra.Matrix<double>[] LoadImageMatrix(string path)
{
OpenCV.Mat mat = OpenCV.CvInvoke.Imread(path, OpenCV.CvEnum.ImreadModes.AnyColor);
OpenCV.Image<OpenCV.Structure.Bgr, double> image = mat.ToImage<OpenCV.Structure.Bgr, double>();
OpenCV.Image<OpenCV.Structure.Gray, double> blue = image[0];
OpenCV.Image<OpenCV.Structure.Gray, double> green = image[1];
OpenCV.Image<OpenCV.Structure.Gray, double> red = image[2];
OpenCV.Matrix<double> matrixRed = new OpenCV.Matrix<double>(red.Height, red.Width, red.NumberOfChannels);
OpenCV.Matrix<double> matrixBlue = new OpenCV.Matrix<double>(blue.Height, blue.Width, blue.NumberOfChannels);
OpenCV.Matrix<double> matrixGreen = new OpenCV.Matrix<double>(green.Height, green.Width, green.NumberOfChannels);
red.CopyTo(matrixRed);
blue.CopyTo(matrixBlue);
green.CopyTo(matrixGreen);
return new OpenCV.Matrix<double>[3] {matrixRed, matrixGreen, matrixBlue };
}
public static bool WriteImage(String path, OpenCV.Matrix<double> [] matrices)
{
OpenCV.Matrix<double> [] BRGMatrices = Converters.ToBRGMatrix(matrices);
double[,,] ThreeDMatrix = new double[BRGMatrices[0].Rows, BRGMatrices[0].Cols, 3];
Parallel.For(0, BRGMatrices.Length, index =>
{
for (int i = 0; i < BRGMatrices[0].Rows; i++)
for (int j = 0; j < BRGMatrices[0].Cols; j++)
ThreeDMatrix[i, j, index] = BRGMatrices[index][i, j];
});
OpenCV.Image<OpenCV.Structure.Bgr, double> image = new OpenCV.Image<OpenCV.Structure.Bgr, double>(ThreeDMatrix);
return OpenCV.CvInvoke.Imwrite(path, image, new KeyValuePair<OpenCV.CvEnum.ImwriteFlags, int>(OpenCV.CvEnum.ImwriteFlags.JpegQuality, 100)) ;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment