0

I'm trying to detect contours in a scene and add a collider to every detected object, I used the canny edge detector to get the coordinates of the detected objects.

Here is my output image

I need to add a collider to each black line to prevent my game object from going in/out of that area but I don't know how to do so exactly. The findContours function returns a list of detected contours each stored as a vector of points but how do I use that to generate a collider?

Thank you for your help.

Update

Here is my source code (for the update method)

 void Update ()
    {
        if (initDone && webCamTexture.isPlaying && webCamTexture.didUpdateThisFrame) {

            //convert webcamtexture to mat
            Utils.webCamTextureToMat (webCamTexture, rgbaMat, colors);
            //convert to grayscale
            Imgproc.cvtColor (rgbaMat, grayMat, Imgproc.COLOR_RGBA2GRAY);

            //Blurring
            Imgproc.GaussianBlur(rgbaMat,blurMat,new Size(7,7),0);
            Imgproc.Canny(blurMat, cannyMat, 50,100);
            Mat inverted = ~cannyMat;
            //convert back to webcam texture
            Utils.matToTexture2D(inverted, texture, colors);

            Mat hierarchy = new Mat();
            List<MatOfPoint> contours = new List<MatOfPoint>();
            Imgproc.findContours(inverted, contours, hierarchy, Imgproc.RETR_LIST, Imgproc.CHAIN_APPROX_SIMPLE);


        }
    }

1 Answers1

0

Use a PolygonCollider2d.

You can edit the collider at runtime using the SetPath function, to which you will pass a list of 2d points (that you already computed using the findContours function.

You can have several paths in the polygon if you want your collider to have holes.

Basile Perrenoud
  • 4,039
  • 3
  • 29
  • 52
  • Yes, you can add colliders on 3d objects. The fact that it is a 2d collider doesn't change. Every object is 3d in unity. even the rect transform have a z value. You can add a collider using `AddComponent` In code. But you don't have to add a new one every frame, juste edit the list of point of an existing one – Basile Perrenoud Apr 05 '18 at 08:17