0

I have some C# code for converting an omnicam picture to a normal image. However, the formula is behaving differently than expected.

Code:

  int Rin = 35; //Image specific variable
  int Rout = 237; //Image specific variable
  int cx = 312; //Image specific variable
  int cy = 239; //Image specific variable
  int width = (int) Math.Round(2 * Math.PI * Rout);
  int height = (int) Math.Round((double)(Rout - Rin));
  for (int i = 0; i < image.GetLength(0); i++)
      {
        double y1 = i / height;
        double r = Rin + (1 - y1 * height);
        for (int j = 0; j < image.GetLength(1); j++)
        {
          double x1 = j / width;
          double theta = -2 * Math.PI * (j / width);

          double xp = r * Math.Cos(theta) + cx;
          double yp = r * Math.Sin(theta) + cy;
          Console.WriteLine(theta + " = " + (-2 * Math.PI) + " * (" + j + " / " + width + ")");
          Console.WriteLine(xp + " = " + r + " * " + Math.Cos(theta) + " + " + cx);
          Console.WriteLine(yp + " = " + r + " * " + Math.Sin(theta) + " + " + cy);
          Console.WriteLine("");

          omnicam[i, j] = Color.FromArgb(1, 1, 1);
        }
      }

However, this prints out

0 = -6.28318530717959 * (82 / 1489)
348 = 36 * 1 + 312
239 = 36 * 0 + 239

If I print x1, it shows 0 for all values. However, I'm not sure why. The loop goes up to 895, and 895 / 1489 = 0.601... So why is it rounded down automatically?

JavaHR
  • 173
  • 1
  • 2
  • 8
  • `j` and `width` are both `int` therefore the calculation will be done using `int`. In this case, the result is truncated not rounded. Try casting them to `double` before doing the calculation, then use `Math.Round()` to round the result before finally casting it back to `int`. – Matthew Watson Jan 11 '18 at 09:14

1 Answers1

0

double x1 = j / width;

Both j and width are INTs.

double x1 = j / (double)width;

Will give you the expected result.

If both of the arguments in C# is a int, then the result will be a int.

If any of the arguments in C# is a double, a double divide is used which results in a double.

Verendus
  • 1,026
  • 1
  • 13
  • 26