idx int64 0 165k | question stringlengths 73 4.15k | target stringlengths 5 918 | len_question int64 21 890 | len_target int64 3 255 |
|---|---|---|---|---|
27,300 | protected void learnAmbiguousNegative ( Rectangle2D_F64 targetRegion ) { TldHelperFunctions . convertRegion ( targetRegion , targetRegion_I32 ) ; if ( detection . isSuccess ( ) ) { TldRegion best = detection . getBest ( ) ; // see if it found the correct solution double overlap = helper . computeOverlap ( best . rect , targetRegion_I32 ) ; if ( overlap <= config . overlapLower ) { template . addDescriptor ( false , best . rect ) ; // fern.learnFernNoise(false, best.rect ); } // mark all ambiguous regions as bad List < ImageRectangle > ambiguous = detection . getAmbiguousRegions ( ) ; for ( ImageRectangle r : ambiguous ) { overlap = helper . computeOverlap ( r , targetRegion_I32 ) ; if ( overlap <= config . overlapLower ) { fern . learnFernNoise ( false , r ) ; template . addDescriptor ( false , r ) ; } } } } | Mark regions which were local maximums and had high confidence as negative . These regions were candidates for the tracker but were not selected | 221 | 25 |
27,301 | public static < T extends ImageGray < T > > InputToBinary < T > localOtsu ( ConfigLength regionWidth , double scale , boolean down , boolean otsu2 , double tuning , Class < T > inputType ) { if ( BOverrideFactoryThresholdBinary . localOtsu != null ) return BOverrideFactoryThresholdBinary . localOtsu . handle ( otsu2 , regionWidth , tuning , scale , down , inputType ) ; ThresholdLocalOtsu otsu ; if ( BoofConcurrency . USE_CONCURRENT ) { otsu = new ThresholdLocalOtsu_MT ( otsu2 , regionWidth , tuning , scale , down ) ; } else { otsu = new ThresholdLocalOtsu ( otsu2 , regionWidth , tuning , scale , down ) ; } return new InputToBinarySwitch <> ( otsu , inputType ) ; } | Applies a local Otsu threshold | 205 | 8 |
27,302 | public static < T extends ImageGray < T > > InputToBinary < T > blockMean ( ConfigLength regionWidth , double scale , boolean down , boolean thresholdFromLocalBlocks , Class < T > inputType ) { if ( BOverrideFactoryThresholdBinary . blockMean != null ) return BOverrideFactoryThresholdBinary . blockMean . handle ( regionWidth , scale , down , thresholdFromLocalBlocks , inputType ) ; BlockProcessor processor ; if ( inputType == GrayU8 . class ) processor = new ThresholdBlockMean_U8 ( scale , down ) ; else processor = new ThresholdBlockMean_F32 ( ( float ) scale , down ) ; if ( BoofConcurrency . USE_CONCURRENT ) { return new ThresholdBlock_MT ( processor , regionWidth , thresholdFromLocalBlocks , inputType ) ; } else { return new ThresholdBlock ( processor , regionWidth , thresholdFromLocalBlocks , inputType ) ; } } | Applies a non - overlapping block mean threshold | 209 | 9 |
27,303 | public static < T extends ImageGray < T > > InputToBinary < T > blockOtsu ( ConfigLength regionWidth , double scale , boolean down , boolean thresholdFromLocalBlocks , boolean otsu2 , double tuning , Class < T > inputType ) { if ( BOverrideFactoryThresholdBinary . blockOtsu != null ) return BOverrideFactoryThresholdBinary . blockOtsu . handle ( otsu2 , regionWidth , tuning , scale , down , thresholdFromLocalBlocks , inputType ) ; BlockProcessor processor = new ThresholdBlockOtsu ( otsu2 , tuning , scale , down ) ; InputToBinary < GrayU8 > otsu ; if ( BoofConcurrency . USE_CONCURRENT ) { otsu = new ThresholdBlock_MT <> ( processor , regionWidth , thresholdFromLocalBlocks , GrayU8 . class ) ; } else { otsu = new ThresholdBlock <> ( processor , regionWidth , thresholdFromLocalBlocks , GrayU8 . class ) ; } return new InputToBinarySwitch <> ( otsu , inputType ) ; } | Applies a non - overlapping block Otsu threshold | 246 | 11 |
27,304 | public static < T extends ImageGray < T > > InputToBinary < T > threshold ( ConfigThreshold config , Class < T > inputType ) { switch ( config . type ) { case FIXED : return globalFixed ( config . fixedThreshold , config . down , inputType ) ; case GLOBAL_OTSU : return globalOtsu ( config . minPixelValue , config . maxPixelValue , config . scale , config . down , inputType ) ; case GLOBAL_ENTROPY : return globalEntropy ( config . minPixelValue , config . maxPixelValue , config . scale , config . down , inputType ) ; case GLOBAL_LI : return globalLi ( config . minPixelValue , config . maxPixelValue , config . scale , config . down , inputType ) ; case GLOBAL_HUANG : return globalHuang ( config . minPixelValue , config . maxPixelValue , config . scale , config . down , inputType ) ; case LOCAL_GAUSSIAN : return localGaussian ( config . width , config . scale , config . down , inputType ) ; case LOCAL_SAVOLA : return localSauvola ( config . width , config . down , config . savolaK , inputType ) ; case LOCAL_NICK : return localNick ( config . width , config . down , config . nickK , inputType ) ; case LOCAL_MEAN : return localMean ( config . width , config . scale , config . down , inputType ) ; case LOCAL_OTSU : { ConfigThresholdLocalOtsu c = ( ConfigThresholdLocalOtsu ) config ; return localOtsu ( config . width , config . scale , config . down , c . useOtsu2 , c . tuning , inputType ) ; } case BLOCK_MIN_MAX : { ConfigThresholdBlockMinMax c = ( ConfigThresholdBlockMinMax ) config ; return blockMinMax ( c . width , c . scale , c . down , c . thresholdFromLocalBlocks , c . minimumSpread , inputType ) ; } case BLOCK_MEAN : return blockMean ( config . width , config . scale , config . down , config . thresholdFromLocalBlocks , inputType ) ; case BLOCK_OTSU : { ConfigThresholdLocalOtsu c = ( ConfigThresholdLocalOtsu ) config ; return blockOtsu ( c . width , c . scale , c . down , c . thresholdFromLocalBlocks , c . useOtsu2 , c . tuning , inputType ) ; } } throw new IllegalArgumentException ( "Unknown type " + config . type ) ; } | Creates threshold using a config class | 579 | 7 |
27,305 | public void constraintSouth ( JComponent target , JComponent top , JComponent bottom , int padV ) { if ( bottom == null ) { layout . putConstraint ( SpringLayout . SOUTH , target , - padV , SpringLayout . SOUTH , this ) ; } else { Spring a = Spring . sum ( Spring . constant ( - padV ) , layout . getConstraint ( SpringLayout . NORTH , bottom ) ) ; Spring b ; if ( top == null ) b = Spring . sum ( Spring . height ( target ) , layout . getConstraint ( SpringLayout . NORTH , this ) ) ; else b = Spring . sum ( Spring . height ( target ) , layout . getConstraint ( SpringLayout . SOUTH , top ) ) ; layout . getConstraints ( target ) . setConstraint ( SpringLayout . SOUTH , Spring . max ( a , b ) ) ; } } | Constrain it to the top of it s bottom panel and prevent it from getting crushed below it s size | 196 | 22 |
27,306 | public void setLensDistoriton ( LensDistortionNarrowFOV distortion ) { pixelToNorm = distortion . undistort_F64 ( true , false ) ; normToPixel = distortion . distort_F64 ( false , true ) ; } | Specifies the intrinsic parameters . | 53 | 6 |
27,307 | public void setFiducial ( double x0 , double y0 , double x1 , double y1 , double x2 , double y2 , double x3 , double y3 ) { points . get ( 0 ) . location . set ( x0 , y0 , 0 ) ; points . get ( 1 ) . location . set ( x1 , y1 , 0 ) ; points . get ( 2 ) . location . set ( x2 , y2 , 0 ) ; points . get ( 3 ) . location . set ( x3 , y3 , 0 ) ; } | Specify the location of points on the 2D fiducial . These should be in world coordinates | 122 | 20 |
27,308 | public void pixelToMarker ( double pixelX , double pixelY , Point2D_F64 marker ) { // find pointing vector in camera reference frame pixelToNorm . compute ( pixelX , pixelY , marker ) ; cameraP3 . set ( marker . x , marker . y , 1 ) ; // rotate into marker reference frame GeometryMath_F64 . multTran ( outputFiducialToCamera . R , cameraP3 , ray . slope ) ; GeometryMath_F64 . multTran ( outputFiducialToCamera . R , outputFiducialToCamera . T , ray . p ) ; ray . p . scale ( - 1 ) ; double t = - ray . p . z / ray . slope . z ; marker . x = ray . p . x + ray . slope . x * t ; marker . y = ray . p . y + ray . slope . y * t ; } | Given the found solution compute the the observed pixel would appear on the marker s surface . pixel - > normalized pixel - > rotated - > projected on to plane | 199 | 31 |
27,309 | protected boolean estimate ( Quadrilateral_F64 cornersPixels , Quadrilateral_F64 cornersNorm , Se3_F64 foundFiducialToCamera ) { // put it into a list to simplify algorithms listObs . clear ( ) ; listObs . add ( cornersPixels . a ) ; listObs . add ( cornersPixels . b ) ; listObs . add ( cornersPixels . c ) ; listObs . add ( cornersPixels . d ) ; // convert observations into normalized image coordinates which P3P requires points . get ( 0 ) . observation . set ( cornersNorm . a ) ; points . get ( 1 ) . observation . set ( cornersNorm . b ) ; points . get ( 2 ) . observation . set ( cornersNorm . c ) ; points . get ( 3 ) . observation . set ( cornersNorm . d ) ; // estimate pose using all permutations bestError = Double . MAX_VALUE ; estimateP3P ( 0 ) ; estimateP3P ( 1 ) ; estimateP3P ( 2 ) ; estimateP3P ( 3 ) ; if ( bestError == Double . MAX_VALUE ) return false ; // refine the best estimate inputP3P . clear ( ) ; for ( int i = 0 ; i < 4 ; i ++ ) { inputP3P . add ( points . get ( i ) ) ; } // got poor or horrible solution the first way, let's try it with EPNP // and see if it does better if ( bestError > 2 ) { if ( epnp . process ( inputP3P , foundEPNP ) ) { if ( foundEPNP . T . z > 0 ) { double error = computeErrors ( foundEPNP ) ; // System.out.println(" error EPNP = "+error); if ( error < bestError ) { bestPose . set ( foundEPNP ) ; } } } } if ( ! refine . fitModel ( inputP3P , bestPose , foundFiducialToCamera ) ) { // us the previous estimate instead foundFiducialToCamera . set ( bestPose ) ; return true ; } return true ; } | Given the observed corners of the quad in the image in pixels estimate and store the results of its pose | 458 | 20 |
27,310 | protected void estimateP3P ( int excluded ) { // the point used to check the solutions is the last one inputP3P . clear ( ) ; for ( int i = 0 ; i < 4 ; i ++ ) { if ( i != excluded ) { inputP3P . add ( points . get ( i ) ) ; } } // initial estimate for the pose solutions . reset ( ) ; if ( ! p3p . process ( inputP3P , solutions ) ) { // System.err.println("PIP Failed!?! That's weird"); return ; } for ( int i = 0 ; i < solutions . size ; i ++ ) { double error = computeErrors ( solutions . get ( i ) ) ; // see if it's better and it should save the results if ( error < bestError ) { bestError = error ; bestPose . set ( solutions . get ( i ) ) ; } } } | Estimates the pose using P3P from 3 out of 4 points . Then use all 4 to pick the best solution | 194 | 24 |
27,311 | protected void enlarge ( Quadrilateral_F64 corners , double scale ) { UtilPolygons2D_F64 . center ( corners , center ) ; extend ( center , corners . a , scale ) ; extend ( center , corners . b , scale ) ; extend ( center , corners . c , scale ) ; extend ( center , corners . d , scale ) ; } | Enlarges the quadrilateral to make it more sensitive to changes in orientation | 79 | 16 |
27,312 | protected double computeErrors ( Se3_F64 fiducialToCamera ) { if ( fiducialToCamera . T . z < 0 ) { // the low level algorithm should already filter this code, but just incase return Double . MAX_VALUE ; } double maxError = 0 ; for ( int i = 0 ; i < 4 ; i ++ ) { maxError = Math . max ( maxError , computePixelError ( fiducialToCamera , points . get ( i ) . location , listObs . get ( i ) ) ) ; } return maxError ; } | Compute the sum of reprojection errors for all four points | 122 | 12 |
27,313 | @ Override public void encode ( DMatrixRMaj F , double [ ] param ) { // see if which columns are to be used selectColumns ( F ) ; // set the largest element in the first two columns and normalize // using that value double v [ ] = new double [ ] { F . get ( 0 , col0 ) , F . get ( 1 , col0 ) , F . get ( 2 , col0 ) , F . get ( 0 , col1 ) , F . get ( 1 , col1 ) , F . get ( 2 , col1 ) } ; double divisor = selectDivisor ( v , param ) ; // solve for alpha and beta and put into param SimpleMatrix A = new SimpleMatrix ( 3 , 2 ) ; SimpleMatrix y = new SimpleMatrix ( 3 , 1 ) ; for ( int i = 0 ; i < 3 ; i ++ ) { A . set ( i , 0 , v [ i ] ) ; A . set ( i , 1 , v [ i + 3 ] ) ; y . set ( i , 0 , F . get ( i , col2 ) / divisor ) ; } SimpleMatrix x = A . solve ( y ) ; param [ 5 ] = x . get ( 0 ) ; param [ 6 ] = x . get ( 1 ) ; } | Examines the matrix structure to determine how to parameterize F . | 280 | 13 |
27,314 | private double selectDivisor ( double v [ ] , double param [ ] ) { double maxValue = 0 ; int maxIndex = 0 ; for ( int i = 0 ; i < v . length ; i ++ ) { if ( Math . abs ( v [ i ] ) > maxValue ) { maxValue = Math . abs ( v [ i ] ) ; maxIndex = i ; } } double divisor = v [ maxIndex ] ; int index = 0 ; for ( int i = 0 ; i < v . length ; i ++ ) { v [ i ] /= divisor ; if ( i != maxIndex ) { // save first 5 parameters param [ index ] = v [ i ] ; // save indexes in the matrix int col = i < 3 ? col0 : col1 ; indexes [ index ++ ] = 3 * ( i % 3 ) + col ; } } // index of 1 int col = maxIndex >= 3 ? col1 : col0 ; indexes [ 5 ] = 3 * ( maxIndex % 3 ) + col ; return divisor ; } | The divisor is the element in the first two columns that has the largest absolute value . Finds this element sets col0 to be the row which contains it and specifies which elements in that column are to be used . | 226 | 45 |
27,315 | protected void createEdge ( String src , String dst , FastQueue < AssociatedPair > pairs , FastQueue < AssociatedIndex > matches ) { // Fitting Essential/Fundamental works when the scene is not planar and not pure rotation int countF = 0 ; if ( ransac3D . process ( pairs . toList ( ) ) ) { countF = ransac3D . getMatchSet ( ) . size ( ) ; } // Fitting homography will work when all or part of the scene is planar or motion is pure rotation int countH = 0 ; if ( ransacH . process ( pairs . toList ( ) ) ) { countH = ransacH . getMatchSet ( ) . size ( ) ; } // fail if not enough features are remaining after RANSAC if ( Math . max ( countF , countH ) < minimumInliers ) return ; // The idea here is that if the number features for F is greater than H then it's a 3D scene. // If they are similar then it might be a plane boolean is3D = countF > countH * ratio3D ; PairwiseImageGraph2 . Motion edge = graph . edges . grow ( ) ; edge . is3D = is3D ; edge . countF = countF ; edge . countH = countH ; edge . index = graph . edges . size - 1 ; edge . src = graph . lookupNode ( src ) ; edge . dst = graph . lookupNode ( dst ) ; edge . src . connections . add ( edge ) ; edge . dst . connections . add ( edge ) ; if ( is3D ) { saveInlierMatches ( ransac3D , matches , edge ) ; edge . F . set ( ransac3D . getModelParameters ( ) ) ; } else { saveInlierMatches ( ransacH , matches , edge ) ; Homography2D_F64 H = ransacH . getModelParameters ( ) ; ConvertDMatrixStruct . convert ( H , edge . F ) ; } } | Connects two views together if they meet a minimal set of geometric requirements . Determines if there is strong evidence that there is 3D information present and not just a homography | 439 | 36 |
27,316 | private void saveInlierMatches ( ModelMatcher < ? , ? > ransac , FastQueue < AssociatedIndex > matches , PairwiseImageGraph2 . Motion edge ) { int N = ransac . getMatchSet ( ) . size ( ) ; edge . inliers . reset ( ) ; for ( int i = 0 ; i < N ; i ++ ) { int idx = ransac . getInputIndex ( i ) ; edge . inliers . grow ( ) . set ( matches . get ( idx ) ) ; } } | Puts the inliers from RANSAC into the edge s list of associated features | 118 | 18 |
27,317 | protected void recycleData ( ) { for ( int i = 0 ; i < nodes . size ( ) ; i ++ ) { SquareNode n = nodes . get ( i ) ; for ( int j = 0 ; j < n . edges . length ; j ++ ) { if ( n . edges [ j ] != null ) { graph . detachEdge ( n . edges [ j ] ) ; } } } for ( int i = 0 ; i < nodes . size ( ) ; i ++ ) { SquareNode n = nodes . get ( i ) ; for ( int j = 0 ; j < n . edges . length ; j ++ ) { if ( n . edges [ j ] != null ) throw new RuntimeException ( "BUG!" ) ; } } nodes . reset ( ) ; for ( int i = 0 ; i < clusters . size ; i ++ ) { clusters . get ( i ) . clear ( ) ; } clusters . reset ( ) ; } | Reset and recycle data structures from the previous run | 198 | 10 |
27,318 | protected void findClusters ( ) { for ( int i = 0 ; i < nodes . size ( ) ; i ++ ) { SquareNode n = nodes . get ( i ) ; if ( n . graph < 0 ) { n . graph = clusters . size ( ) ; List < SquareNode > graph = clusters . grow ( ) ; graph . add ( n ) ; addToCluster ( n , graph ) ; } } } | Put sets of nodes into the same list if they are some how connected | 90 | 14 |
27,319 | void addToCluster ( SquareNode seed , List < SquareNode > graph ) { open . clear ( ) ; open . add ( seed ) ; while ( ! open . isEmpty ( ) ) { SquareNode n = open . remove ( open . size ( ) - 1 ) ; for ( int i = 0 ; i < n . square . size ( ) ; i ++ ) { SquareEdge edge = n . edges [ i ] ; if ( edge == null ) continue ; SquareNode other ; if ( edge . a == n ) other = edge . b ; else if ( edge . b == n ) other = edge . a ; else throw new RuntimeException ( "BUG!" ) ; if ( other . graph == SquareNode . RESET_GRAPH ) { other . graph = n . graph ; graph . add ( other ) ; open . add ( other ) ; } else if ( other . graph != n . graph ) { throw new RuntimeException ( "BUG! " + other . graph + " " + n . graph ) ; } } } } | Finds all neighbors and adds them to the graph . Repeated until there are no more nodes to add to the graph | 220 | 24 |
27,320 | public static void printClickedColor ( final BufferedImage image ) { ImagePanel gui = new ImagePanel ( image ) ; gui . addMouseListener ( new MouseAdapter ( ) { @ Override public void mouseClicked ( MouseEvent e ) { float [ ] color = new float [ 3 ] ; int rgb = image . getRGB ( e . getX ( ) , e . getY ( ) ) ; ColorHsv . rgbToHsv ( ( rgb >> 16 ) & 0xFF , ( rgb >> 8 ) & 0xFF , rgb & 0xFF , color ) ; System . out . println ( "H = " + color [ 0 ] + " S = " + color [ 1 ] + " V = " + color [ 2 ] ) ; showSelectedColor ( "Selected" , image , color [ 0 ] , color [ 1 ] ) ; } } ) ; ShowImages . showWindow ( gui , "Color Selector" ) ; } | Shows a color image and allows the user to select a pixel convert it to HSV print the HSV values and calls the function below to display similar pixels . | 204 | 33 |
27,321 | public static void showSelectedColor ( String name , BufferedImage image , float hue , float saturation ) { Planar < GrayF32 > input = ConvertBufferedImage . convertFromPlanar ( image , null , true , GrayF32 . class ) ; Planar < GrayF32 > hsv = input . createSameShape ( ) ; // Convert into HSV ColorHsv . rgbToHsv ( input , hsv ) ; // Euclidean distance squared threshold for deciding which pixels are members of the selected set float maxDist2 = 0.4f * 0.4f ; // Extract hue and saturation bands which are independent of intensity GrayF32 H = hsv . getBand ( 0 ) ; GrayF32 S = hsv . getBand ( 1 ) ; // Adjust the relative importance of Hue and Saturation. // Hue has a range of 0 to 2*PI and Saturation from 0 to 1. float adjustUnits = ( float ) ( Math . PI / 2.0 ) ; // step through each pixel and mark how close it is to the selected color BufferedImage output = new BufferedImage ( input . width , input . height , BufferedImage . TYPE_INT_RGB ) ; for ( int y = 0 ; y < hsv . height ; y ++ ) { for ( int x = 0 ; x < hsv . width ; x ++ ) { // Hue is an angle in radians, so simple subtraction doesn't work float dh = UtilAngle . dist ( H . unsafe_get ( x , y ) , hue ) ; float ds = ( S . unsafe_get ( x , y ) - saturation ) * adjustUnits ; // this distance measure is a bit naive, but good enough for to demonstrate the concept float dist2 = dh * dh + ds * ds ; if ( dist2 <= maxDist2 ) { output . setRGB ( x , y , image . getRGB ( x , y ) ) ; } } } ShowImages . showWindow ( output , "Showing " + name ) ; } | Selectively displays only pixels which have a similar hue and saturation values to what is provided . This is intended to be a simple example of color based segmentation . Color based segmentation can be done in RGB color but is more problematic due to it not being intensity invariant . More robust techniques can use Gaussian models instead of a uniform distribution as is done below . | 436 | 73 |
27,322 | public static ImageDimension transformDimension ( ImageBase orig , int level ) { return transformDimension ( orig . width , orig . height , level ) ; } | Returns dimension which is required for the transformed image in a multilevel wavelet transform . | 34 | 18 |
27,323 | public static int borderForwardLower ( WlCoef desc ) { int ret = - Math . min ( desc . offsetScaling , desc . offsetWavelet ) ; return ret + ( ret % 2 ) ; } | Returns the lower border for a forward wavelet transform . | 45 | 11 |
27,324 | public static int borderInverseLower ( WlBorderCoef < ? > desc , BorderIndex1D border ) { WlCoef inner = desc . getInnerCoefficients ( ) ; int borderSize = borderForwardLower ( inner ) ; WlCoef ll = borderSize > 0 ? inner : null ; WlCoef lu = ll ; WlCoef uu = inner ; int indexLU = 0 ; if ( desc . getLowerLength ( ) > 0 ) { ll = desc . getBorderCoefficients ( 0 ) ; indexLU = desc . getLowerLength ( ) * 2 - 2 ; lu = desc . getBorderCoefficients ( indexLU ) ; } if ( desc . getUpperLength ( ) > 0 ) { uu = desc . getBorderCoefficients ( - 2 ) ; } border . setLength ( 2000 ) ; borderSize = checkInverseLower ( ll , 0 , border , borderSize ) ; borderSize = checkInverseLower ( lu , indexLU , border , borderSize ) ; borderSize = checkInverseLower ( uu , 1998 , border , borderSize ) ; return borderSize ; } | Returns the lower border for an inverse wavelet transform . | 253 | 11 |
27,325 | public static int round ( int top , int div2 , int divisor ) { if ( top > 0 ) return ( top + div2 ) / divisor ; else return ( top - div2 ) / divisor ; } | Specialized rounding for use with integer wavelet transform . | 50 | 11 |
27,326 | public static void adjustForDisplay ( ImageGray transform , int numLevels , double valueRange ) { if ( transform instanceof GrayF32 ) adjustForDisplay ( ( GrayF32 ) transform , numLevels , ( float ) valueRange ) ; else adjustForDisplay ( ( GrayI ) transform , numLevels , ( int ) valueRange ) ; } | Adjusts the values inside a wavelet transform to make it easier to view . | 75 | 16 |
27,327 | public static void equalizeLocalNaive ( GrayU8 input , int radius , GrayU8 output , IWorkArrays workArrays ) { int width = 2 * radius + 1 ; int maxValue = workArrays . length ( ) - 1 ; //CONCURRENT_BELOW BoofConcurrency.loopBlocks(0,input.height,(idx0,idx1)->{ int idx0 = 0 , idx1 = input . height ; int [ ] histogram = workArrays . pop ( ) ; for ( int y = idx0 ; y < idx1 ; y ++ ) { // make sure it's inside the image bounds int y0 = y - radius ; int y1 = y + radius + 1 ; if ( y0 < 0 ) { y0 = 0 ; y1 = width ; if ( y1 > input . height ) y1 = input . height ; } else if ( y1 > input . height ) { y1 = input . height ; y0 = y1 - width ; if ( y0 < 0 ) y0 = 0 ; } // pixel indexes int indexIn = input . startIndex + y * input . stride ; int indexOut = output . startIndex + y * output . stride ; for ( int x = 0 ; x < input . width ; x ++ ) { // make sure it's inside the image bounds int x0 = x - radius ; int x1 = x + radius + 1 ; if ( x0 < 0 ) { x0 = 0 ; x1 = width ; if ( x1 > input . width ) x1 = input . width ; } else if ( x1 > input . width ) { x1 = input . width ; x0 = x1 - width ; if ( x0 < 0 ) x0 = 0 ; } // compute the local histogram localHistogram ( input , x0 , y0 , x1 , y1 , histogram ) ; // only need to compute up to the value of the input pixel int inputValue = input . data [ indexIn ++ ] & 0xFF ; int sum = 0 ; for ( int i = 0 ; i <= inputValue ; i ++ ) { sum += histogram [ i ] ; } int area = ( y1 - y0 ) * ( x1 - x0 ) ; output . data [ indexOut ++ ] = ( byte ) ( ( sum * maxValue ) / area ) ; } } workArrays . recycle ( histogram ) ; //CONCURRENT_ABOVE }); } | Inefficiently computes the local histogram but can handle every possible case for image size and local region size | 539 | 23 |
27,328 | public static void equalizeLocalInner ( GrayU8 input , int radius , GrayU8 output , IWorkArrays workArrays ) { int width = 2 * radius + 1 ; int area = width * width ; int maxValue = workArrays . length ( ) - 1 ; //CONCURRENT_BELOW BoofConcurrency.loopBlocks(radius,input.height-radius,(y0,y1)->{ int y0 = radius , y1 = input . height - radius ; int [ ] histogram = workArrays . pop ( ) ; for ( int y = y0 ; y < y1 ; y ++ ) { localHistogram ( input , 0 , y - radius , width , y + radius + 1 , histogram ) ; // compute equalized pixel value using the local histogram int inputValue = input . unsafe_get ( radius , y ) ; int sum = 0 ; for ( int i = 0 ; i <= inputValue ; i ++ ) { sum += histogram [ i ] ; } output . set ( radius , y , ( sum * maxValue ) / area ) ; // start of old and new columns in histogram region int indexOld = input . startIndex + y * input . stride ; int indexNew = indexOld + width ; // index of pixel being examined int indexIn = input . startIndex + y * input . stride + radius + 1 ; int indexOut = output . startIndex + y * output . stride + radius + 1 ; for ( int x = radius + 1 ; x < input . width - radius ; x ++ ) { // update local histogram by removing the left column for ( int i = - radius ; i <= radius ; i ++ ) { histogram [ input . data [ indexOld + i * input . stride ] & 0xFF ] -- ; } // update local histogram by adding the right column for ( int i = - radius ; i <= radius ; i ++ ) { histogram [ input . data [ indexNew + i * input . stride ] & 0xFF ] ++ ; } // compute equalized pixel value using the local histogram inputValue = input . data [ indexIn ++ ] & 0xFF ; sum = 0 ; for ( int i = 0 ; i <= inputValue ; i ++ ) { sum += histogram [ i ] ; } output . data [ indexOut ++ ] = ( byte ) ( ( sum * maxValue ) / area ) ; indexOld ++ ; indexNew ++ ; } } workArrays . recycle ( histogram ) ; //CONCURRENT_ABOVE }); } | Performs local histogram equalization just on the inner portion of the image | 547 | 15 |
27,329 | public static void localHistogram ( GrayU16 input , int x0 , int y0 , int x1 , int y1 , int histogram [ ] ) { for ( int i = 0 ; i < histogram . length ; i ++ ) histogram [ i ] = 0 ; for ( int i = y0 ; i < y1 ; i ++ ) { int index = input . startIndex + i * input . stride + x0 ; int end = index + x1 - x0 ; for ( ; index < end ; index ++ ) { histogram [ input . data [ index ] & 0xFFFF ] ++ ; } } } | Computes the local histogram just for the specified inner region | 135 | 12 |
27,330 | public synchronized void setBufferedImage ( BufferedImage image ) { // assume the image was initially set before the GUI was invoked if ( checkEventDispatch && this . img != null ) { if ( ! SwingUtilities . isEventDispatchThread ( ) ) throw new RuntimeException ( "Changed image when not in GUI thread?" ) ; } this . img = image ; if ( image != null ) updateSize ( image . getWidth ( ) , image . getHeight ( ) ) ; } | Change the image being displayed . | 101 | 6 |
27,331 | public void initialize ( T image , RectangleLength2D_I32 initial ) { if ( ! image . isInBounds ( initial . x0 , initial . y0 ) ) throw new IllegalArgumentException ( "Initial rectangle is out of bounds!" ) ; if ( ! image . isInBounds ( initial . x0 + initial . width , initial . y0 + initial . height ) ) throw new IllegalArgumentException ( "Initial rectangle is out of bounds!" ) ; pdf . reshape ( image . width , image . height ) ; ImageMiscOps . fill ( pdf , - 1 ) ; setTrackLocation ( initial ) ; failed = false ; // compute the initial sum of the likelihood so that it can detect when the target is no longer visible minimumSum = 0 ; targetModel . setImage ( image ) ; for ( int y = 0 ; y < initial . height ; y ++ ) { for ( int x = 0 ; x < initial . width ; x ++ ) { minimumSum += targetModel . compute ( x + initial . x0 , y + initial . y0 ) ; } } minimumSum *= minFractionDrop ; } | Specifies the initial target location so that it can learn its description | 243 | 13 |
27,332 | public boolean process ( T image ) { if ( failed ) return false ; targetModel . setImage ( image ) ; // mark the region where the pdf has been modified as dirty dirty . set ( location . x0 , location . y0 , location . x0 + location . width , location . y0 + location . height ) ; // compute the pdf inside the initial rectangle updatePdfImage ( location . x0 , location . y0 , location . x0 + location . width , location . y0 + location . height ) ; // current location of the target int x0 = location . x0 ; int y0 = location . y0 ; // previous location of the target in the most recent iteration int prevX = x0 ; int prevY = y0 ; // iterate until it converges or reaches the maximum number of iterations for ( int i = 0 ; i < maxIterations ; i ++ ) { // compute the weighted centroid using the likelihood function float totalPdf = 0 ; float sumX = 0 ; float sumY = 0 ; for ( int y = 0 ; y < location . height ; y ++ ) { int indexPdf = pdf . startIndex + pdf . stride * ( y + y0 ) + x0 ; for ( int x = 0 ; x < location . width ; x ++ ) { float p = pdf . data [ indexPdf ++ ] ; totalPdf += p ; sumX += ( x0 + x ) * p ; sumY += ( y0 + y ) * p ; } } // if the target isn't likely to be in view, give up if ( totalPdf <= minimumSum ) { failed = true ; return false ; } // Use the new center to find the new top left corner, while rounding to the nearest integer x0 = ( int ) ( sumX / totalPdf - location . width / 2 + 0.5f ) ; y0 = ( int ) ( sumY / totalPdf - location . height / 2 + 0.5f ) ; // make sure it doesn't go outside the image if ( x0 < 0 ) x0 = 0 ; else if ( x0 >= image . width - location . width ) x0 = image . width - location . width ; if ( y0 < 0 ) y0 = 0 ; else if ( y0 >= image . height - location . height ) y0 = image . height - location . height ; // see if it has converged if ( x0 == prevX && y0 == prevY ) break ; // save the previous location prevX = x0 ; prevY = y0 ; // update the pdf updatePdfImage ( x0 , y0 , x0 + location . width , y0 + location . height ) ; } // update the output location . x0 = x0 ; location . y0 = y0 ; // clean up the image for the next iteration ImageMiscOps . fillRectangle ( pdf , - 1 , dirty . x0 , dirty . y0 , dirty . x1 - dirty . x0 , dirty . y1 - dirty . y0 ) ; return true ; } | Updates the target s location in the image by performing a mean - shift search . Returns if it was successful at finding the target or not . If it fails once it will need to be re - initialized | 659 | 41 |
27,333 | protected void updatePdfImage ( int x0 , int y0 , int x1 , int y1 ) { for ( int y = y0 ; y < y1 ; y ++ ) { int indexOut = pdf . startIndex + pdf . stride * y + x0 ; for ( int x = x0 ; x < x1 ; x ++ , indexOut ++ ) { if ( pdf . data [ indexOut ] < 0 ) pdf . data [ indexOut ] = targetModel . compute ( x , y ) ; } } // update the dirty region if ( dirty . x0 > x0 ) dirty . x0 = x0 ; if ( dirty . y0 > y0 ) dirty . y0 = y0 ; if ( dirty . x1 < x1 ) dirty . x1 = x1 ; if ( dirty . y1 < y1 ) dirty . y1 = y1 ; } | Computes the PDF only inside the image as needed amd update the dirty rectangle | 190 | 15 |
27,334 | @ Override public void process ( T image ) { // initialize data structures this . image = image ; this . stopRequested = false ; modeLocation . reset ( ) ; modeColor . reset ( ) ; modeMemberCount . reset ( ) ; interpolate . setImage ( image ) ; pixelToMode . reshape ( image . width , image . height ) ; quickMode . reshape ( image . width , image . height ) ; // mark as -1 so it knows which pixels have been assigned a mode already and can skip them ImageMiscOps . fill ( pixelToMode , - 1 ) ; // mark all pixels are not being a mode ImageMiscOps . fill ( quickMode , - 1 ) ; // use mean shift to find the peak of each pixel in the image int indexImg = 0 ; for ( int y = 0 ; y < image . height && ! stopRequested ; y ++ ) { for ( int x = 0 ; x < image . width ; x ++ , indexImg ++ ) { if ( pixelToMode . data [ indexImg ] != - 1 ) { int peakIndex = pixelToMode . data [ indexImg ] ; modeMemberCount . data [ peakIndex ] ++ ; continue ; } float meanColor = interpolate . get ( x , y ) ; findPeak ( x , y , meanColor ) ; // convert mean-shift location into pixel index int modeX = ( int ) ( this . modeX + 0.5f ) ; int modeY = ( int ) ( this . modeY + 0.5f ) ; int modePixelIndex = modeY * image . width + modeX ; // get index in the list of peaks int modeIndex = quickMode . data [ modePixelIndex ] ; // If the mode is new add it to the list if ( modeIndex < 0 ) { modeIndex = this . modeLocation . size ( ) ; this . modeLocation . grow ( ) . set ( modeX , modeY ) ; // Save the peak's color modeColor . grow ( ) [ 0 ] = meanGray ; // Mark the mode in the segment image quickMode . data [ modePixelIndex ] = modeIndex ; // Set the initial count to zero. This will be incremented when it is traversed later on modeMemberCount . add ( 0 ) ; } // add this pixel to the membership list modeMemberCount . data [ modeIndex ] ++ ; // Add all pixels it traversed through to the membership of this mode // This is an approximate of mean-shift for ( int i = 0 ; i < history . size ; i ++ ) { Point2D_F32 p = history . get ( i ) ; int px = ( int ) ( p . x + 0.5f ) ; int py = ( int ) ( p . y + 0.5f ) ; int index = pixelToMode . getIndex ( px , py ) ; if ( pixelToMode . data [ index ] == - 1 ) { pixelToMode . data [ index ] = modeIndex ; } } } } } | Performs mean - shift clustering on the input image | 646 | 11 |
27,335 | public void set ( Point2D3D src ) { observation . set ( src . observation ) ; location . set ( src . location ) ; } | Sets this to be identical to src . | 31 | 9 |
27,336 | public void clearLensDistortion ( ) { detector . clearLensDistortion ( ) ; if ( refineGray != null ) refineGray . clearLensDistortion ( ) ; edgeIntensity . setTransform ( null ) ; } | Discard previously set lens distortion models | 46 | 7 |
27,337 | public void process ( T gray , GrayU8 binary ) { detector . process ( gray , binary ) ; if ( refineGray != null ) refineGray . setImage ( gray ) ; edgeIntensity . setImage ( gray ) ; long time0 = System . nanoTime ( ) ; FastQueue < DetectPolygonFromContour . Info > detections = detector . getFound ( ) ; if ( adjustForBias != null ) { int minSides = getMinimumSides ( ) ; for ( int i = detections . size ( ) - 1 ; i >= 0 ; i -- ) { Polygon2D_F64 p = detections . get ( i ) . polygon ; adjustForBias . process ( p , detector . isOutputClockwise ( ) ) ; // When the polygon is adjusted for bias a point might need to be removed because it's // almost parallel. This could cause the shape to have too few corners and needs to be removed. if ( p . size ( ) < minSides ) detections . remove ( i ) ; } } long time1 = System . nanoTime ( ) ; double milli = ( time1 - time0 ) * 1e-6 ; milliAdjustBias . update ( milli ) ; // System.out.printf(" contour %7.2f shapes %7.2f adjust_bias %7.2f\n", // detector.getMilliShapes(),detector.getMilliShapes(),milliAdjustBias); } | Detects polygons inside the grayscale image and its thresholded version | 322 | 15 |
27,338 | public boolean refine ( DetectPolygonFromContour . Info info ) { double before , after ; if ( edgeIntensity . computeEdge ( info . polygon , ! detector . isOutputClockwise ( ) ) ) { before = edgeIntensity . getAverageOutside ( ) - edgeIntensity . getAverageInside ( ) ; } else { return false ; } boolean success = false ; if ( refineContour != null ) { List < Point2D_I32 > contour = detector . getContour ( info ) ; refineContour . process ( contour , info . splits , work ) ; if ( adjustForBias != null ) adjustForBias . process ( work , detector . isOutputClockwise ( ) ) ; if ( edgeIntensity . computeEdge ( work , ! detector . isOutputClockwise ( ) ) ) { after = edgeIntensity . getAverageOutside ( ) - edgeIntensity . getAverageInside ( ) ; if ( after > before ) { info . edgeInside = edgeIntensity . getAverageInside ( ) ; info . edgeOutside = edgeIntensity . getAverageOutside ( ) ; info . polygon . set ( work ) ; success = true ; before = after ; } } } if ( functionAdjust != null ) { functionAdjust . adjust ( info , detector . isOutputClockwise ( ) ) ; } if ( refineGray != null ) { work . vertexes . resize ( info . polygon . size ( ) ) ; if ( refineGray . refine ( info . polygon , work ) ) { if ( edgeIntensity . computeEdge ( work , ! detector . isOutputClockwise ( ) ) ) { after = edgeIntensity . getAverageOutside ( ) - edgeIntensity . getAverageInside ( ) ; // basically, unless it diverged stick with this optimization // a near tie if ( after * 1.5 > before ) { info . edgeInside = edgeIntensity . getAverageInside ( ) ; info . edgeOutside = edgeIntensity . getAverageOutside ( ) ; info . polygon . set ( work ) ; success = true ; } } } } return success ; } | Refines the fit to the specified polygon . Only info . polygon is modified | 447 | 17 |
27,339 | public void refineAll ( ) { List < DetectPolygonFromContour . Info > detections = detector . getFound ( ) . toList ( ) ; for ( int i = 0 ; i < detections . size ( ) ; i ++ ) { refine ( detections . get ( i ) ) ; } } | Refines all the detected polygons and places them into the provided list . Polygons which fail the refinement step are not added . | 66 | 27 |
27,340 | public static < T extends ImageGray < T > > T checkReshape ( T target , ImageGray testImage , Class < T > targetType ) { if ( target == null ) { return GeneralizedImageOps . createSingleBand ( targetType , testImage . width , testImage . height ) ; } else if ( target . width != testImage . width || target . height != testImage . height ) { target . reshape ( testImage . width , testImage . height ) ; } return target ; } | Checks to see if the target image is null or if it is a different size than the test image . If it is null then a new image is returned otherwise target is reshaped and returned . | 108 | 40 |
27,341 | protected void findLocalScaleSpaceMax ( PyramidFloat < T > ss , int layerID ) { int index0 = spaceIndex ; int index1 = ( spaceIndex + 1 ) % 3 ; int index2 = ( spaceIndex + 2 ) % 3 ; List < Point2D_I16 > candidates = maximums [ index1 ] ; ImageBorder_F32 inten0 = ( ImageBorder_F32 ) FactoryImageBorderAlgs . value ( intensities [ index0 ] , 0 ) ; GrayF32 inten1 = intensities [ index1 ] ; ImageBorder_F32 inten2 = ( ImageBorder_F32 ) FactoryImageBorderAlgs . value ( intensities [ index2 ] , 0 ) ; float scale0 = ( float ) ss . scale [ layerID - 1 ] ; float scale1 = ( float ) ss . scale [ layerID ] ; float scale2 = ( float ) ss . scale [ layerID + 1 ] ; float sigma0 = ( float ) ss . getSigma ( layerID - 1 ) ; float sigma1 = ( float ) ss . getSigma ( layerID ) ; float sigma2 = ( float ) ss . getSigma ( layerID + 1 ) ; // not sure if this is the correct way to handle the change in scale float ss0 = ( float ) ( Math . pow ( sigma0 , scalePower ) / scale0 ) ; float ss1 = ( float ) ( Math . pow ( sigma1 , scalePower ) / scale1 ) ; float ss2 = ( float ) ( Math . pow ( sigma2 , scalePower ) / scale2 ) ; for ( Point2D_I16 c : candidates ) { float val = ss1 * inten1 . get ( c . x , c . y ) ; // find pixel location in each image's local coordinate int x0 = ( int ) ( c . x * scale1 / scale0 ) ; int y0 = ( int ) ( c . y * scale1 / scale0 ) ; int x2 = ( int ) ( c . x * scale1 / scale2 ) ; int y2 = ( int ) ( c . y * scale1 / scale2 ) ; if ( checkMax ( inten0 , val / ss0 , x0 , y0 ) && checkMax ( inten2 , val / ss2 , x2 , y2 ) ) { // put features into the scale of the upper image foundPoints . add ( new ScalePoint ( c . x * scale1 , c . y * scale1 , sigma1 ) ) ; } } } | Searches the pyramid layers up and down to see if the found 2D features are also scale space maximums . | 550 | 24 |
27,342 | int getCornerIndex ( SquareNode node , double x , double y ) { for ( int i = 0 ; i < node . square . size ( ) ; i ++ ) { Point2D_F64 c = node . square . get ( i ) ; if ( c . x == x && c . y == y ) return i ; } throw new RuntimeException ( "BUG!" ) ; } | Returns the corner index of the specified coordinate | 84 | 8 |
27,343 | boolean candidateIsMuchCloser ( SquareNode node0 , SquareNode node1 , double distance2 ) { double length = Math . max ( node0 . largestSide , node1 . largestSide ) * tooFarFraction ; length *= length ; if ( distance2 > length ) return false ; return distance2 <= length ; } | Checks to see if the two corners which are to be connected are by far the two closest corners between the two squares | 70 | 24 |
27,344 | private void handleContextMenu ( JTree tree , int x , int y ) { TreePath path = tree . getPathForLocation ( x , y ) ; tree . setSelectionPath ( path ) ; DefaultMutableTreeNode node = ( DefaultMutableTreeNode ) tree . getLastSelectedPathComponent ( ) ; if ( node == null ) return ; if ( ! node . isLeaf ( ) ) { tree . setSelectionPath ( null ) ; return ; } final AppInfo info = ( AppInfo ) node . getUserObject ( ) ; JMenuItem copyname = new JMenuItem ( "Copy Name" ) ; copyname . addActionListener ( e -> { Clipboard clipboard = Toolkit . getDefaultToolkit ( ) . getSystemClipboard ( ) ; clipboard . setContents ( new StringSelection ( info . app . getSimpleName ( ) ) , null ) ; } ) ; JMenuItem copypath = new JMenuItem ( "Copy Path" ) ; copypath . addActionListener ( e -> { String path1 = UtilIO . getSourcePath ( info . app . getPackage ( ) . getName ( ) , info . app . getSimpleName ( ) ) ; Clipboard clipboard = Toolkit . getDefaultToolkit ( ) . getSystemClipboard ( ) ; clipboard . setContents ( new StringSelection ( path1 ) , null ) ; } ) ; JMenuItem github = new JMenuItem ( "Go to Github" ) ; github . addActionListener ( e -> openInGitHub ( info ) ) ; JPopupMenu submenu = new JPopupMenu ( ) ; submenu . add ( copyname ) ; submenu . add ( copypath ) ; submenu . add ( github ) ; submenu . show ( tree , x , y ) ; } | Displays a context menu for a class leaf node Allows copying of the name and the path to the source | 395 | 21 |
27,345 | private void openInGitHub ( AppInfo info ) { if ( Desktop . isDesktopSupported ( ) ) { try { URI uri = new URI ( UtilIO . getGithubURL ( info . app . getPackage ( ) . getName ( ) , info . app . getSimpleName ( ) ) ) ; if ( ! uri . getPath ( ) . isEmpty ( ) ) Desktop . getDesktop ( ) . browse ( uri ) ; else System . err . println ( "Bad URL received" ) ; } catch ( Exception e1 ) { JOptionPane . showMessageDialog ( this , "Open GitHub Error" , "Error connecting: " + e1 . getMessage ( ) , JOptionPane . ERROR_MESSAGE ) ; System . err . println ( e1 . getMessage ( ) ) ; } } } | Opens github page of source code up in a browser window | 181 | 12 |
27,346 | public void killAllProcesses ( long blockTimeMS ) { // remove already dead processes from the GUI SwingUtilities . invokeLater ( new Runnable ( ) { @ Override public void run ( ) { DefaultListModel model = ( DefaultListModel ) processList . getModel ( ) ; for ( int i = model . size ( ) - 1 ; i >= 0 ; i -- ) { ActiveProcess p = ( ActiveProcess ) model . get ( i ) ; removeProcessTab ( p , false ) ; } } } ) ; // kill processes that are already running synchronized ( processes ) { for ( int i = 0 ; i < processes . size ( ) ; i ++ ) { processes . get ( i ) . requestKill ( ) ; } } // block until everything is dead if ( blockTimeMS > 0 ) { long abortTime = System . currentTimeMillis ( ) + blockTimeMS ; while ( abortTime > System . currentTimeMillis ( ) ) { int total = 0 ; synchronized ( processes ) { for ( int i = 0 ; i < processes . size ( ) ; i ++ ) { if ( ! processes . get ( i ) . isActive ( ) ) { total ++ ; } } if ( processes . size ( ) == total ) { break ; } } } } } | Requests that all active processes be killed . | 272 | 9 |
27,347 | @ Override public void intervalAdded ( ListDataEvent e ) { //retrieve the most recently added process and display it DefaultListModel listModel = ( DefaultListModel ) e . getSource ( ) ; ActiveProcess process = ( ActiveProcess ) listModel . get ( listModel . getSize ( ) - 1 ) ; addProcessTab ( process , outputPanel ) ; } | Called after a new process is added to the process list | 78 | 12 |
27,348 | protected void setUpEdges ( GrayS32 input , GrayS32 output ) { if ( connectRule == ConnectRule . EIGHT ) { setUpEdges8 ( input , edgesIn ) ; setUpEdges8 ( output , edgesOut ) ; edges [ 0 ] . set ( 1 , 0 ) ; edges [ 1 ] . set ( 1 , 1 ) ; edges [ 2 ] . set ( 0 , 1 ) ; edges [ 3 ] . set ( - 1 , 0 ) ; } else { setUpEdges4 ( input , edgesIn ) ; setUpEdges4 ( output , edgesOut ) ; edges [ 0 ] . set ( 1 , 0 ) ; edges [ 1 ] . set ( 0 , 1 ) ; } } | Declares lookup tables for neighbors | 156 | 6 |
27,349 | public void process ( GrayS32 input , GrayS32 output , GrowQueue_I32 regionMemberCount ) { // initialize data structures this . regionMemberCount = regionMemberCount ; regionMemberCount . reset ( ) ; setUpEdges ( input , output ) ; ImageMiscOps . fill ( output , - 1 ) ; // this is a bit of a hack here. Normally you call the parent's init function. // since the number of regions is not initially known this will grow mergeList . reset ( ) ; connectInner ( input , output ) ; connectLeftRight ( input , output ) ; connectBottom ( input , output ) ; // Merge together all the regions that are connected in the output image performMerge ( output , regionMemberCount ) ; } | Relabels the image such that all pixels with the same label are a member of the same graph . | 159 | 21 |
27,350 | protected void connectInner ( GrayS32 input , GrayS32 output ) { int startX = connectRule == ConnectRule . EIGHT ? 1 : 0 ; for ( int y = 0 ; y < input . height - 1 ; y ++ ) { int indexIn = input . startIndex + y * input . stride + startX ; int indexOut = output . startIndex + y * output . stride + startX ; for ( int x = startX ; x < input . width - 1 ; x ++ , indexIn ++ , indexOut ++ ) { int inputLabel = input . data [ indexIn ] ; int outputLabel = output . data [ indexOut ] ; if ( outputLabel == - 1 ) { // see if it needs to create a new output segment output . data [ indexOut ] = outputLabel = regionMemberCount . size ; regionMemberCount . add ( 1 ) ; mergeList . add ( outputLabel ) ; } for ( int i = 0 ; i < edgesIn . length ; i ++ ) { if ( inputLabel == input . data [ indexIn + edgesIn [ i ] ] ) { int outputAdj = output . data [ indexOut + edgesOut [ i ] ] ; if ( outputAdj == - 1 ) { // see if not assigned regionMemberCount . data [ outputLabel ] ++ ; output . data [ indexOut + edgesOut [ i ] ] = outputLabel ; } else if ( outputLabel != outputAdj ) { // see if assigned to different regions markMerge ( outputLabel , outputAdj ) ; } // do nothing, same input and output labels } } } } } | Examines pixels inside the image without the need for bounds checking | 343 | 12 |
27,351 | protected void connectLeftRight ( GrayS32 input , GrayS32 output ) { for ( int y = 0 ; y < input . height ; y ++ ) { int x = input . width - 1 ; int inputLabel = input . unsafe_get ( x , y ) ; int outputLabel = output . unsafe_get ( x , y ) ; if ( outputLabel == - 1 ) { // see if it needs to create a new output segment outputLabel = regionMemberCount . size ; output . unsafe_set ( x , y , outputLabel ) ; regionMemberCount . add ( 1 ) ; mergeList . add ( outputLabel ) ; } // check right first for ( int i = 0 ; i < edges . length ; i ++ ) { Point2D_I32 offset = edges [ i ] ; // make sure it is inside the image if ( ! input . isInBounds ( x + offset . x , y + offset . y ) ) continue ; if ( inputLabel == input . unsafe_get ( x + offset . x , y + offset . y ) ) { int outputAdj = output . unsafe_get ( x + offset . x , y + offset . y ) ; if ( outputAdj == - 1 ) { // see if not assigned regionMemberCount . data [ outputLabel ] ++ ; output . unsafe_set ( x + offset . x , y + offset . y , outputLabel ) ; } else if ( outputLabel != outputAdj ) { // see if assigned to different regions markMerge ( outputLabel , outputAdj ) ; } // do nothing, same input and output labels } } // skip check of left of 4-connect if ( connectRule != ConnectRule . EIGHT ) continue ; x = 0 ; inputLabel = input . unsafe_get ( x , y ) ; outputLabel = output . unsafe_get ( x , y ) ; if ( outputLabel == - 1 ) { // see if it needs to create a new output segment outputLabel = regionMemberCount . size ; output . unsafe_set ( x , y , outputLabel ) ; regionMemberCount . add ( 1 ) ; mergeList . add ( outputLabel ) ; } for ( int i = 0 ; i < edges . length ; i ++ ) { Point2D_I32 offset = edges [ i ] ; // make sure it is inside the image if ( ! input . isInBounds ( x + offset . x , y + offset . y ) ) continue ; if ( inputLabel == input . unsafe_get ( x + offset . x , y + offset . y ) ) { int outputAdj = output . unsafe_get ( x + offset . x , y + offset . y ) ; if ( outputAdj == - 1 ) { // see if not assigned regionMemberCount . data [ outputLabel ] ++ ; output . unsafe_set ( x + offset . x , y + offset . y , outputLabel ) ; } else if ( outputLabel != outputAdj ) { // see if assigned to different regions markMerge ( outputLabel , outputAdj ) ; } // do nothing, same input and output labels } } } } | Examines pixels along the left and right border | 663 | 9 |
27,352 | protected void connectBottom ( GrayS32 input , GrayS32 output ) { for ( int x = 0 ; x < input . width - 1 ; x ++ ) { int y = input . height - 1 ; int inputLabel = input . unsafe_get ( x , y ) ; int outputLabel = output . unsafe_get ( x , y ) ; if ( outputLabel == - 1 ) { // see if it needs to create a new output segment outputLabel = regionMemberCount . size ; output . unsafe_set ( x , y , outputLabel ) ; regionMemberCount . add ( 1 ) ; mergeList . add ( outputLabel ) ; } // for 4 and 8 connect the check is only +1 x and 0 y if ( inputLabel == input . unsafe_get ( x + 1 , y ) ) { int outputAdj = output . unsafe_get ( x + 1 , y ) ; if ( outputAdj == - 1 ) { // see if not assigned regionMemberCount . data [ outputLabel ] ++ ; output . unsafe_set ( x + 1 , y , outputLabel ) ; } else if ( outputLabel != outputAdj ) { // see if assigned to different regions markMerge ( outputLabel , outputAdj ) ; } // do nothing, same input and output labels } } } | Examines pixels along the bottom border | 275 | 7 |
27,353 | public void setImage ( I image , D derivX , D derivY ) { InputSanityCheck . checkSameShape ( image , derivX , derivY ) ; this . image = image ; this . interpInput . setImage ( image ) ; this . derivX = derivX ; this . derivY = derivY ; } | Sets the current image it should be tracking with . | 70 | 11 |
27,354 | @ SuppressWarnings ( { "SuspiciousNameCombination" } ) public boolean setDescription ( KltFeature feature ) { setAllowedBounds ( feature ) ; if ( ! isFullyInside ( feature . x , feature . y ) ) { if ( isFullyOutside ( feature . x , feature . y ) ) return false ; else return internalSetDescriptionBorder ( feature ) ; } return internalSetDescription ( feature ) ; } | Sets the features description using the current image and the location of the feature stored in the feature . If the feature is an illegal location and cannot be set then false is returned . | 95 | 36 |
27,355 | protected boolean internalSetDescriptionBorder ( KltFeature feature ) { computeSubImageBounds ( feature , feature . x , feature . y ) ; ImageMiscOps . fill ( feature . desc , Float . NaN ) ; feature . desc . subimage ( dstX0 , dstY0 , dstX1 , dstY1 , subimage ) ; interpInput . setImage ( image ) ; interpInput . region ( srcX0 , srcY0 , subimage ) ; feature . derivX . subimage ( dstX0 , dstY0 , dstX1 , dstY1 , subimage ) ; interpDeriv . setImage ( derivX ) ; interpDeriv . region ( srcX0 , srcY0 , subimage ) ; feature . derivY . subimage ( dstX0 , dstY0 , dstX1 , dstY1 , subimage ) ; interpDeriv . setImage ( derivY ) ; interpDeriv . region ( srcX0 , srcY0 , subimage ) ; int total = 0 ; Gxx = Gyy = Gxy = 0 ; for ( int i = 0 ; i < lengthFeature ; i ++ ) { if ( Float . isNaN ( feature . desc . data [ i ] ) ) continue ; total ++ ; float dX = feature . derivX . data [ i ] ; float dY = feature . derivY . data [ i ] ; Gxx += dX * dX ; Gyy += dY * dY ; Gxy += dX * dY ; } // technically don't need to save this... feature . Gxx = Gxx ; feature . Gyy = Gyy ; feature . Gxy = Gxy ; float det = Gxx * Gyy - Gxy * Gxy ; return ( det >= config . minDeterminant * total ) ; } | Computes the descriptor for border features . All it needs to do is save the pixel value but derivative information is also computed so that it can reject bad features immediately . | 394 | 33 |
27,356 | protected void setAllowedBounds ( KltFeature feature ) { // compute the feature's width and temporary storage related to it 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 | 129 | 12 |
27,357 | 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 the description was outside of the image here skip it if ( Float . isNaN ( template ) || Float . isNaN ( current ) ) continue ; // count total number of points inbounds total ++ ; float dX = feature . derivX . data [ i ] ; float dY = feature . derivY . data [ i ] ; // compute the difference between the previous and the current image 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 | 312 | 18 |
27,358 | 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 | 54 | 22 |
27,359 | 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 . | 48 | 13 |
27,360 | 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 ... | 48 | 55 |
27,361 | 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 | 132 | 15 |
27,362 | 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 . | 136 | 12 |
27,363 | public void configure ( int width , int height , int gridRows , int gridCols ) { // need to maintain the same ratio of pixels in the grid as in the regular image for similarity and rigid // to work correctly 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 | 189 | 26 |
27,364 | 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 | 60 | 24 |
27,365 | 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 . | 67 | 9 |
27,366 | 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 | 52 | 16 |
27,367 | 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 | 33 | 10 |
27,368 | 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 . | 179 | 34 |
27,369 | 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 | 132 | 12 |
27,370 | 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 | 132 | 12 |
27,371 | void interpolateDeformedPoint ( float v_x , float v_y , Point2D_F32 deformed ) { // sample the closest point and x+1,y+1 int x0 = ( int ) v_x ; int y0 = ( int ) v_y ; int x1 = x0 + 1 ; int y1 = y0 + 1 ; // make sure the 4 sample points are in bounds if ( x1 >= gridCols ) x1 = gridCols - 1 ; if ( y1 >= gridRows ) y1 = gridRows - 1 ; // weight along each axis float ax = v_x - x0 ; float ay = v_y - y0 ; // bilinear weight for each sample point float w00 = ( 1.0f - ax ) * ( 1.0f - ay ) ; float w01 = ax * ( 1.0f - ay ) ; float w11 = ax * ay ; float w10 = ( 1.0f - ax ) * ay ; // apply weights to each sample point 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 | 430 | 15 |
27,372 | 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 . | 95 | 9 |
27,373 | 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 | 91 | 7 |
27,374 | @ Override public boolean process ( double x , double y ) { leftPixelToRect . compute ( x , y , pixelRect ) ; // round to the nearest pixel if ( ! disparity . process ( ( int ) ( pixelRect . x + 0.5 ) , ( int ) ( pixelRect . y + 0.5 ) ) ) return false ; // Compute coordinate in camera frame 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 | 118 | 15 |
27,375 | 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 | 54 | 14 |
27,376 | 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 ; } } // bug but I won't throw an exception to stop it from blowing up a bunch 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 | 138 | 33 |
27,377 | 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 . | 141 | 53 |
27,378 | 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 . | 96 | 26 |
27,379 | public boolean almostParallel ( SquareNode a , int sideA , SquareNode b , int sideB ) { double selected = acuteAngle ( a , sideA , b , sideB ) ; if ( selected > parallelThreshold ) return false ; // see if the two sides are about parallel too // double left = acuteAngle(a,add(sideA,-1),b,add(sideB,1)); // double right = acuteAngle(a,add(sideA,1),b,add(sideB,-1)); // // if( left > selected+parallelThreshold || right > selected+parallelThreshold ) // return false; // if( selected > acuteAngle(a,sideA,b,add(sideB,1)) || selected > acuteAngle(a,sideA,b,add(sideB,-1)) ) // return false; // // if( selected > acuteAngle(a,add(sideA,1),b,sideB) || selected > acuteAngle(a,add(sideA,-1),b,sideB) ) // return false; return true ; } | Checks to see if the two sides are almost parallel to each other by looking at their acute angle . | 243 | 21 |
27,380 | public void setImageGradient ( Deriv derivX , Deriv derivY ) { this . derivX . wrap ( derivX ) ; this . derivY . wrap ( derivY ) ; } | Specify the input image | 41 | 5 |
27,381 | void computeHistogram ( int c_x , int c_y , double sigma ) { int r = ( int ) Math . ceil ( sigma * sigmaEnlarge ) ; // specify the area being sampled 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 ( ) ; // make sure it is contained in the image bounds BoofMiscOps . boundRectangleInside ( rawDX , bound ) ; // clear the histogram Arrays . fill ( histogramMag , 0 ) ; Arrays . fill ( histogramX , 0 ) ; Arrays . fill ( histogramY , 0 ) ; // construct the histogram for ( int y = bound . y0 ; y < bound . y1 ; y ++ ) { // iterate through the raw array for speed 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 ++ ) ; // edge intensity and angle double magnitude = Math . sqrt ( dx * dx + dy * dy ) ; double theta = UtilAngle . domain2PI ( Math . atan2 ( dy , dx ) ) ; // weight from gaussian double weight = computeWeight ( x - c_x , y - c_y , sigma ) ; // histogram index int h = ( int ) ( theta / histAngleBin ) % histogramMag . length ; // update the histogram histogramMag [ h ] += magnitude * weight ; histogramX [ h ] += dx * weight ; histogramY [ h ] += dy * weight ; } } } | Constructs the histogram around the specified point . | 462 | 10 |
27,382 | void findHistogramPeaks ( ) { // reset data structures peaks . reset ( ) ; angles . reset ( ) ; peakAngle = 0 ; // identify peaks and find the highest peak 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 ; // see if any of the other peaks are within 80% of the max peak 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 . | 292 | 19 |
27,383 | double computeAngle ( int index1 ) { int index0 = CircularIndex . addOffset ( index1 , - 1 , histogramMag . length ) ; int index2 = CircularIndex . addOffset ( index1 , 1 , histogramMag . length ) ; // compute the peak location using a second order polygon double v0 = histogramMag [ index0 ] ; double v1 = histogramMag [ index1 ] ; double v2 = histogramMag [ index2 ] ; double offset = FastHessianFeatureDetector . polyPeak ( v0 , v1 , v2 ) ; // interpolate using the index offset and angle of its neighbor 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 . | 160 | 52 |
27,384 | 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 . | 174 | 26 |
27,385 | double computeWeight ( double deltaX , double deltaY , double sigma ) { // the exact equation // return Math.exp(-0.5 * ((deltaX * deltaX + deltaY * deltaY) / (sigma * sigma))); // approximation below. when validating this approach it produced results that were within // floating point tolerance of the exact solution, but much faster 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 | 137 | 23 |
27,386 | @ Override 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 . | 65 | 38 |
27,387 | @ Override protected void renderBitmapImage ( BitmapMode mode , ImageBase image ) { switch ( mode ) { case UNSAFE : { // this application is configured to use double buffer and could ignore all other modes 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 . | 167 | 14 |
27,388 | 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 ; } } // check on a per row basis to reduce impact on performance if ( candidatesLow . size + candidatesHigh . size >= maxFeatures ) break ; } } | Computes fast corner features and their intensity . The intensity is needed if non - max suppression is used | 309 | 20 |
27,389 | 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 | 123 | 15 |
27,390 | 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 | 102 | 16 |
27,391 | 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 | 94 | 18 |
27,392 | public static boolean isImage ( File file ) { try { String mimeType = Files . probeContentType ( file . toPath ( ) ) ; if ( mimeType == null ) { // In some OS there is a bug where it always returns 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 . | 153 | 33 |
27,393 | 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 . | 378 | 6 |
27,394 | 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 | 90 | 25 |
27,395 | 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." ) ; } } // set width/height to zero to force the image to be redeclared bottomWidth = bottomHeight = 0 ; this . scale = scaleFactors . clone ( ) ; checkScales ( ) ; } | Specifies the pyramid s structure . Scale factors are in relative to the input image . | 125 | 17 |
27,396 | 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 ) ; // remove reference so that it can be freed this . contour = null ; vertexes . setTo ( splits ) ; return result ; } | Approximates the input list with a set of line segments | 97 | 12 |
27,397 | 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 | 48 | 12 |
27,398 | @ SuppressWarnings ( { "SuspiciousSystemArraycopy" } ) @ Override 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 . | 210 | 20 |
27,399 | 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 . | 100 | 11 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.