How to find bounded shape for figures ( Java application )?

asked 2016-11-06 07:00:19 -0500

alexkhromov gravatar image

Hi all. I am new in opencv and image processing. And it is really hard for me to figure out can this library solve my problem or not. So i will be very appreciate for any answer and help. My problem is that a have a service that make some calculations and return me 2D array ( boolean [][] arr it is just example):
{ 0,.0,............. .... ............0 }
.................... ...
{ 0,0,0,0,0,1,1,.... .... ............0 }
{ 0,0,0,1,1,1,1,.... .... ............0 }
{ 0,0,1,1,0,1,1,0,1, .... ............0 }
{ 0,0,0,1,1,1,1,1,1, .... ............0 }
..................................
{ 0,.0,............. .... ............0 }
Based on this array i am create simple image of the same size as an array.
Where value is true the pixel is WHITE
image description
Actually it can be any abstract shape and it also can be more than 1 shape.
So it possible to have 2 or 3 shapes and they will be different. The problem is that i don't know how to find bounded shape / contour for figures.
As a result i want to have only contours and know points of this contour. I am try to use a code like next : Imgproc.findContours(). And it calculates about 2000 contours for given image. It happens because mix of true and false values in array. But instead i need only 1 contour if only one shape present in image.

Thanks for any help.

edit retag flag offensive close merge delete

Comments

Actually i am found answer:

Mat src = new Mat( im.getHeight(), im.getWidth(), CvType.CV_8UC1 );
src.put( 0, 0, ( ( DataBufferByte ) im.getRaster().getDataBuffer() ).getData() );
List< MatOfPoint > contours = new ArrayList<>();
Imgproc.findContours( src, contours, new Mat(), Imgproc.RETR_TREE, Imgproc.CHAIN_APPROX_SIMPLE, new Point( 0, 0 ) );

 for ( MatOfPoint point: contours ) {

      MatOfPoint2f source = new MatOfPoint2f();
      point.convertTo( source, CvType.CV_32F );
      MatOfPoint2f gb= new MatOfPoint2f();
      Imgproc.GaussianBlur( source, gb, new Size( 3, 3 ), 0, 0 );
      Polygon polygon = new Polygon();
      gb.toList().stream().forEach( p -> polygon.addPoint( ( int ) p.x, ( int ) p.y ) );
      g2.setColor( Color.WHITE);
alexkhromov gravatar imagealexkhromov ( 2016-11-21 12:02:09 -0500 )edit