Hough变换代码为学校

时间:2017-05-23 09:21:52

标签: c#

您好我为hough变换编写代码,累加器空间将在程序中查看但我不知道我的代码有什么问题。请帮忙

public Image<Rgb, Byte> houghTransform(Image<Gray, Byte> input)
    {
        int width = input.Width, height = input.Height;

        //1. create accumulator space
        double MaxRho = Math.Sqrt(((width / 2) * (width / 2)) + ((height / 2) * (height / 2)));
        double MaxTheta = Math.PI * 2;

        int[,] accumulator = new int[width * 2,height*2];

        for (int i=0;i< width;i++)
            for (int j = 0; j < height; j++)
            {
                accumulator[i, j] = 0;
            } 

        //2. Loop for point in image
        for (int i = 0; i < width; i++)
            for (int j = 0; j < height; j++)
                if (input.Data[j, i, 0] == 0)   //0 for black, 255 for white
                {
                    for (int k = 0; k < height; k++)
                    {
                        double rho = ((double)(i - (width / 2)) * Math.Cos((MaxTheta/height) * (double)k)) + ((double)(j - (height / 2)) * Math.Sin((MaxTheta / height) * (double)k));
                        int newRho = (int)((rho / MaxRho) * width);
                        if(newRho >= 0 && newRho < width) accumulator[newRho, k]++;
                    }
                }

        int maxima = 0;
        for (int i = 0; i < width; i++)
            for (int j = 0; j < height * 2; j++)
            {
                if (accumulator[i, j] > maxima)
                { maxima = accumulator[i, j];  }
            }

        //3. Tresholding the acc 
        for (int i = 0; i < width; i++)
            for (int j = 0; j < height ; j++)
            {
                int temp = 0;
                if(maxima!=0) temp = (accumulator[i, j] / maxima) * 255;
                accumulator[i, j] = (byte)temp;
            }

        //4. Save to Image<Gray, Byte>
        Image<Rgb, Byte> output = new Image<Rgb, Byte>((int)width, height*2 );
        for (int i = 0; i < width; i++)
            for (int j = 0; j < height; j++)
            {
                output.Data[j, i, 0] = (byte)accumulator[i, j];
                output.Data[j, i, 1] = (byte)accumulator[i, j];
                output.Data[j, i, 2] = (byte)accumulator[i, j];
            }

        return output;

    }

测试结果:我的累加器只有4个点

img

我期待的是:

what the result must be

1 个答案:

答案 0 :(得分:1)

我做到了,所以问题在于阈值处理,必须首先转换为双倍进行计算然后再转换为整数。