Question

I want to process image with pointer to make it faster.At first,I do it like this

unsafe
    {
        double a = 288 / 55;
        double b = -215 * 288 / 55;
        MIplImage ss = diff.MIplImage;
        for (int i = 0; i < ss.height; i++)
        {
            IntPtr ptr = ss.imageData + i * ss.widthStep;
            for (int j = 0; j < ss.width; j++)
            {
                if (a * j - i + b > 0)
                    ((byte*)(ptr))[j] = 0;
            }
        }
    }

and it performs well(0.5ms while 4ms without pointer).

Then I find that the managed objects should be fixed to prevent relocation.So I think it would be like this

Image<Gray, byte> diff = new Image<Gray, byte>(frame.Width,frame.Height);
fixed (void* p_temp=diff.Ptr.ToPointer()){}

or

fixed (byte* p_temp=(byte*)temp.Ptr){}

But it is wrong.So how to fix the Image? And how to use pointer with emgucv? I am really confused.Thanks!

unsafe
        {
            var data = diff.Data;
            int stride = diff.MIplImage.widthStep;
            byte* p;
            fixed (byte* pData = data)
            {
                for (int i = 0; i < diff.Height; i++)
                {
                    p = pData + i * stride;
                    for (int j = 0; j < diff.Width; j++)
                    {
                        if (a * j - i + b > 0)
                            *(p + j) = (byte)0;
                    }

                }
            }
        }
Was it helpful?

Solution

I just made a quick demo (not production quality code) to give you a starting working example on unsafe emgu usage.

        Image<Gray, Byte> img = new Image<Gray, byte>(510, 510);            
        // Fill image with random values
        img.SetRandUniform(new MCvScalar(), new MCvScalar(255));
        // Show Image
        ImageViewer.Show(img);
        var data = img.Data;
        int stride = img.MIplImage.widthStep;
        fixed (byte* pData = data)
        {
            for (int i = 0; i < 255 * stride; i++)
                *(pData + i) = (byte)(i % stride);
        }
        // Show Image Again
        ImageViewer.Show(img);

First I fill image with random noise and then fill some rows with a gradient :-) enter image description here

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top