UnsupportedOperationException: Mat data type is not compatible: 5

asked 2017-12-29 08:43:04 -0600

Aubin gravatar image
    public static Image Mat2Image( Mat m ) {
      int type = BufferedImage.TYPE_BYTE_GRAY;
      if ( m.channels() > 1 ) {
         type = BufferedImage.TYPE_3BYTE_BGR;
      }
      final int bufferSize = m.channels() * m.cols() * m.rows();
      final byte[] srcPixels = new byte[bufferSize];

      m.get( 0, 0, srcPixels );  <<<<<<<<<<<<<<<<<<<<<<<<<<<< UnsupportedOperationException here

      final BufferedImage image = new BufferedImage( m.cols(), m.rows(), type );
      final byte[] tgtPixels = ((DataBufferByte)image.getRaster().getDataBuffer()).getData();
      System.arraycopy( srcPixels, 0, tgtPixels, 0, srcPixels.length );
      return image;
   }

   public static void main( String[] args ) {
      final Mat   img     = Highgui.imread( "Screenshot_2017-12-29-10-49-48.png" );
      final Mat   templ   = Highgui.imread( "place.png" );
      final Mat   result  = new Mat();
      final int[] methods = {
         Imgproc.TM_SQDIFF,
         Imgproc.TM_SQDIFF_NORMED,
         Imgproc.TM_CCORR,
         Imgproc.TM_CCORR_NORMED,
         Imgproc.TM_CCOEFF,
         Imgproc.TM_CCOEFF_NORMED,
      };
      for( final int method : methods ) {
         final int result_cols = img.cols() - templ.cols() + 1;
         final int result_rows = img.rows() - templ.rows() + 1;
         result.create( result_cols, result_rows, CvType.CV_32FC1 );
         Imgproc.matchTemplate( img, templ, result, method );
         Core.normalize( result, result, 0, 1, Core.NORM_MINMAX, -1, new Mat());
         final MinMaxLocResult mmlr = Core.minMaxLoc( result, new Mat());
         final Point matchLoc;
         if( method  == Imgproc.TM_SQDIFF || method == Imgproc.TM_SQDIFF_NORMED ) {
            matchLoc = mmlr.minLoc;
         }
         else {
            matchLoc = mmlr.maxLoc;
         }
         Core.rectangle( img, matchLoc,
            new Point( matchLoc.x + templ.cols(), matchLoc.y + templ.rows()),
            Scalar.all(0), 2, 8, 0 );
         Core.rectangle( result, matchLoc,
            new Point( matchLoc.x + templ.cols(), matchLoc.y + templ.rows()),
            Scalar.all(0), 2, 8, 0 );
         displayImage( "OpenCV source", Mat2Image( img ));
         displayImage( "OpenCV result", Mat2Image( result ));
      }
   }
edit retag flag offensive close merge delete