idx int64 0 41.2k | question stringlengths 74 4.04k | target stringlengths 7 750 |
|---|---|---|
27,400 | protected void setAllowedBounds ( KltFeature feature ) { widthFeature = feature . radius * 2 + 1 ; lengthFeature = widthFeature * widthFeature ; allowedLeft = feature . radius ; allowedTop = feature . radius ; allowedRight = image . width - feature . radius - 1 ; allowedBottom = image . height - feature . radius - 1 ; outsideLeft = - feature . radius ; outsideTop = - feature . radius ; outsideRight = image . width + feature . radius - 1 ; outsideBottom = image . height + feature . radius - 1 ; } | Precompute image bounds that the feature is allowed inside of |
27,401 | protected int computeGandE_border ( KltFeature feature , float cx , float cy ) { computeSubImageBounds ( feature , cx , cy ) ; ImageMiscOps . fill ( currDesc , Float . NaN ) ; currDesc . subimage ( dstX0 , dstY0 , dstX1 , dstY1 , subimage ) ; interpInput . setImage ( image ) ; interpInput . region ( srcX0 , srcY0 , subimage ) ; int total = 0 ; Gxx = 0 ; Gyy = 0 ; Gxy = 0 ; Ex = 0 ; Ey = 0 ; for ( int i = 0 ; i < lengthFeature ; i ++ ) { float template = feature . desc . data [ i ] ; float current = currDesc . data [ i ] ; if ( Float . isNaN ( template ) || Float . isNaN ( current ) ) continue ; total ++ ; float dX = feature . derivX . data [ i ] ; float dY = feature . derivY . data [ i ] ; float d = template - current ; Ex += d * dX ; Ey += d * dY ; Gxx += dX * dX ; Gyy += dY * dY ; Gxy += dX * dY ; } return total ; } | When part of the region is outside the image G and E need to be recomputed |
27,402 | public boolean isDescriptionComplete ( KltFeature feature ) { for ( int i = 0 ; i < lengthFeature ; i ++ ) { if ( Float . isNaN ( feature . desc . data [ i ] ) ) return false ; } return true ; } | Checks to see if the feature description is complete or if it was created by a feature partially outside the image |
27,403 | public boolean isFullyInside ( float x , float y ) { if ( x < allowedLeft || x > allowedRight ) return false ; if ( y < allowedTop || y > allowedBottom ) return false ; return true ; } | Returns true if the features is entirely enclosed inside of the image . |
27,404 | public boolean isFullyOutside ( float x , float y ) { if ( x < outsideLeft || x > outsideRight ) return true ; if ( y < outsideTop || y > outsideBottom ) return true ; return false ; } | Returns true if the features is entirely outside of the image . A region is entirely outside if not an entire pixel is contained inside the image . So if only 0 . 999 of a pixel is inside then the whole region is considered to be outside . Can t interpolate nothing ... |
27,405 | private boolean checkMax ( T image , double adj , double bestScore , int c_x , int c_y ) { sparseLaplace . setImage ( image ) ; boolean isMax = true ; beginLoop : for ( int i = c_y - 1 ; i <= c_y + 1 ; i ++ ) { for ( int j = c_x - 1 ; j <= c_x + 1 ; j ++ ) { double value = adj * sparseLaplace . compute ( j , i ) ; if ( value >= bestScore ) { isMax = false ; break beginLoop ; } } } return isMax ; } | See if the best score is better than the local adjusted scores at this scale |
27,406 | public void findPatterns ( GrayF32 input ) { found . reset ( ) ; detector . process ( input ) ; clusterFinder . process ( detector . getCorners ( ) . toList ( ) ) ; FastQueue < ChessboardCornerGraph > clusters = clusterFinder . getOutputClusters ( ) ; for ( int clusterIdx = 0 ; clusterIdx < clusters . size ; clusterIdx ++ ) { ChessboardCornerGraph c = clusters . get ( clusterIdx ) ; if ( ! clusterToGrid . convert ( c , found . grow ( ) ) ) { found . removeTail ( ) ; } } } | Processes the image and searches for all chessboard patterns . |
27,407 | public void configure ( int width , int height , int gridRows , int gridCols ) { int s = Math . max ( width , height ) ; scaleX = s / ( float ) ( gridCols - 1 ) ; scaleY = s / ( float ) ( gridRows - 1 ) ; if ( gridRows > gridCols ) { scaleY /= ( gridCols - 1 ) / ( float ) ( gridRows - 1 ) ; } else { scaleX /= ( gridRows - 1 ) / ( float ) ( gridCols - 1 ) ; } this . gridRows = gridRows ; this . gridCols = gridCols ; grid . resize ( gridCols * gridRows ) ; reset ( ) ; } | Specifies the input image size and the size of the grid it will use to approximate the idea solution . All control points are discarded |
27,408 | public int addControl ( float x , float y ) { Control c = controls . grow ( ) ; c . q . set ( x , y ) ; setUndistorted ( controls . size ( ) - 1 , x , y ) ; return controls . size ( ) - 1 ; } | Adds a new control point at the specified location . Initially the distorted and undistorted location will be set to the same |
27,409 | public void setUndistorted ( int which , float x , float y ) { if ( scaleX <= 0 || scaleY <= 0 ) throw new IllegalArgumentException ( "Must call configure first" ) ; controls . get ( which ) . p . set ( x / scaleX , y / scaleY ) ; } | Sets the location of a control point . |
27,410 | public int add ( float srcX , float srcY , float dstX , float dstY ) { int which = addControl ( srcX , srcY ) ; setUndistorted ( which , dstX , dstY ) ; return which ; } | Function that let s you set control and undistorted points at the same time |
27,411 | public void setDistorted ( int which , float x , float y ) { controls . get ( which ) . q . set ( x , y ) ; } | Sets the distorted location of a specific control point |
27,412 | public void fixateUndistorted ( ) { if ( controls . size ( ) < 2 ) throw new RuntimeException ( "Not enough control points specified. Found " + controls . size ( ) ) ; for ( int row = 0 ; row < gridRows ; row ++ ) { for ( int col = 0 ; col < gridCols ; col ++ ) { Cache cache = getGrid ( row , col ) ; cache . weights . resize ( controls . size ) ; cache . A . resize ( controls . size ) ; cache . A_s . resize ( controls . size ( ) ) ; float v_x = col ; float v_y = row ; computeWeights ( cache , v_x , v_y ) ; computeAverageP ( cache ) ; model . computeCache ( cache , v_x , v_y ) ; } } } | Precompute the portion of the equation which only concerns the undistorted location of each point on the grid even the current undistorted location of each control point . |
27,413 | void computeAverageP ( Cache cache ) { float [ ] weights = cache . weights . data ; cache . aveP . set ( 0 , 0 ) ; for ( int i = 0 ; i < controls . size ( ) ; i ++ ) { Control c = controls . get ( i ) ; float w = weights [ i ] ; cache . aveP . x += c . p . x * w ; cache . aveP . y += c . p . y * w ; } cache . aveP . x /= cache . totalWeight ; cache . aveP . y /= cache . totalWeight ; } | Computes the average P given the weights at this cached point |
27,414 | void computeAverageQ ( Cache cache ) { float [ ] weights = cache . weights . data ; cache . aveQ . set ( 0 , 0 ) ; for ( int i = 0 ; i < controls . size ( ) ; i ++ ) { Control c = controls . get ( i ) ; float w = weights [ i ] ; cache . aveQ . x += c . q . x * w ; cache . aveQ . y += c . q . y * w ; } cache . aveQ . x /= cache . totalWeight ; cache . aveQ . y /= cache . totalWeight ; } | Computes the average Q given the weights at this cached point |
27,415 | void interpolateDeformedPoint ( float v_x , float v_y , Point2D_F32 deformed ) { int x0 = ( int ) v_x ; int y0 = ( int ) v_y ; int x1 = x0 + 1 ; int y1 = y0 + 1 ; if ( x1 >= gridCols ) x1 = gridCols - 1 ; if ( y1 >= gridRows ) y1 = gridRows - 1 ; float ax = v_x - x0 ; float ay = v_y - y0 ; float w00 = ( 1.0f - ax ) * ( 1.0f - ay ) ; float w01 = ax * ( 1.0f - ay ) ; float w11 = ax * ay ; float w10 = ( 1.0f - ax ) * ay ; Point2D_F32 d00 = getGrid ( y0 , x0 ) . deformed ; Point2D_F32 d01 = getGrid ( y0 , x1 ) . deformed ; Point2D_F32 d10 = getGrid ( y1 , x0 ) . deformed ; Point2D_F32 d11 = getGrid ( y1 , x1 ) . deformed ; deformed . set ( 0 , 0 ) ; deformed . x += w00 * d00 . x ; deformed . x += w01 * d01 . x ; deformed . x += w11 * d11 . x ; deformed . x += w10 * d10 . x ; deformed . y += w00 * d00 . y ; deformed . y += w01 * d01 . y ; deformed . y += w11 * d11 . y ; deformed . y += w10 * d10 . y ; } | Samples the 4 grid points around v and performs bilinear interpolation |
27,416 | public void process ( DMatrixRMaj cameraCalibration , List < DMatrixRMaj > homographies , List < CalibrationObservation > observations ) { init ( observations ) ; setupA_and_B ( cameraCalibration , homographies , observations ) ; if ( ! solver . setA ( A ) ) throw new RuntimeException ( "Solver had problems" ) ; solver . solve ( B , X ) ; } | Computes radial distortion using a linear method . |
27,417 | private void init ( List < CalibrationObservation > observations ) { int totalPoints = 0 ; for ( int i = 0 ; i < observations . size ( ) ; i ++ ) { totalPoints += observations . get ( i ) . size ( ) ; } A . reshape ( 2 * totalPoints , X . numRows , false ) ; B . reshape ( A . numRows , 1 , false ) ; } | Declares and sets up data structures |
27,418 | public boolean process ( double x , double y ) { leftPixelToRect . compute ( x , y , pixelRect ) ; if ( ! disparity . process ( ( int ) ( pixelRect . x + 0.5 ) , ( int ) ( pixelRect . y + 0.5 ) ) ) return false ; this . w = disparity . getDisparity ( ) ; computeHomo3D ( pixelRect . x , pixelRect . y , pointLeft ) ; return true ; } | Takes in pixel coordinates from the left camera in the original image coordinate system |
27,419 | public void detachEdge ( SquareEdge edge ) { edge . a . edges [ edge . sideA ] = null ; edge . b . edges [ edge . sideB ] = null ; edge . distance = 0 ; edgeManager . recycleInstance ( edge ) ; } | Removes the edge from the two nodes and recycles the data structure |
27,420 | public int findSideIntersect ( SquareNode n , LineSegment2D_F64 line , Point2D_F64 intersection , LineSegment2D_F64 storage ) { for ( int j = 0 , i = 3 ; j < 4 ; i = j , j ++ ) { storage . a = n . square . get ( i ) ; storage . b = n . square . get ( j ) ; if ( Intersection2D_F64 . intersection ( line , storage , intersection ) != null ) { return i ; } } return - 1 ; } | Finds the side which intersects the line on the shape . The line is assumed to pass through the shape so if there is no intersection it is considered a bug |
27,421 | public void checkConnect ( SquareNode a , int indexA , SquareNode b , int indexB , double distance ) { if ( a . edges [ indexA ] != null && a . edges [ indexA ] . distance > distance ) { detachEdge ( a . edges [ indexA ] ) ; } if ( b . edges [ indexB ] != null && b . edges [ indexB ] . distance > distance ) { detachEdge ( b . edges [ indexB ] ) ; } if ( a . edges [ indexA ] == null && b . edges [ indexB ] == null ) { connect ( a , indexA , b , indexB , distance ) ; } } | Checks to see if the two nodes can be connected . If one of the nodes is already connected to another it then checks to see if the proposed connection is more desirable . If it is the old connection is removed and a new one created . Otherwise nothing happens . |
27,422 | void connect ( SquareNode a , int indexA , SquareNode b , int indexB , double distance ) { SquareEdge edge = edgeManager . requestInstance ( ) ; edge . reset ( ) ; edge . a = a ; edge . sideA = indexA ; edge . b = b ; edge . sideB = indexB ; edge . distance = distance ; a . edges [ indexA ] = edge ; b . edges [ indexB ] = edge ; } | Creates a new edge which will connect the two nodes . The side on each node which is connected is specified by the indexes . |
27,423 | public boolean almostParallel ( SquareNode a , int sideA , SquareNode b , int sideB ) { double selected = acuteAngle ( a , sideA , b , sideB ) ; if ( selected > parallelThreshold ) return false ; return true ; } | Checks to see if the two sides are almost parallel to each other by looking at their acute angle . |
27,424 | public void setImageGradient ( Deriv derivX , Deriv derivY ) { this . derivX . wrap ( derivX ) ; this . derivY . wrap ( derivY ) ; } | Specify the input image |
27,425 | void computeHistogram ( int c_x , int c_y , double sigma ) { int r = ( int ) Math . ceil ( sigma * sigmaEnlarge ) ; bound . x0 = c_x - r ; bound . y0 = c_y - r ; bound . x1 = c_x + r + 1 ; bound . y1 = c_y + r + 1 ; ImageGray rawDX = derivX . getImage ( ) ; ImageGray rawDY = derivY . getImage ( ) ; BoofMiscOps . boundRectangleInside ( rawDX , bound ) ; Arrays . fill ( histogramMag , 0 ) ; Arrays . fill ( histogramX , 0 ) ; Arrays . fill ( histogramY , 0 ) ; for ( int y = bound . y0 ; y < bound . y1 ; y ++ ) { int indexDX = rawDX . startIndex + y * rawDX . stride + bound . x0 ; int indexDY = rawDY . startIndex + y * rawDY . stride + bound . x0 ; for ( int x = bound . x0 ; x < bound . x1 ; x ++ ) { float dx = derivX . getF ( indexDX ++ ) ; float dy = derivY . getF ( indexDY ++ ) ; double magnitude = Math . sqrt ( dx * dx + dy * dy ) ; double theta = UtilAngle . domain2PI ( Math . atan2 ( dy , dx ) ) ; double weight = computeWeight ( x - c_x , y - c_y , sigma ) ; int h = ( int ) ( theta / histAngleBin ) % histogramMag . length ; histogramMag [ h ] += magnitude * weight ; histogramX [ h ] += dx * weight ; histogramY [ h ] += dy * weight ; } } } | Constructs the histogram around the specified point . |
27,426 | void findHistogramPeaks ( ) { peaks . reset ( ) ; angles . reset ( ) ; peakAngle = 0 ; double largest = 0 ; int largestIndex = - 1 ; double before = histogramMag [ histogramMag . length - 2 ] ; double current = histogramMag [ histogramMag . length - 1 ] ; for ( int i = 0 ; i < histogramMag . length ; i ++ ) { double after = histogramMag [ i ] ; if ( current > before && current > after ) { int currentIndex = CircularIndex . addOffset ( i , - 1 , histogramMag . length ) ; peaks . push ( currentIndex ) ; if ( current > largest ) { largest = current ; largestIndex = currentIndex ; } } before = current ; current = after ; } if ( largestIndex < 0 ) return ; double threshold = largest * 0.8 ; for ( int i = 0 ; i < peaks . size ; i ++ ) { int index = peaks . data [ i ] ; current = histogramMag [ index ] ; if ( current >= threshold ) { double angle = computeAngle ( index ) ; angles . push ( angle ) ; if ( index == largestIndex ) peakAngle = angle ; } } } | Finds local peaks in histogram and selects orientations . Location of peaks is interpolated . |
27,427 | double computeAngle ( int index1 ) { int index0 = CircularIndex . addOffset ( index1 , - 1 , histogramMag . length ) ; int index2 = CircularIndex . addOffset ( index1 , 1 , histogramMag . length ) ; double v0 = histogramMag [ index0 ] ; double v1 = histogramMag [ index1 ] ; double v2 = histogramMag [ index2 ] ; double offset = FastHessianFeatureDetector . polyPeak ( v0 , v1 , v2 ) ; return interpolateAngle ( index0 , index1 , index2 , offset ) ; } | Compute the angle . The angle for each neighbor bin is found using the weighted sum of the derivative . Then the peak index is found by 2nd order polygon interpolation . These two bits of information are combined and used to return the final angle output . |
27,428 | double interpolateAngle ( int index0 , int index1 , int index2 , double offset ) { double angle1 = Math . atan2 ( histogramY [ index1 ] , histogramX [ index1 ] ) ; double deltaAngle ; if ( offset < 0 ) { double angle0 = Math . atan2 ( histogramY [ index0 ] , histogramX [ index0 ] ) ; deltaAngle = UtilAngle . dist ( angle0 , angle1 ) ; } else { double angle2 = Math . atan2 ( histogramY [ index2 ] , histogramX [ index2 ] ) ; deltaAngle = UtilAngle . dist ( angle2 , angle1 ) ; } return UtilAngle . bound ( angle1 + deltaAngle * offset ) ; } | Given the interpolated index compute the angle from the 3 indexes . The angle for each index is computed from the weighted gradients . |
27,429 | double computeWeight ( double deltaX , double deltaY , double sigma ) { double d = ( ( deltaX * deltaX + deltaY * deltaY ) / ( sigma * sigma ) ) / approximateStep ; if ( approximateGauss . interpolate ( d ) ) { return approximateGauss . value ; } else return 0 ; } | Computes the weight based on a centered Gaussian shaped function . Interpolation is used to speed up the process |
27,430 | protected void onCameraResolutionChange ( int width , int height , int sensorOrientation ) { super . onCameraResolutionChange ( width , height , sensorOrientation ) ; derivX . reshape ( width , height ) ; derivY . reshape ( width , height ) ; } | During camera initialization this function is called once after the resolution is known . This is a good function to override and predeclare data structres which are dependent on the video feeds resolution . |
27,431 | protected void renderBitmapImage ( BitmapMode mode , ImageBase image ) { switch ( mode ) { case UNSAFE : { VisualizeImageData . colorizeGradient ( derivX , derivY , - 1 , bitmap , bitmapTmp ) ; } break ; case DOUBLE_BUFFER : { VisualizeImageData . colorizeGradient ( derivX , derivY , - 1 , bitmapWork , bitmapTmp ) ; if ( bitmapLock . tryLock ( ) ) { try { Bitmap tmp = bitmapWork ; bitmapWork = bitmap ; bitmap = tmp ; } finally { bitmapLock . unlock ( ) ; } } } break ; } } | Override the default behavior and colorize gradient instead of converting input image . |
27,432 | public void process ( T image , GrayF32 intensity ) { int maxFeatures = ( int ) ( maxFeaturesFraction * image . width * image . height ) ; candidatesLow . reset ( ) ; candidatesHigh . reset ( ) ; this . image = image ; if ( stride != image . stride ) { stride = image . stride ; offsets = DiscretizedCircle . imageOffsets ( radius , image . stride ) ; } helper . setImage ( image , offsets ) ; for ( int y = radius ; y < image . height - radius ; y ++ ) { int indexIntensity = intensity . startIndex + y * intensity . stride + radius ; int index = image . startIndex + y * image . stride + radius ; for ( int x = radius ; x < image . width - radius ; x ++ , index ++ , indexIntensity ++ ) { int result = helper . checkPixel ( index ) ; if ( result < 0 ) { intensity . data [ indexIntensity ] = helper . scoreLower ( index ) ; candidatesLow . add ( x , y ) ; } else if ( result > 0 ) { intensity . data [ indexIntensity ] = helper . scoreUpper ( index ) ; candidatesHigh . add ( x , y ) ; } else { intensity . data [ indexIntensity ] = 0 ; } } if ( candidatesLow . size + candidatesHigh . size >= maxFeatures ) break ; } } | Computes fast corner features and their intensity . The intensity is needed if non - max suppression is used |
27,433 | public static double selectZoomToShowAll ( JComponent panel , int width , int height ) { int w = panel . getWidth ( ) ; int h = panel . getHeight ( ) ; if ( w == 0 ) { w = panel . getPreferredSize ( ) . width ; h = panel . getPreferredSize ( ) . height ; } double scale = Math . max ( width / ( double ) w , height / ( double ) h ) ; if ( scale > 1.0 ) { return 1.0 / scale ; } else { return 1.0 ; } } | Select a zoom which will allow the entire image to be shown in the panel |
27,434 | public static double selectZoomToFitInDisplay ( int width , int height ) { Dimension screenSize = Toolkit . getDefaultToolkit ( ) . getScreenSize ( ) ; double w = screenSize . getWidth ( ) ; double h = screenSize . getHeight ( ) ; double scale = Math . max ( width / w , height / h ) ; if ( scale > 1.0 ) { return 1.0 / scale ; } else { return 1.0 ; } } | Figures out what the scale should be to fit the window inside the default display |
27,435 | public static void antialiasing ( Graphics2D g2 ) { g2 . setRenderingHint ( RenderingHints . KEY_STROKE_CONTROL , RenderingHints . VALUE_STROKE_PURE ) ; g2 . setRenderingHint ( RenderingHints . KEY_ANTIALIASING , RenderingHints . VALUE_ANTIALIAS_ON ) ; } | Sets rendering hints that will enable antialiasing and make sub pixel rendering look good |
27,436 | public static boolean isImage ( File file ) { try { String mimeType = Files . probeContentType ( file . toPath ( ) ) ; if ( mimeType == null ) { String extension = FilenameUtils . getExtension ( file . getName ( ) ) . toLowerCase ( ) ; String [ ] suffixes = ImageIO . getReaderFileSuffixes ( ) ; for ( String s : suffixes ) { if ( s . equals ( extension ) ) { return true ; } } } else { return mimeType . startsWith ( "image" ) ; } } catch ( IOException ignore ) { } return false ; } | Uses mime type to determine if it s an image or not . If mime fails it will look at the suffix . This isn t 100% correct . |
27,437 | public static void print ( IntegralKernel kernel ) { int x0 = 0 , x1 = 0 , y0 = 0 , y1 = 0 ; for ( ImageRectangle k : kernel . blocks ) { if ( k . x0 < x0 ) x0 = k . x0 ; if ( k . y0 < y0 ) y0 = k . y0 ; if ( k . x1 > x1 ) x1 = k . x1 ; if ( k . y1 > y1 ) y1 = k . y1 ; } int w = x1 - x0 ; int h = y1 - y0 ; int sum [ ] = new int [ w * h ] ; for ( int i = 0 ; i < kernel . blocks . length ; i ++ ) { ImageRectangle r = kernel . blocks [ i ] ; int value = kernel . scales [ i ] ; for ( int y = r . y0 ; y < r . y1 ; y ++ ) { int yy = y - y0 ; for ( int x = r . x0 ; x < r . x1 ; x ++ ) { int xx = x - x0 ; sum [ yy * w + xx ] += value ; } } } System . out . println ( "IntegralKernel: TL = (" + ( x0 + 1 ) + "," + ( y0 + 1 ) + ") BR=(" + x1 + "," + y1 + ")" ) ; for ( int y = 0 ; y < h ; y ++ ) { for ( int x = 0 ; x < w ; x ++ ) { System . out . printf ( "%4d " , sum [ y * w + x ] ) ; } System . out . println ( ) ; } } | Prints out the kernel . |
27,438 | public static boolean isInBounds ( int x , int y , IntegralKernel kernel , int width , int height ) { for ( ImageRectangle r : kernel . blocks ) { if ( x + r . x0 < 0 || y + r . y0 < 0 ) return false ; if ( x + r . x1 >= width || y + r . y1 >= height ) return false ; } return true ; } | Checks to see if the kernel is applied at this specific spot if all the pixels would be inside the image bounds or not |
27,439 | public void setScaleFactors ( int ... scaleFactors ) { for ( int i = 1 ; i < scaleFactors . length ; i ++ ) { if ( scaleFactors [ i ] % scaleFactors [ i - 1 ] != 0 ) { throw new IllegalArgumentException ( "Layer " + i + " is not evenly divisible by its lower layer." ) ; } } bottomWidth = bottomHeight = 0 ; this . scale = scaleFactors . clone ( ) ; checkScales ( ) ; } | Specifies the pyramid s structure . Scale factors are in relative to the input image . |
27,440 | public boolean process ( List < Point2D_I32 > list , GrowQueue_I32 vertexes ) { this . contour = list ; this . minimumSideLengthPixel = minimumSideLength . computeI ( contour . size ( ) ) ; splits . reset ( ) ; boolean result = _process ( list ) ; this . contour = null ; vertexes . setTo ( splits ) ; return result ; } | Approximates the input list with a set of line segments |
27,441 | protected double splitThresholdSq ( Point2D_I32 a , Point2D_I32 b ) { return Math . max ( 2 , a . distance2 ( b ) * toleranceFractionSq ) ; } | Computes the split threshold from the end point of two lines |
27,442 | @ SuppressWarnings ( { "SuspiciousSystemArraycopy" } ) public void setTo ( T orig ) { if ( orig . width != width || orig . height != height || orig . numBands != numBands ) reshape ( orig . width , orig . height , orig . numBands ) ; if ( ! orig . isSubimage ( ) && ! isSubimage ( ) ) { System . arraycopy ( orig . _getData ( ) , orig . startIndex , _getData ( ) , startIndex , stride * height ) ; } else { int indexSrc = orig . startIndex ; int indexDst = startIndex ; for ( int y = 0 ; y < height ; y ++ ) { System . arraycopy ( orig . _getData ( ) , indexSrc , _getData ( ) , indexDst , width * numBands ) ; indexSrc += orig . stride ; indexDst += stride ; } } } | Sets this image equal to the specified image . Automatically resized to match the input image . |
27,443 | public static void determinant ( GrayF32 featureIntensity , GrayF32 hessianXX , GrayF32 hessianYY , GrayF32 hessianXY ) { InputSanityCheck . checkSameShape ( featureIntensity , hessianXX , hessianYY , hessianXY ) ; ImplHessianBlobIntensity . determinant ( featureIntensity , hessianXX , hessianYY , hessianXY ) ; } | Feature intensity using the Hessian matrix s determinant . |
27,444 | public static void trace ( GrayF32 featureIntensity , GrayF32 hessianXX , GrayF32 hessianYY ) { InputSanityCheck . checkSameShape ( featureIntensity , hessianXX , hessianYY ) ; ImplHessianBlobIntensity . trace ( featureIntensity , hessianXX , hessianYY ) ; } | Feature intensity using the trace of the Hessian matrix . This is also known as the Laplacian . |
27,445 | public void reshape ( int width , int height ) { if ( padded == null ) { binary . reshape ( width , height ) ; } else { binary . reshape ( width + 2 , height + 2 ) ; binary . subimage ( 1 , 1 , width + 1 , height + 1 , subimage ) ; } } | Reshapes data so that the un - padded image has the specified shape . |
27,446 | public boolean computeEdge ( Polygon2D_F64 polygon , boolean ccw ) { averageInside = 0 ; averageOutside = 0 ; double tangentSign = ccw ? 1 : - 1 ; int totalSides = 0 ; for ( int i = polygon . size ( ) - 1 , j = 0 ; j < polygon . size ( ) ; i = j , j ++ ) { Point2D_F64 a = polygon . get ( i ) ; Point2D_F64 b = polygon . get ( j ) ; double dx = b . x - a . x ; double dy = b . y - a . y ; double t = Math . sqrt ( dx * dx + dy * dy ) ; dx /= t ; dy /= t ; if ( t < 3 * cornerOffset ) { offsetA . set ( a ) ; offsetB . set ( b ) ; } else { offsetA . x = a . x + cornerOffset * dx ; offsetA . y = a . y + cornerOffset * dy ; offsetB . x = b . x - cornerOffset * dx ; offsetB . y = b . y - cornerOffset * dy ; } double tanX = - dy * tangentDistance * tangentSign ; double tanY = dx * tangentDistance * tangentSign ; scorer . computeAverageDerivative ( offsetA , offsetB , tanX , tanY ) ; if ( scorer . getSamplesInside ( ) > 0 ) { totalSides ++ ; averageInside += scorer . getAverageUp ( ) / tangentDistance ; averageOutside += scorer . getAverageDown ( ) / tangentDistance ; } } if ( totalSides > 0 ) { averageInside /= totalSides ; averageOutside /= totalSides ; } else { averageInside = averageOutside = 0 ; return false ; } return true ; } | Checks to see if its a valid polygon or a false positive by looking at edge intensity |
27,447 | public boolean checkIntensity ( boolean insideDark , double threshold ) { if ( insideDark ) return averageOutside - averageInside >= threshold ; else return averageInside - averageOutside >= threshold ; } | Checks the edge intensity against a threshold . |
27,448 | public void setCamera ( double skew , double cx , double cy , int width , int height ) { double d = Math . sqrt ( width * width + height * height ) ; V . zero ( ) ; V . set ( 0 , 0 , d / 2 ) ; V . set ( 0 , 1 , skew ) ; V . set ( 0 , 2 , cx ) ; V . set ( 1 , 1 , d / 2 ) ; V . set ( 1 , 2 , cy ) ; V . set ( 2 , 2 , 1 ) ; CommonOps_DDRM . invert ( V , Vinv ) ; } | Specifies known portions of camera intrinsic parameters |
27,449 | public void setSampling ( double min , double max , int total ) { this . sampleMin = min ; this . sampleMax = max ; this . numSamples = total ; this . scores = new double [ numSamples ] ; } | Specifies how focal lengths are sampled on a log scale . Remember 1 . 0 = nominal length |
27,450 | boolean computeRectifyH ( double f1 , double f2 , DMatrixRMaj P2 , DMatrixRMaj H ) { estimatePlaneInf . setCamera1 ( f1 , f1 , 0 , 0 , 0 ) ; estimatePlaneInf . setCamera2 ( f2 , f2 , 0 , 0 , 0 ) ; if ( ! estimatePlaneInf . estimatePlaneAtInfinity ( P2 , planeInf ) ) return false ; K1 . zero ( ) ; K1 . set ( 0 , 0 , f1 ) ; K1 . set ( 1 , 1 , f1 ) ; K1 . set ( 2 , 2 , 1 ) ; MultiViewOps . createProjectiveToMetric ( K1 , planeInf . x , planeInf . y , planeInf . z , 1 , H ) ; return true ; } | Given the focal lengths for the first two views compute homography H |
27,451 | protected static List < NodeInfo > findLine ( NodeInfo seed , NodeInfo next , int clusterSize , List < NodeInfo > line , boolean ccw ) { if ( next == null ) return null ; if ( line == null ) line = new ArrayList < > ( ) ; else line . clear ( ) ; next . marked = true ; double anglePrev = direction ( next , seed ) ; double prevDist = next . ellipse . center . distance ( seed . ellipse . center ) ; line . add ( seed ) ; line . add ( next ) ; NodeInfo previous = seed ; for ( int i = 0 ; i < clusterSize + 1 ; i ++ ) { double bestScore = Double . MAX_VALUE ; double bestDistance = Double . MAX_VALUE ; double bestAngle = Double . NaN ; double closestDistance = Double . MAX_VALUE ; NodeInfo best = null ; double previousLength = next . ellipse . center . distance ( previous . ellipse . center ) ; for ( int j = 0 ; j < next . edges . size ( ) ; j ++ ) { double angle = next . edges . get ( j ) . angle ; NodeInfo c = next . edges . get ( j ) . target ; if ( c . marked ) continue ; double candidateLength = next . ellipse . center . distance ( c . ellipse . center ) ; double ratioLengths = previousLength / candidateLength ; double ratioSize = previous . ellipse . a / c . ellipse . a ; if ( ratioLengths > 1 ) { ratioLengths = 1.0 / ratioLengths ; ratioSize = 1.0 / ratioSize ; } if ( Math . abs ( ratioLengths - ratioSize ) > 0.4 ) continue ; double angleDist = ccw ? UtilAngle . distanceCCW ( anglePrev , angle ) : UtilAngle . distanceCW ( anglePrev , angle ) ; if ( angleDist <= Math . PI + MAX_LINE_ANGLE_CHANGE ) { double d = c . ellipse . center . distance ( next . ellipse . center ) ; double score = d / prevDist + angleDist ; if ( score < bestScore ) { bestDistance = d ; bestScore = score ; bestAngle = angle ; best = c ; } closestDistance = Math . min ( d , closestDistance ) ; } } if ( best == null || bestDistance > closestDistance * 2.0 ) { return line ; } else { best . marked = true ; prevDist = bestDistance ; line . add ( best ) ; anglePrev = UtilAngle . bound ( bestAngle + Math . PI ) ; previous = next ; next = best ; } } return null ; } | Finds all the nodes which form an approximate line |
27,452 | protected static NodeInfo findClosestEdge ( NodeInfo n , Point2D_F64 p ) { double bestDistance = Double . MAX_VALUE ; NodeInfo best = null ; for ( int i = 0 ; i < n . edges . size ( ) ; i ++ ) { Edge e = n . edges . get ( i ) ; if ( e . target . marked ) continue ; double d = e . target . ellipse . center . distance2 ( p ) ; if ( d < bestDistance ) { bestDistance = d ; best = e . target ; } } return best ; } | Finds the node which is an edge of n that is closest to point p |
27,453 | boolean checkDuplicates ( List < List < NodeInfo > > grid ) { for ( int i = 0 ; i < listInfo . size ; i ++ ) { listInfo . get ( i ) . marked = false ; } for ( int i = 0 ; i < grid . size ( ) ; i ++ ) { List < NodeInfo > list = grid . get ( i ) ; for ( int j = 0 ; j < list . size ( ) ; j ++ ) { NodeInfo n = list . get ( j ) ; if ( n . marked ) return true ; n . marked = true ; } } return false ; } | Checks to see if any node is used more than once |
27,454 | void addEdgesToInfo ( List < Node > cluster ) { for ( int i = 0 ; i < cluster . size ( ) ; i ++ ) { Node n = cluster . get ( i ) ; NodeInfo infoA = listInfo . get ( i ) ; EllipseRotated_F64 a = infoA . ellipse ; for ( int j = 0 ; j < n . connections . size ( ) ; j ++ ) { NodeInfo infoB = listInfo . get ( indexOf ( cluster , n . connections . get ( j ) ) ) ; EllipseRotated_F64 b = infoB . ellipse ; Edge edge = infoA . edges . grow ( ) ; edge . target = infoB ; edge . angle = Math . atan2 ( b . center . y - a . center . y , b . center . x - a . center . x ) ; } sorter . sort ( infoA . edges . data , infoA . edges . size ) ; } } | Adds edges to node info and computes their orientation |
27,455 | void pruneNearlyIdenticalAngles ( ) { for ( int i = 0 ; i < listInfo . size ( ) ; i ++ ) { NodeInfo infoN = listInfo . get ( i ) ; for ( int j = 0 ; j < infoN . edges . size ( ) ; ) { int k = ( j + 1 ) % infoN . edges . size ; double angularDiff = UtilAngle . dist ( infoN . edges . get ( j ) . angle , infoN . edges . get ( k ) . angle ) ; if ( angularDiff < UtilAngle . radian ( 5 ) ) { NodeInfo infoJ = infoN . edges . get ( j ) . target ; NodeInfo infoK = infoN . edges . get ( k ) . target ; double distJ = infoN . ellipse . center . distance ( infoJ . ellipse . center ) ; double distK = infoN . ellipse . center . distance ( infoK . ellipse . center ) ; if ( distJ < distK ) { infoN . edges . remove ( k ) ; } else { infoN . edges . remove ( j ) ; } } else { j ++ ; } } } } | If there is a nearly perfect line a node farther down the line can come before . This just selects the closest |
27,456 | void findLargestAnglesForAllNodes ( ) { for ( int i = 0 ; i < listInfo . size ( ) ; i ++ ) { NodeInfo info = listInfo . get ( i ) ; if ( info . edges . size < 2 ) continue ; for ( int k = 0 , j = info . edges . size - 1 ; k < info . edges . size ; j = k , k ++ ) { double angleA = info . edges . get ( j ) . angle ; double angleB = info . edges . get ( k ) . angle ; double distance = UtilAngle . distanceCCW ( angleA , angleB ) ; if ( distance > info . angleBetween ) { info . angleBetween = distance ; info . left = info . edges . get ( j ) . target ; info . right = info . edges . get ( k ) . target ; } } } } | Finds the two edges with the greatest angular distance between them . |
27,457 | boolean findContour ( boolean mustHaveInner ) { NodeInfo seed = listInfo . get ( 0 ) ; for ( int i = 1 ; i < listInfo . size ( ) ; i ++ ) { NodeInfo info = listInfo . get ( i ) ; if ( info . angleBetween > seed . angleBetween ) { seed = info ; } } contour . reset ( ) ; contour . add ( seed ) ; seed . contour = true ; NodeInfo prev = seed ; NodeInfo current = seed . right ; while ( current != null && current != seed && contour . size ( ) < listInfo . size ( ) ) { if ( prev != current . left ) return false ; contour . add ( current ) ; current . contour = true ; prev = current ; current = current . right ; } return ! ( contour . size < 4 || ( mustHaveInner && contour . size >= listInfo . size ( ) ) ) ; } | Finds nodes in the outside of the grid . First the node in the grid with the largest angleBetween is selected as a seed . It is assumed at this node must be on the contour . Then the graph is traversed in CCW direction until a loop is formed . |
27,458 | public static int indexOf ( List < Node > list , int value ) { for ( int i = 0 ; i < list . size ( ) ; i ++ ) { if ( list . get ( i ) . which == value ) return i ; } return - 1 ; } | Finds the node with the index of value |
27,459 | NodeInfo selectSeedCorner ( ) { NodeInfo best = null ; double bestAngle = 0 ; for ( int i = 0 ; i < contour . size ; i ++ ) { NodeInfo info = contour . get ( i ) ; if ( info . angleBetween > bestAngle ) { bestAngle = info . angleBetween ; best = info ; } } best . marked = true ; return best ; } | Pick the node in the contour with the largest angle . Distortion tends to make the acute angle smaller . Without distortion it will be 270 degrees . |
27,460 | public static void depthTo3D ( CameraPinholeBrown param , GrayU16 depth , FastQueue < Point3D_F64 > cloud ) { cloud . reset ( ) ; Point2Transform2_F64 p2n = LensDistortionFactory . narrow ( param ) . undistort_F64 ( true , false ) ; Point2D_F64 n = new Point2D_F64 ( ) ; for ( int y = 0 ; y < depth . height ; y ++ ) { int index = depth . startIndex + y * depth . stride ; for ( int x = 0 ; x < depth . width ; x ++ ) { int mm = depth . data [ index ++ ] & 0xFFFF ; if ( mm == 0 ) continue ; p2n . compute ( x , y , n ) ; Point3D_F64 p = cloud . grow ( ) ; p . z = mm ; p . x = n . x * p . z ; p . y = n . y * p . z ; } } } | Creates a point cloud from a depth image . |
27,461 | public static void depthTo3D ( CameraPinholeBrown param , Planar < GrayU8 > rgb , GrayU16 depth , FastQueue < Point3D_F64 > cloud , FastQueueArray_I32 cloudColor ) { cloud . reset ( ) ; cloudColor . reset ( ) ; RemoveBrownPtoN_F64 p2n = new RemoveBrownPtoN_F64 ( ) ; p2n . setK ( param . fx , param . fy , param . skew , param . cx , param . cy ) . setDistortion ( param . radial , param . t1 , param . t2 ) ; Point2D_F64 n = new Point2D_F64 ( ) ; GrayU8 colorR = rgb . getBand ( 0 ) ; GrayU8 colorG = rgb . getBand ( 1 ) ; GrayU8 colorB = rgb . getBand ( 2 ) ; for ( int y = 0 ; y < depth . height ; y ++ ) { int index = depth . startIndex + y * depth . stride ; for ( int x = 0 ; x < depth . width ; x ++ ) { int mm = depth . data [ index ++ ] & 0xFFFF ; if ( mm == 0 ) continue ; p2n . compute ( x , y , n ) ; Point3D_F64 p = cloud . grow ( ) ; p . z = mm ; p . x = n . x * p . z ; p . y = n . y * p . z ; int color [ ] = cloudColor . grow ( ) ; color [ 0 ] = colorR . unsafe_get ( x , y ) ; color [ 1 ] = colorG . unsafe_get ( x , y ) ; color [ 2 ] = colorB . unsafe_get ( x , y ) ; } } } | Creates a point cloud from a depth image and saves the color information . The depth and color images are assumed to be aligned . |
27,462 | public boolean prune ( List < Point2D_I32 > contour , GrowQueue_I32 input , GrowQueue_I32 output ) { this . contour = contour ; output . setTo ( input ) ; removeDuplicates ( output ) ; if ( output . size ( ) <= 3 ) return false ; computeSegmentEnergy ( output ) ; double total = 0 ; for ( int i = 0 ; i < output . size ( ) ; i ++ ) { total += energySegment [ i ] ; } FitLinesToContour fit = new FitLinesToContour ( ) ; fit . setContour ( contour ) ; boolean modified = false ; while ( output . size ( ) > 3 ) { double bestEnergy = total ; boolean betterFound = false ; bestCorners . reset ( ) ; for ( int i = 0 ; i < output . size ( ) ; i ++ ) { workCorners1 . reset ( ) ; for ( int j = 0 ; j < output . size ( ) ; j ++ ) { if ( i != j ) { workCorners1 . add ( output . get ( j ) ) ; } } removeDuplicates ( workCorners1 ) ; if ( workCorners1 . size ( ) > 3 ) { int anchor0 = CircularIndex . addOffset ( i , - 2 , workCorners1 . size ( ) ) ; int anchor1 = CircularIndex . addOffset ( i , 1 , workCorners1 . size ( ) ) ; if ( fit . fitAnchored ( anchor0 , anchor1 , workCorners1 , workCorners2 ) ) { double score = 0 ; for ( int j = 0 , k = workCorners2 . size ( ) - 1 ; j < workCorners2 . size ( ) ; k = j , j ++ ) { score += computeSegmentEnergy ( workCorners2 , k , j ) ; } if ( score < bestEnergy ) { betterFound = true ; bestEnergy = score ; bestCorners . reset ( ) ; bestCorners . addAll ( workCorners2 ) ; } } } } if ( betterFound ) { modified = true ; total = bestEnergy ; output . setTo ( bestCorners ) ; } else { break ; } } return modified ; } | Given a contour and initial set of corners compute a new set of corner indexes |
27,463 | void removeDuplicates ( GrowQueue_I32 corners ) { for ( int i = 0 ; i < corners . size ( ) ; i ++ ) { Point2D_I32 a = contour . get ( corners . get ( i ) ) ; for ( int j = corners . size ( ) - 1 ; j > i ; j -- ) { Point2D_I32 b = contour . get ( corners . get ( j ) ) ; if ( a . x == b . x && a . y == b . y ) { corners . remove ( j ) ; } } } } | Look for two corners which point to the same point and removes one of them from the corner list |
27,464 | void computeSegmentEnergy ( GrowQueue_I32 corners ) { if ( energySegment . length < corners . size ( ) ) { energySegment = new double [ corners . size ( ) ] ; } for ( int i = 0 , j = corners . size ( ) - 1 ; i < corners . size ( ) ; j = i , i ++ ) { energySegment [ j ] = computeSegmentEnergy ( corners , j , i ) ; } } | Computes the energy of each segment individually |
27,465 | protected double energyRemoveCorner ( int removed , GrowQueue_I32 corners ) { double total = 0 ; int cornerA = CircularIndex . addOffset ( removed , - 1 , corners . size ( ) ) ; int cornerB = CircularIndex . addOffset ( removed , 1 , corners . size ( ) ) ; total += computeSegmentEnergy ( corners , cornerA , cornerB ) ; if ( cornerA > cornerB ) { for ( int i = cornerB ; i < cornerA ; i ++ ) total += energySegment [ i ] ; } else { for ( int i = 0 ; i < cornerA ; i ++ ) { total += energySegment [ i ] ; } for ( int i = cornerB ; i < corners . size ( ) ; i ++ ) { total += energySegment [ i ] ; } } return total ; } | Returns the total energy after removing a corner |
27,466 | protected double computeSegmentEnergy ( GrowQueue_I32 corners , int cornerA , int cornerB ) { int indexA = corners . get ( cornerA ) ; int indexB = corners . get ( cornerB ) ; if ( indexA == indexB ) { return 100000.0 ; } Point2D_I32 a = contour . get ( indexA ) ; Point2D_I32 b = contour . get ( indexB ) ; line . p . x = a . x ; line . p . y = a . y ; line . slope . set ( b . x - a . x , b . y - a . y ) ; double total = 0 ; int length = circularDistance ( indexA , indexB ) ; for ( int k = 1 ; k < length ; k ++ ) { Point2D_I32 c = getContour ( indexA + 1 + k ) ; point . set ( c . x , c . y ) ; total += Distance2D_F64 . distanceSq ( line , point ) ; } return ( total + splitPenalty ) / a . distance2 ( b ) ; } | Computes the energy for a segment defined by the two corner indexes |
27,467 | public void process ( T image , GrayS32 pixelToRegion , GrowQueue_I32 regionMemberCount , FastQueue < float [ ] > regionColor ) { stopRequested = false ; while ( ! stopRequested ) { regionColor . resize ( regionMemberCount . size ) ; computeColor . process ( image , pixelToRegion , regionMemberCount , regionColor ) ; initializeMerge ( regionMemberCount . size ) ; if ( ! setupPruneList ( regionMemberCount ) ) break ; findAdjacentRegions ( pixelToRegion ) ; for ( int i = 0 ; i < pruneGraph . size ; i ++ ) { selectMerge ( i , regionColor ) ; } performMerge ( pixelToRegion , regionMemberCount ) ; } } | Merges together smaller regions . Segmented image region member count and region color are all updated . |
27,468 | protected boolean setupPruneList ( GrowQueue_I32 regionMemberCount ) { segmentPruneFlag . resize ( regionMemberCount . size ) ; pruneGraph . reset ( ) ; segmentToPruneID . resize ( regionMemberCount . size ) ; for ( int i = 0 ; i < regionMemberCount . size ; i ++ ) { if ( regionMemberCount . get ( i ) < minimumSize ) { segmentToPruneID . set ( i , pruneGraph . size ( ) ) ; Node n = pruneGraph . grow ( ) ; n . init ( i ) ; segmentPruneFlag . set ( i , true ) ; } else { segmentPruneFlag . set ( i , false ) ; } } return pruneGraph . size ( ) != 0 ; } | Identifies which regions are to be pruned based on their member counts . Then sets up data structures for graph and converting segment ID to prune ID . |
27,469 | protected void findAdjacentRegions ( GrayS32 pixelToRegion ) { if ( connect . length == 4 ) adjacentInner4 ( pixelToRegion ) ; else if ( connect . length == 8 ) { adjacentInner8 ( pixelToRegion ) ; } adjacentBorder ( pixelToRegion ) ; } | Go through each pixel in the image and examine its neighbors according to a 4 - connect rule . If one of the pixels is in a region that is to be pruned mark them as neighbors . The image is traversed such that the number of comparisons is minimized . |
27,470 | protected void selectMerge ( int pruneId , FastQueue < float [ ] > regionColor ) { Node n = pruneGraph . get ( pruneId ) ; float [ ] targetColor = regionColor . get ( n . segment ) ; int bestId = - 1 ; float bestDistance = Float . MAX_VALUE ; for ( int i = 0 ; i < n . edges . size ; i ++ ) { int segment = n . edges . get ( i ) ; float [ ] neighborColor = regionColor . get ( segment ) ; float d = SegmentMeanShiftSearch . distanceSq ( targetColor , neighborColor ) ; if ( d < bestDistance ) { bestDistance = d ; bestId = segment ; } } if ( bestId == - 1 ) throw new RuntimeException ( "No neighbors? Something went really wrong." ) ; markMerge ( n . segment , bestId ) ; } | Examine edges for the specified node and select node which it is the best match for it to merge with |
27,471 | private void declareDerivativeImages ( ImageGradient < T , D > gradient , ImageHessian < D > hessian , Class < D > derivType ) { if ( gradient != null || hessian != null ) { derivX = GeneralizedImageOps . createSingleBand ( derivType , 1 , 1 ) ; derivY = GeneralizedImageOps . createSingleBand ( derivType , 1 , 1 ) ; } if ( hessian != null ) { derivXX = GeneralizedImageOps . createSingleBand ( derivType , 1 , 1 ) ; derivYY = GeneralizedImageOps . createSingleBand ( derivType , 1 , 1 ) ; derivXY = GeneralizedImageOps . createSingleBand ( derivType , 1 , 1 ) ; } } | Declare storage for image derivatives as needed |
27,472 | public void detect ( T input , QueueCorner exclude ) { initializeDerivatives ( input ) ; if ( detector . getRequiresGradient ( ) || detector . getRequiresHessian ( ) ) gradient . process ( input , derivX , derivY ) ; if ( detector . getRequiresHessian ( ) ) hessian . process ( derivX , derivY , derivXX , derivYY , derivXY ) ; detector . setExcludeMaximum ( exclude ) ; detector . process ( input , derivX , derivY , derivXX , derivYY , derivXY ) ; } | Detect features inside the image . Excluding points in the exclude list . |
27,473 | private void initializeDerivatives ( T input ) { if ( detector . getRequiresGradient ( ) || detector . getRequiresHessian ( ) ) { derivX . reshape ( input . width , input . height ) ; derivY . reshape ( input . width , input . height ) ; } if ( detector . getRequiresHessian ( ) ) { derivXX . reshape ( input . width , input . height ) ; derivYY . reshape ( input . width , input . height ) ; derivXY . reshape ( input . width , input . height ) ; } } | Reshape derivative images to match the input image |
27,474 | public boolean checkFlip ( SquareGrid grid ) { if ( grid . columns == 1 || grid . rows == 1 ) return false ; Point2D_F64 a = grid . get ( 0 , 0 ) . center ; Point2D_F64 b = grid . get ( 0 , grid . columns - 1 ) . center ; Point2D_F64 c = grid . get ( grid . rows - 1 , 0 ) . center ; double x0 = b . x - a . x ; double y0 = b . y - a . y ; double x1 = c . x - a . x ; double y1 = c . y - a . y ; double z = x0 * y1 - y0 * x1 ; return z < 0 ; } | Checks to see if it needs to be flipped . Flipping is required if X and Y axis in 2D grid are not CCW . |
27,475 | protected void orderNodeGrid ( SquareGrid grid , int row , int col ) { SquareNode node = grid . get ( row , col ) ; if ( grid . rows == 1 && grid . columns == 1 ) { for ( int i = 0 ; i < 4 ; i ++ ) { ordered [ i ] = node . square . get ( i ) ; } } else if ( grid . columns == 1 ) { if ( row == grid . rows - 1 ) { orderNode ( node , grid . get ( row - 1 , col ) , false ) ; rotateTwiceOrdered ( ) ; } else { orderNode ( node , grid . get ( row + 1 , col ) , false ) ; } } else { if ( col == grid . columns - 1 ) { orderNode ( node , grid . get ( row , col - 1 ) , true ) ; rotateTwiceOrdered ( ) ; } else { orderNode ( node , grid . get ( row , col + 1 ) , true ) ; } } } | Given the grid coordinate order the corners for the node at that location . Takes in handles situations where there are no neighbors . |
27,476 | private void rotateTwiceOrdered ( ) { Point2D_F64 a = ordered [ 0 ] ; Point2D_F64 b = ordered [ 1 ] ; Point2D_F64 c = ordered [ 2 ] ; Point2D_F64 d = ordered [ 3 ] ; ordered [ 0 ] = c ; ordered [ 1 ] = d ; ordered [ 2 ] = a ; ordered [ 3 ] = b ; } | Reorders the list by the equivalent of two rotations |
27,477 | protected void orderNode ( SquareNode target , SquareNode node , boolean pointingX ) { int index0 = findIntersection ( target , node ) ; int index1 = ( index0 + 1 ) % 4 ; int index2 = ( index0 + 2 ) % 4 ; int index3 = ( index0 + 3 ) % 4 ; if ( index0 < 0 ) throw new RuntimeException ( "Couldn't find intersection. Probable bug" ) ; lineCenters . a = target . center ; lineCenters . b = node . center ; UtilLine2D_F64 . convert ( lineCenters , general ) ; Polygon2D_F64 poly = target . square ; if ( pointingX ) { if ( sign ( general , poly . get ( index0 ) ) > 0 ) { ordered [ 1 ] = poly . get ( index1 ) ; ordered [ 2 ] = poly . get ( index0 ) ; } else { ordered [ 1 ] = poly . get ( index0 ) ; ordered [ 2 ] = poly . get ( index1 ) ; } if ( sign ( general , poly . get ( index2 ) ) > 0 ) { ordered [ 3 ] = poly . get ( index2 ) ; ordered [ 0 ] = poly . get ( index3 ) ; } else { ordered [ 3 ] = poly . get ( index3 ) ; ordered [ 0 ] = poly . get ( index2 ) ; } } else { if ( sign ( general , poly . get ( index0 ) ) > 0 ) { ordered [ 2 ] = poly . get ( index1 ) ; ordered [ 3 ] = poly . get ( index0 ) ; } else { ordered [ 2 ] = poly . get ( index0 ) ; ordered [ 3 ] = poly . get ( index1 ) ; } if ( sign ( general , poly . get ( index2 ) ) > 0 ) { ordered [ 0 ] = poly . get ( index2 ) ; ordered [ 1 ] = poly . get ( index3 ) ; } else { ordered [ 0 ] = poly . get ( index3 ) ; ordered [ 1 ] = poly . get ( index2 ) ; } } } | Fills the ordered list with the corners in target node in canonical order . |
27,478 | protected int findIntersection ( SquareNode target , SquareNode node ) { lineCenters . a = target . center ; lineCenters . b = node . center ; for ( int i = 0 ; i < 4 ; i ++ ) { int j = ( i + 1 ) % 4 ; lineSide . a = target . square . get ( i ) ; lineSide . b = target . square . get ( j ) ; if ( Intersection2D_F64 . intersection ( lineCenters , lineSide , dummy ) != null ) { return i ; } } return - 1 ; } | Finds the side which intersects the line segment from the center of target to center of node |
27,479 | public boolean orderSquareCorners ( SquareGrid grid ) { for ( int row = 0 ; row < grid . rows ; row ++ ) { for ( int col = 0 ; col < grid . columns ; col ++ ) { orderNodeGrid ( grid , row , col ) ; Polygon2D_F64 square = grid . get ( row , col ) . square ; for ( int i = 0 ; i < 4 ; i ++ ) { square . vertexes . data [ i ] = ordered [ i ] ; } } } return true ; } | Adjust the corners in the square s polygon so that they are aligned along the grids overall length |
27,480 | private static List < Match > findMatches ( GrayF32 image , GrayF32 template , GrayF32 mask , int expectedMatches ) { TemplateMatching < GrayF32 > matcher = FactoryTemplateMatching . createMatcher ( TemplateScoreType . SUM_DIFF_SQ , GrayF32 . class ) ; matcher . setImage ( image ) ; matcher . setTemplate ( template , mask , expectedMatches ) ; matcher . process ( ) ; return matcher . getResults ( ) . toList ( ) ; } | Demonstrates how to search for matches of a template inside an image |
27,481 | public static void showMatchIntensity ( GrayF32 image , GrayF32 template , GrayF32 mask ) { TemplateMatchingIntensity < GrayF32 > matchIntensity = FactoryTemplateMatching . createIntensity ( TemplateScoreType . SUM_DIFF_SQ , GrayF32 . class ) ; matchIntensity . setInputImage ( image ) ; matchIntensity . process ( template , mask ) ; GrayF32 intensity = matchIntensity . getIntensity ( ) ; float min = ImageStatistics . min ( intensity ) ; float max = ImageStatistics . max ( intensity ) ; float range = max - min ; PixelMath . plus ( intensity , - min , intensity ) ; PixelMath . divide ( intensity , range , intensity ) ; PixelMath . multiply ( intensity , 255.0f , intensity ) ; BufferedImage output = new BufferedImage ( image . width , image . height , BufferedImage . TYPE_INT_BGR ) ; VisualizeImageData . grayMagnitude ( intensity , output , - 1 ) ; ShowImages . showWindow ( output , "Match Intensity" , true ) ; } | Computes the template match intensity image and displays the results . Brighter intensity indicates a better match to the template . |
27,482 | private static void drawRectangles ( Graphics2D g2 , GrayF32 image , GrayF32 template , GrayF32 mask , int expectedMatches ) { List < Match > found = findMatches ( image , template , mask , expectedMatches ) ; int r = 2 ; int w = template . width + 2 * r ; int h = template . height + 2 * r ; for ( Match m : found ) { System . out . println ( "Match " + m . x + " " + m . y + " score " + m . score ) ; int x0 = m . x - r ; int y0 = m . y - r ; int x1 = x0 + w ; int y1 = y0 + h ; g2 . drawLine ( x0 , y0 , x1 , y0 ) ; g2 . drawLine ( x1 , y0 , x1 , y1 ) ; g2 . drawLine ( x1 , y1 , x0 , y1 ) ; g2 . drawLine ( x0 , y1 , x0 , y0 ) ; } } | Helper function will is finds matches and displays the results as colored rectangles |
27,483 | public void getCenter ( int which , Point2D_F64 location ) { Quadrilateral_F64 q = alg . getFound ( ) . get ( which ) . distortedPixels ; UtilLine2D_F64 . convert ( q . a , q . c , line02 ) ; UtilLine2D_F64 . convert ( q . b , q . d , line13 ) ; Intersection2D_F64 . intersection ( line02 , line13 , location ) ; } | Return the intersection of two lines defined by opposing corners . This should also be the geometric center |
27,484 | public < T extends SquareNode > T destination ( SquareNode src ) { if ( a == src ) return ( T ) b ; else if ( b == src ) return ( T ) a ; else throw new IllegalArgumentException ( "BUG! src is not a or b" ) ; } | Returns the destination node . |
27,485 | public static String inlierPercent ( VisualOdometry alg ) { if ( ! ( alg instanceof AccessPointTracks3D ) ) return "" ; AccessPointTracks3D access = ( AccessPointTracks3D ) alg ; int count = 0 ; int N = access . getAllTracks ( ) . size ( ) ; for ( int i = 0 ; i < N ; i ++ ) { if ( access . isInlier ( i ) ) count ++ ; } return String . format ( "%%%5.3f" , 100.0 * count / N ) ; } | If the algorithm implements AccessPointTracks3D then count the number of inlier features and return a string . |
27,486 | public static void fitBinaryImage ( GrayF32 input ) { GrayU8 binary = new GrayU8 ( input . width , input . height ) ; BufferedImage polygon = new BufferedImage ( input . width , input . height , BufferedImage . TYPE_INT_RGB ) ; double mean = ImageStatistics . mean ( input ) ; ThresholdImageOps . threshold ( input , binary , ( float ) mean , true ) ; GrayU8 filtered = BinaryImageOps . erode8 ( binary , 1 , null ) ; filtered = BinaryImageOps . dilate8 ( filtered , 1 , null ) ; List < Contour > contours = BinaryImageOps . contour ( filtered , ConnectRule . EIGHT , null ) ; Graphics2D g2 = polygon . createGraphics ( ) ; g2 . setStroke ( new BasicStroke ( 2 ) ) ; for ( Contour c : contours ) { List < PointIndex_I32 > vertexes = ShapeFittingOps . fitPolygon ( c . external , true , minSide , cornerPenalty ) ; g2 . setColor ( Color . RED ) ; VisualizeShapes . drawPolygon ( vertexes , true , g2 ) ; g2 . setColor ( Color . BLUE ) ; for ( List < Point2D_I32 > internal : c . internal ) { vertexes = ShapeFittingOps . fitPolygon ( internal , true , minSide , cornerPenalty ) ; VisualizeShapes . drawPolygon ( vertexes , true , g2 ) ; } } gui . addImage ( polygon , "Binary Blob Contours" ) ; } | Fits polygons to found contours around binary blobs . |
27,487 | public static void fitCannyEdges ( GrayF32 input ) { BufferedImage displayImage = new BufferedImage ( input . width , input . height , BufferedImage . TYPE_INT_RGB ) ; CannyEdge < GrayF32 , GrayF32 > canny = FactoryEdgeDetectors . canny ( 2 , true , true , GrayF32 . class , GrayF32 . class ) ; canny . process ( input , 0.1f , 0.3f , null ) ; List < EdgeContour > contours = canny . getContours ( ) ; Graphics2D g2 = displayImage . createGraphics ( ) ; g2 . setStroke ( new BasicStroke ( 2 ) ) ; Random rand = new Random ( 234 ) ; for ( EdgeContour e : contours ) { g2 . setColor ( new Color ( rand . nextInt ( ) ) ) ; for ( EdgeSegment s : e . segments ) { List < PointIndex_I32 > vertexes = ShapeFittingOps . fitPolygon ( s . points , false , minSide , cornerPenalty ) ; VisualizeShapes . drawPolygon ( vertexes , false , g2 ) ; } } gui . addImage ( displayImage , "Canny Trace" ) ; } | Fits a sequence of line - segments into a sequence of points found using the Canny edge detector . In this case the points are not connected in a loop . The canny detector produces a more complex tree and the fitted points can be a bit noisy compared to the others . |
27,488 | public static void fitCannyBinary ( GrayF32 input ) { BufferedImage displayImage = new BufferedImage ( input . width , input . height , BufferedImage . TYPE_INT_RGB ) ; GrayU8 binary = new GrayU8 ( input . width , input . height ) ; CannyEdge < GrayF32 , GrayF32 > canny = FactoryEdgeDetectors . canny ( 2 , false , true , GrayF32 . class , GrayF32 . class ) ; canny . process ( input , 0.1f , 0.3f , binary ) ; List < Contour > contours = BinaryImageOps . contourExternal ( binary , ConnectRule . EIGHT ) ; Graphics2D g2 = displayImage . createGraphics ( ) ; g2 . setStroke ( new BasicStroke ( 2 ) ) ; Random rand = new Random ( 234 ) ; for ( Contour c : contours ) { List < PointIndex_I32 > vertexes = ShapeFittingOps . fitPolygon ( c . external , true , minSide , cornerPenalty ) ; g2 . setColor ( new Color ( rand . nextInt ( ) ) ) ; VisualizeShapes . drawPolygon ( vertexes , true , g2 ) ; } gui . addImage ( displayImage , "Canny Contour" ) ; } | Detects contours inside the binary image generated by canny . Only the external contour is relevant . Often easier to deal with than working with Canny edges directly . |
27,489 | protected Confusion evaluate ( Map < String , List < String > > set ) { ClassificationHistogram histogram = new ClassificationHistogram ( scenes . size ( ) ) ; int total = 0 ; for ( int i = 0 ; i < scenes . size ( ) ; i ++ ) { total += set . get ( scenes . get ( i ) ) . size ( ) ; } System . out . println ( "total images " + total ) ; for ( int i = 0 ; i < scenes . size ( ) ; i ++ ) { String scene = scenes . get ( i ) ; List < String > images = set . get ( scene ) ; System . out . println ( " " + scene + " " + images . size ( ) ) ; for ( String image : images ) { int predicted = classify ( image ) ; histogram . increment ( i , predicted ) ; } } return histogram . createConfusion ( ) ; } | Given a set of images with known classification predict which scene each one belongs in and compute a confusion matrix for the results . |
27,490 | public static Map < String , List < String > > findImages ( File rootDir ) { File files [ ] = rootDir . listFiles ( ) ; if ( files == null ) return null ; List < File > imageDirectories = new ArrayList < > ( ) ; for ( File f : files ) { if ( f . isDirectory ( ) ) { imageDirectories . add ( f ) ; } } Map < String , List < String > > out = new HashMap < > ( ) ; for ( File d : imageDirectories ) { List < String > images = new ArrayList < > ( ) ; files = d . listFiles ( ) ; if ( files == null ) throw new RuntimeException ( "Should be a directory!" ) ; for ( File f : files ) { if ( f . isHidden ( ) || f . isDirectory ( ) || f . getName ( ) . endsWith ( ".txt" ) ) { continue ; } images . add ( f . getPath ( ) ) ; } String key = d . getName ( ) . toLowerCase ( ) ; out . put ( key , images ) ; } return out ; } | Loads the paths to image files contained in subdirectories of the root directory . Each sub directory is assumed to be a different category of images . |
27,491 | public synchronized void setImages ( BufferedImage leftImage , BufferedImage rightImage ) { this . leftImage = leftImage ; this . rightImage = rightImage ; setPreferredSize ( leftImage . getWidth ( ) , leftImage . getHeight ( ) , rightImage . getWidth ( ) , rightImage . getHeight ( ) ) ; } | Sets the internal images . Not thread safe . |
27,492 | private void computeScales ( ) { int width = getWidth ( ) ; int height = getHeight ( ) ; width = ( width - borderSize ) / 2 ; scaleLeft = scaleRight = 1 ; if ( leftImage . getWidth ( ) > width || leftImage . getHeight ( ) > height ) { double scaleX = ( double ) width / ( double ) leftImage . getWidth ( ) ; double scaleY = ( double ) height / ( double ) leftImage . getHeight ( ) ; scaleLeft = Math . min ( scaleX , scaleY ) ; } if ( rightImage . getWidth ( ) > width || rightImage . getHeight ( ) > height ) { double scaleX = ( double ) width / ( double ) rightImage . getWidth ( ) ; double scaleY = ( double ) height / ( double ) rightImage . getHeight ( ) ; scaleRight = Math . min ( scaleX , scaleY ) ; } } | Compute individually how each image will be scaled |
27,493 | public static void normalize ( GrayF32 image , float mean , float stdev ) { for ( int y = 0 ; y < image . height ; y ++ ) { int index = image . startIndex + y * image . stride ; int end = index + image . width ; while ( index < end ) { image . data [ index ] = ( image . data [ index ] - mean ) / stdev ; index ++ ; } } } | Normalizes a gray scale image by first subtracting the mean then dividing by stdev . |
27,494 | public static Kernel1D_F32 create1D_F32 ( double [ ] kernel ) { Kernel1D_F32 k = new Kernel1D_F32 ( kernel . length , kernel . length / 2 ) ; for ( int i = 0 ; i < kernel . length ; i ++ ) { k . data [ i ] = ( float ) kernel [ i ] ; } return k ; } | Converts the double array into a 1D float kernel |
27,495 | public static void imageToTensor ( Planar < GrayF32 > input , Tensor_F32 output , int miniBatch ) { if ( input . isSubimage ( ) ) throw new RuntimeException ( "Subimages not accepted" ) ; if ( output . getDimension ( ) != 4 ) throw new IllegalArgumentException ( "Output should be 4-DOF. batch + spatial (channel,height,width)" ) ; if ( output . length ( 1 ) != input . getNumBands ( ) ) throw new IllegalArgumentException ( "Number of bands don't match" ) ; if ( output . length ( 2 ) != input . getHeight ( ) ) throw new IllegalArgumentException ( "Spatial height doesn't match" ) ; if ( output . length ( 3 ) != input . getWidth ( ) ) throw new IllegalArgumentException ( "Spatial width doesn't match" ) ; for ( int i = 0 ; i < input . getNumBands ( ) ; i ++ ) { GrayF32 band = input . getBand ( i ) ; int indexOut = output . idx ( miniBatch , i , 0 , 0 ) ; int length = input . width * input . height ; System . arraycopy ( band . data , 0 , output . d , indexOut , length ) ; } } | Converts an image into a spatial tensor |
27,496 | public void process ( GrayU8 binary , int adjustX , int adjustY ) { this . adjustX = adjustX ; this . adjustY = adjustY ; storagePoints . reset ( ) ; ImageMiscOps . fillBorder ( binary , 0 , 1 ) ; tracer . setInputs ( binary ) ; final byte binaryData [ ] = binary . data ; for ( int y = 1 ; y < binary . height - 1 ; y ++ ) { int x = 1 ; int indexBinary = binary . startIndex + y * binary . stride + 1 ; int end = indexBinary + binary . width - 2 ; while ( true ) { int delta = findNotZero ( binaryData , indexBinary , end ) - indexBinary ; indexBinary += delta ; if ( indexBinary == end ) break ; x += delta ; if ( binaryData [ indexBinary ] == 1 ) { if ( tracer . trace ( x , y , true ) ) { int N = storagePoints . sizeOfTail ( ) ; if ( N < minContourLength || N >= maxContourLength ) storagePoints . removeTail ( ) ; } else { storagePoints . removeTail ( ) ; } } delta = findZero ( binaryData , indexBinary , end ) - indexBinary ; indexBinary += delta ; if ( indexBinary == end ) break ; x += delta ; if ( binaryData [ indexBinary - 1 ] == 1 ) { tracer . trace ( x - 1 , y , false ) ; storagePoints . removeTail ( ) ; } else { binaryData [ indexBinary - 1 ] = - 2 ; } } } } | Detects contours inside the binary image . |
27,497 | static int findNotZero ( byte [ ] data , int index , int end ) { while ( index < end && data [ index ] == 0 ) { index ++ ; } return index ; } | Searches for a value in the array which is not zero . |
27,498 | static int findZero ( byte [ ] data , int index , int end ) { while ( index < end && data [ index ] != 0 ) { index ++ ; } return index ; } | Searches for a value in the array which is zero . |
27,499 | public void addPatternImage ( T pattern , double threshold , double lengthSide ) { GrayU8 binary = new GrayU8 ( pattern . width , pattern . height ) ; GThresholdImageOps . threshold ( pattern , binary , threshold , false ) ; alg . addPattern ( binary , lengthSide ) ; } | Add a new pattern to be detected . This function takes in a raw gray scale image and thresholds it . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.