获得检测到的直线的长度和角度

时间:2015-02-20 00:43:19

标签: android opencv

我正在开发一个Android应用程序。我可以使用Canny和Hough变换检测线条,但我不知道如何获得检测到的线条的角度和长度,你能帮忙吗?这是代码:

public void countStraightLines(View view) {
    try{
        int iCannyLowerThreshold = 45;  
        int iCannyUpperThreshold = 75; 

        Mat rgba = Utils.loadResource(getApplicationContext(), res);
        Bitmap bmp = Bitmap.createBitmap(rgba.width(), rgba.height(), Bitmap.Config.ARGB_8888);
        Mat gray = new Mat ();
        Imgproc.cvtColor(rgba, gray, Imgproc.COLOR_BGRA2GRAY, 4);
        Imgproc.Canny(gray, gray, iCannyLowerThreshold, iCannyUpperThreshold); 
        Utils.matToBitmap(gray, bmp);
        imgSource.setImageBitmap(bmp);

    } catch (IOException e) {
        Log.e(TAG, "ERROR Loading Mat");
        e.printStackTrace();
    }


}

@Override
public void onItemSelected(AdapterView<?> parent, View view, int position,
        long id) {

    Globals.pictSelected=parent.getItemAtPosition(position).toString();
    res = getResources().getIdentifier(parent.getItemAtPosition(position).toString(), "drawable", this.getPackageName());

    try {

        Mat rgba = Utils.loadResource(getApplicationContext(), res);
        Bitmap bmp = Bitmap.createBitmap(rgba.width(), rgba.height(), Bitmap.Config.ARGB_8888);
        Mat gray = new Mat ();
        Imgproc.cvtColor(rgba, gray, Imgproc.COLOR_BGRA2GRAY, 4);

        int iCannyLowerThreshold = 45;  
        int iCannyUpperThreshold = 75;  
        int iHoughLinesThreshold = 50;
        int iHoughLinesMinLineSize = 40;
        int iHoughLinesGap = 20;

        Imgproc.Canny(gray, gray, iCannyLowerThreshold, iCannyUpperThreshold);  
        Mat lines = new Mat();
        Imgproc.HoughLinesP(gray, lines, 1, Math.PI/180, iHoughLinesThreshold, iHoughLinesMinLineSize, iHoughLinesGap);  

        int x = 0;
        char s = 'N';
        for (; x < Math.min(lines.cols(), 100); x++)   
        {  
            double[] vec = lines.get(0, x);  

            if (vec == null)  
                break;  

            double x1 = vec[0], y1 = vec[1], x2 = vec[2], y2 = vec[3];  
            Point start = new Point(x1, y1);  
            Point end = new Point(x2, y2);  

            Core.line(rgba, start, end, new Scalar(255, 0, 0, 255), 1);  

            if (x >= 40){s = 'C';}
            else {s = 'S';}
         }
        text.setText("Line Count: " + x + " and The Picture is " + s);
        Utils.matToBitmap(rgba, bmp);
        imgSource.setImageBitmap(bmp);

    } catch (IOException e) {
        Log.e(TAG, "ERROR Loading Mat");
        e.printStackTrace();
    }

}

谢谢!

1 个答案:

答案 0 :(得分:0)

好吧,看起来你有一个起点和一个终点 - 长度只是((starty-endy)^ 2 +(startx-endx)^ 2)^(1/2)。您可以通过使用两个向量A和B A.B=|A|*|B|*cos(alpha)的点积这一事实来获得它们之间的角度,其中alpha是它们之间的角度。所以alpha= arccos((A.B)/(|A|*|B|))