Nested for thread conversion

1

I have the following% nested for that runs the entire length of a bitmap image in C #. I would like to run the second for threads to run parallel.

Bitmap alterado = new Bitmap(original.Width, original.Height);

//Convertendo para tons de Cinza
for (int i = 0; i < original.Width; i++)
{
    for (int j = 0; j < original.Height; j++)
    {
        Color corOriginal = original.GetPixel(i, j);
        int escalaCinza = (int)((corOriginal.R * 0.3) + (corOriginal.G * 0.49) + (corOriginal.B * 0.11));
        Color CorEmEscalaDeCinza = Color.FromArgb(escalaCinza, escalaCinza, escalaCinza);
        alterado.SetPixel(i, j, CorEmEscalaDeCinza);
    }
}

return alterado;

How can I do this?

    
asked by anonymous 01.12.2016 / 19:11

1 answer

1

Try this:

Parallel.For(0, original.Height, j => {
    for (int i = 0; i < original.Width; i++) {
        Color corOriginal = original.GetPixel(i, j);
        int escalaCinza = (int)((corOriginal.R * 0.3) + (corOriginal.G * 0.49) + (corOriginal.B * 0.11));
        Color CorEmEscalaDeCinza = Color.FromArgb(escalaCinza, escalaCinza, escalaCinza);
        alterado.SetPixel(i, j, CorEmEscalaDeCinza);
    }
});

Keep in mind that using the same algorithm that is used for sequencing in parallel is not always the best solution. You're comparing the wrong things. In parallel should do otherwise, there maybe won. Other than that, read what I mentioned above and the link I provided there.

Read about LockBits . It would also work with lock , but it is less efficient.

    
01.12.2016 / 20:46