idx int64 0 165k | question stringlengths 73 4.15k | target stringlengths 5 918 | len_question int64 21 890 | len_target int64 3 255 |
|---|---|---|---|---|
26,600 | boolean removeCornerAndSavePolyline ( Element < Corner > corner , double sideErrorAfterRemoved ) { // System.out.println("removing a corner idx="+target.object.index); // Note: the corner is "lost" until the next contour is fit. Not worth the effort to recycle Element < Corner > p = previous ( corner ) ; // go through the hassle of passing in this value instead of recomputing it // since recomputing it isn't trivial p . object . sideError = sideErrorAfterRemoved ; list . remove ( corner ) ; // the line below is commented out because right now the current algorithm will // never grow after removing a corner. If this changes in the future uncomment it // computePotentialSplitScore(contour,p); return savePolyline ( ) ; } | Remove the corner from the current polyline . If the new polyline has a better score than the currently saved one with the same number of corners save it | 173 | 31 |
26,601 | static int findCornerSeed ( List < Point2D_I32 > contour ) { Point2D_I32 a = contour . get ( 0 ) ; int best = - 1 ; double bestDistance = - Double . MAX_VALUE ; for ( int i = 1 ; i < contour . size ( ) ; i ++ ) { Point2D_I32 b = contour . get ( i ) ; double d = distanceSq ( a , b ) ; if ( d > bestDistance ) { bestDistance = d ; best = i ; } } return best ; } | The seed corner is the point farther away from the first point . In a perfect polygon with no noise this should be a corner . | 125 | 27 |
26,602 | static int maximumDistance ( List < Point2D_I32 > contour , int indexA , int indexB ) { Point2D_I32 a = contour . get ( indexA ) ; Point2D_I32 b = contour . get ( indexB ) ; int best = - 1 ; double bestDistance = - Double . MAX_VALUE ; for ( int i = 0 ; i < contour . size ( ) ; i ++ ) { Point2D_I32 c = contour . get ( i ) ; // can't sum sq distance because some skinny shapes it maximizes one and not the other // double d = Math.sqrt(distanceSq(a,c)) + Math.sqrt(distanceSq(b,c)); double d = distanceAbs ( a , c ) + distanceAbs ( b , c ) ; if ( d > bestDistance ) { bestDistance = d ; best = i ; } } return best ; } | Finds the point in the contour which maximizes the distance between points A and B . | 204 | 19 |
26,603 | double computeSideError ( List < Point2D_I32 > contour , int indexA , int indexB ) { assignLine ( contour , indexA , indexB , line ) ; // don't sample the end points because the error will be zero by definition int numSamples ; double sumOfDistances = 0 ; int length ; if ( indexB >= indexA ) { length = indexB - indexA - 1 ; numSamples = Math . min ( length , maxNumberOfSideSamples ) ; for ( int i = 0 ; i < numSamples ; i ++ ) { int index = indexA + 1 + length * i / numSamples ; Point2D_I32 p = contour . get ( index ) ; sumOfDistances += Distance2D_F64 . distanceSq ( line , p . x , p . y ) ; } sumOfDistances /= numSamples ; } else { length = contour . size ( ) - indexA - 1 + indexB ; numSamples = Math . min ( length , maxNumberOfSideSamples ) ; for ( int i = 0 ; i < numSamples ; i ++ ) { int where = length * i / numSamples ; int index = ( indexA + 1 + where ) % contour . size ( ) ; Point2D_I32 p = contour . get ( index ) ; sumOfDistances += Distance2D_F64 . distanceSq ( line , p . x , p . y ) ; } sumOfDistances /= numSamples ; } // handle divide by zero error if ( numSamples > 0 ) return sumOfDistances ; else return 0 ; } | Scores a side based on the sum of Euclidean distance squared of each point along the line . Euclidean squared is used because its fast to compute | 361 | 32 |
26,604 | void computePotentialSplitScore ( List < Point2D_I32 > contour , Element < Corner > e0 , boolean mustSplit ) { Element < Corner > e1 = next ( e0 ) ; e0 . object . splitable = canBeSplit ( contour , e0 , mustSplit ) ; if ( e0 . object . splitable ) { setSplitVariables ( contour , e0 , e1 ) ; } } | Computes the split location and the score of the two new sides if it s split there | 94 | 18 |
26,605 | void setSplitVariables ( List < Point2D_I32 > contour , Element < Corner > e0 , Element < Corner > e1 ) { int distance0 = CircularIndex . distanceP ( e0 . object . index , e1 . object . index , contour . size ( ) ) ; int index0 = CircularIndex . plusPOffset ( e0 . object . index , minimumSideLength , contour . size ( ) ) ; int index1 = CircularIndex . minusPOffset ( e1 . object . index , minimumSideLength , contour . size ( ) ) ; splitter . selectSplitPoint ( contour , index0 , index1 , resultsA ) ; // if convex only perform the split if it would result in a convex polygon if ( convex ) { Point2D_I32 a = contour . get ( e0 . object . index ) ; Point2D_I32 b = contour . get ( resultsA . index ) ; Point2D_I32 c = contour . get ( next ( e0 ) . object . index ) ; if ( UtilPolygons2D_I32 . isPositiveZ ( a , b , c ) ) { e0 . object . splitable = false ; return ; } } // see if this would result in a side that's too small int dist0 = CircularIndex . distanceP ( e0 . object . index , resultsA . index , contour . size ( ) ) ; if ( dist0 < minimumSideLength || ( contour . size ( ) - dist0 ) < minimumSideLength ) { throw new RuntimeException ( "Should be impossible" ) ; } // this function is only called if splitable is set to true so no need to set it again e0 . object . splitLocation = resultsA . index ; e0 . object . splitError0 = computeSideError ( contour , e0 . object . index , resultsA . index ) ; e0 . object . splitError1 = computeSideError ( contour , resultsA . index , e1 . object . index ) ; if ( e0 . object . splitLocation >= contour . size ( ) ) throw new RuntimeException ( "Egads" ) ; } | Selects and splits the side defined by the e0 corner . If convex a check is performed to ensure that the polyline will be convex still . | 480 | 32 |
26,606 | boolean canBeSplit ( List < Point2D_I32 > contour , Element < Corner > e0 , boolean mustSplit ) { Element < Corner > e1 = next ( e0 ) ; // NOTE: The contour is passed in but only the size of the contour matters. This was done to prevent // changing the signature if the algorithm was changed later on. int length = CircularIndex . distanceP ( e0 . object . index , e1 . object . index , contour . size ( ) ) ; // needs to be <= to prevent it from trying to split a side less than 1 // times two because the two new sides would have to have a length of at least min if ( length <= 2 * minimumSideLength ) { return false ; } // threshold is greater than zero ti prevent it from saying it can split a perfect side return mustSplit || e0 . object . sideError > thresholdSideSplitScore ; } | Determines if the side can be split again . A side can always be split as long as it s &ge ; the minimum length or that the side score is larger the the split threshold | 196 | 39 |
26,607 | Element < Corner > next ( Element < Corner > e ) { if ( e . next == null ) { return list . getHead ( ) ; } else { return e . next ; } } | Returns the next corner in the list | 40 | 7 |
26,608 | Element < Corner > previous ( Element < Corner > e ) { if ( e . previous == null ) { return list . getTail ( ) ; } else { return e . previous ; } } | Returns the previous corner in the list | 41 | 7 |
26,609 | static double distanceSq ( Point2D_I32 a , Point2D_I32 b ) { double dx = b . x - a . x ; double dy = b . y - a . y ; return dx * dx + dy * dy ; } | Using double prevision here instead of int due to fear of overflow in very large images | 55 | 17 |
26,610 | public static void assignLine ( List < Point2D_I32 > contour , int indexA , int indexB , LineParametric2D_F64 line ) { Point2D_I32 endA = contour . get ( indexA ) ; Point2D_I32 endB = contour . get ( indexB ) ; line . p . x = endA . x ; line . p . y = endA . y ; line . slope . x = endB . x - endA . x ; line . slope . y = endB . y - endA . y ; } | Assigns the line so that it passes through points A and B . | 128 | 15 |
26,611 | protected void splitPixels ( int indexStart , int indexStop ) { // too short to split if ( indexStart + 1 >= indexStop ) return ; int indexSplit = selectSplitBetween ( indexStart , indexStop ) ; if ( indexSplit >= 0 ) { splitPixels ( indexStart , indexSplit ) ; splits . add ( indexSplit ) ; splitPixels ( indexSplit , indexStop ) ; } } | Recursively splits pixels . Used in the initial segmentation . Only split points between the two ends are added | 87 | 22 |
26,612 | protected boolean splitSegments ( ) { boolean change = false ; work . reset ( ) ; for ( int i = 0 ; i < splits . size - 1 ; i ++ ) { int start = splits . data [ i ] ; int end = splits . data [ i + 1 ] ; int bestIndex = selectSplitBetween ( start , end ) ; if ( bestIndex >= 0 ) { change |= true ; work . add ( start ) ; work . add ( bestIndex ) ; } else { work . add ( start ) ; } } work . add ( splits . data [ splits . size - 1 ] ) ; // swap the two lists GrowQueue_I32 tmp = work ; work = splits ; splits = tmp ; return change ; } | Splits a line in two if there is a paint that is too far away | 155 | 16 |
26,613 | protected boolean mergeSegments ( ) { // can't merge a single line if ( splits . size <= 2 ) return false ; boolean change = false ; work . reset ( ) ; // first point is always at the start work . add ( splits . data [ 0 ] ) ; for ( int i = 0 ; i < splits . size - 2 ; i ++ ) { if ( selectSplitBetween ( splits . data [ i ] , splits . data [ i + 2 ] ) < 0 ) { // merge the two lines by not adding it change = true ; } else { work . add ( splits . data [ i + 1 ] ) ; } } // and end work . add ( splits . data [ splits . size - 1 ] ) ; // swap the two lists GrowQueue_I32 tmp = work ; work = splits ; splits = tmp ; return change ; } | Merges lines together which have an acute angle less than the threshold . | 179 | 14 |
26,614 | public void initialize ( PyramidDiscrete < I > image ) { if ( previousDerivX == null || previousDerivX . length != image . getNumLayers ( ) || previousImage . getInputWidth ( ) != image . getInputWidth ( ) || previousImage . getInputHeight ( ) != image . getInputHeight ( ) ) { declareDataStructures ( image ) ; } for ( int i = 0 ; i < image . getNumLayers ( ) ; i ++ ) { gradient . process ( image . getLayer ( i ) , previousDerivX [ i ] , previousDerivY [ i ] ) ; } previousImage . setTo ( image ) ; } | Call for the first image being tracked | 144 | 7 |
26,615 | protected void declareDataStructures ( PyramidDiscrete < I > image ) { numPyramidLayers = image . getNumLayers ( ) ; previousDerivX = ( D [ ] ) Array . newInstance ( derivType , image . getNumLayers ( ) ) ; previousDerivY = ( D [ ] ) Array . newInstance ( derivType , image . getNumLayers ( ) ) ; currentDerivX = ( D [ ] ) Array . newInstance ( derivType , image . getNumLayers ( ) ) ; currentDerivY = ( D [ ] ) Array . newInstance ( derivType , image . getNumLayers ( ) ) ; for ( int i = 0 ; i < image . getNumLayers ( ) ; i ++ ) { int w = image . getWidth ( i ) ; int h = image . getHeight ( i ) ; previousDerivX [ i ] = GeneralizedImageOps . createSingleBand ( derivType , w , h ) ; previousDerivY [ i ] = GeneralizedImageOps . createSingleBand ( derivType , w , h ) ; currentDerivX [ i ] = GeneralizedImageOps . createSingleBand ( derivType , w , h ) ; currentDerivY [ i ] = GeneralizedImageOps . createSingleBand ( derivType , w , h ) ; } Class imageClass = image . getImageType ( ) . getImageClass ( ) ; previousImage = FactoryPyramid . discreteGaussian ( image . getScales ( ) , - 1 , 1 , false , ImageType . single ( imageClass ) ) ; previousImage . initialize ( image . getInputWidth ( ) , image . getInputHeight ( ) ) ; for ( int i = 0 ; i < tracks . length ; i ++ ) { Track t = new Track ( ) ; t . klt = new PyramidKltFeature ( numPyramidLayers , featureRadius ) ; tracks [ i ] = t ; } } | Declares internal data structures based on the input image pyramid | 420 | 11 |
26,616 | public boolean process ( ImagePyramid < I > image , Rectangle2D_F64 targetRectangle ) { boolean success = true ; updateCurrent ( image ) ; // create feature tracks spawnGrid ( targetRectangle ) ; // track features while computing forward/backward error and NCC error if ( ! trackFeature ( ) ) success = false ; // makes the current image into a previous image setCurrentToPrevious ( ) ; return success ; } | Creates several tracks inside the target rectangle and compuets their motion | 93 | 14 |
26,617 | protected void updateCurrent ( ImagePyramid < I > image ) { this . currentImage = image ; for ( int i = 0 ; i < image . getNumLayers ( ) ; i ++ ) { gradient . process ( image . getLayer ( i ) , currentDerivX [ i ] , currentDerivY [ i ] ) ; } } | Computes the gradient and changes the reference to the current pyramid | 74 | 12 |
26,618 | protected void spawnGrid ( Rectangle2D_F64 prevRect ) { // Shrink the rectangle to ensure that all features are entirely contained inside spawnRect . p0 . x = prevRect . p0 . x + featureRadius ; spawnRect . p0 . y = prevRect . p0 . y + featureRadius ; spawnRect . p1 . x = prevRect . p1 . x - featureRadius ; spawnRect . p1 . y = prevRect . p1 . y - featureRadius ; double spawnWidth = spawnRect . getWidth ( ) ; double spawnHeight = spawnRect . getHeight ( ) ; // try spawning features at evenly spaced points inside the grid tracker . setImage ( previousImage , previousDerivX , previousDerivY ) ; for ( int i = 0 ; i < gridWidth ; i ++ ) { float y = ( float ) ( spawnRect . p0 . y + i * spawnHeight / ( gridWidth - 1 ) ) ; for ( int j = 0 ; j < gridWidth ; j ++ ) { float x = ( float ) ( spawnRect . p0 . x + j * spawnWidth / ( gridWidth - 1 ) ) ; Track t = tracks [ i * gridWidth + j ] ; t . klt . x = x ; t . klt . y = y ; if ( tracker . setDescription ( t . klt ) ) { t . active = true ; } else { t . active = false ; } } } } | Spawn KLT tracks at evenly spaced points inside a grid | 317 | 11 |
26,619 | public boolean process ( T left , T right ) { if ( first ) { associateL2R ( left , right ) ; first = false ; } else { // long time0 = System.currentTimeMillis(); associateL2R ( left , right ) ; // long time1 = System.currentTimeMillis(); associateF2F ( ) ; // long time2 = System.currentTimeMillis(); cyclicConsistency ( ) ; // long time3 = System.currentTimeMillis(); if ( ! estimateMotion ( ) ) return false ; // long time4 = System.currentTimeMillis(); // System.out.println("timing: "+(time1-time0)+" "+(time2-time1)+" "+(time3-time2)+" "+(time4-time3)); } return true ; } | Estimates camera egomotion from the stereo pair | 179 | 10 |
26,620 | private void associateL2R ( T left , T right ) { // make the previous new observations into the new old ones ImageInfo < TD > tmp = featsLeft1 ; featsLeft1 = featsLeft0 ; featsLeft0 = tmp ; tmp = featsRight1 ; featsRight1 = featsRight0 ; featsRight0 = tmp ; // detect and associate features in the two images featsLeft1 . reset ( ) ; featsRight1 . reset ( ) ; // long time0 = System.currentTimeMillis(); describeImage ( left , featsLeft1 ) ; describeImage ( right , featsRight1 ) ; // long time1 = System.currentTimeMillis(); // detect and associate features in the current stereo pair for ( int i = 0 ; i < detector . getNumberOfSets ( ) ; i ++ ) { SetMatches matches = setMatches [ i ] ; matches . swap ( ) ; matches . match2to3 . reset ( ) ; FastQueue < Point2D_F64 > leftLoc = featsLeft1 . location [ i ] ; FastQueue < Point2D_F64 > rightLoc = featsRight1 . location [ i ] ; assocL2R . setSource ( leftLoc , featsLeft1 . description [ i ] ) ; assocL2R . setDestination ( rightLoc , featsRight1 . description [ i ] ) ; assocL2R . associate ( ) ; FastQueue < AssociatedIndex > found = assocL2R . getMatches ( ) ; // removeUnassociated(leftLoc,featsLeft1.description[i],rightLoc,featsRight1.description[i],found); setMatches ( matches . match2to3 , found , leftLoc . size ) ; } // long time2 = System.currentTimeMillis(); // System.out.println(" desc "+(time1-time0)+" assoc "+(time2-time1)); } | Associates image features from the left and right camera together while applying epipolar constraints . | 411 | 18 |
26,621 | private void associateF2F ( ) { quadViews . reset ( ) ; for ( int i = 0 ; i < detector . getNumberOfSets ( ) ; i ++ ) { SetMatches matches = setMatches [ i ] ; // old left to new left assocSame . setSource ( featsLeft0 . location [ i ] , featsLeft0 . description [ i ] ) ; assocSame . setDestination ( featsLeft1 . location [ i ] , featsLeft1 . description [ i ] ) ; assocSame . associate ( ) ; setMatches ( matches . match0to2 , assocSame . getMatches ( ) , featsLeft0 . location [ i ] . size ) ; // old right to new right assocSame . setSource ( featsRight0 . location [ i ] , featsRight0 . description [ i ] ) ; assocSame . setDestination ( featsRight1 . location [ i ] , featsRight1 . description [ i ] ) ; assocSame . associate ( ) ; setMatches ( matches . match1to3 , assocSame . getMatches ( ) , featsRight0 . location [ i ] . size ) ; } } | Associates images between left and left and right and right images | 254 | 13 |
26,622 | private void cyclicConsistency ( ) { for ( int i = 0 ; i < detector . getNumberOfSets ( ) ; i ++ ) { FastQueue < Point2D_F64 > obs0 = featsLeft0 . location [ i ] ; FastQueue < Point2D_F64 > obs1 = featsRight0 . location [ i ] ; FastQueue < Point2D_F64 > obs2 = featsLeft1 . location [ i ] ; FastQueue < Point2D_F64 > obs3 = featsRight1 . location [ i ] ; SetMatches matches = setMatches [ i ] ; if ( matches . match0to1 . size != matches . match0to2 . size ) throw new RuntimeException ( "Failed sanity check" ) ; for ( int j = 0 ; j < matches . match0to1 . size ; j ++ ) { int indexIn1 = matches . match0to1 . data [ j ] ; int indexIn2 = matches . match0to2 . data [ j ] ; if ( indexIn1 < 0 || indexIn2 < 0 ) continue ; int indexIn3a = matches . match1to3 . data [ indexIn1 ] ; int indexIn3b = matches . match2to3 . data [ indexIn2 ] ; if ( indexIn3a < 0 || indexIn3b < 0 ) continue ; // consistent association to new right camera image if ( indexIn3a == indexIn3b ) { QuadView v = quadViews . grow ( ) ; v . v0 = obs0 . get ( j ) ; v . v1 = obs1 . get ( indexIn1 ) ; v . v2 = obs2 . get ( indexIn2 ) ; v . v3 = obs3 . get ( indexIn3a ) ; } } } } | Create a list of features which have a consistent cycle of matches 0 - > 1 - > 3 and 0 - > 2 - > 3 | 392 | 27 |
26,623 | private void describeImage ( T left , ImageInfo < TD > info ) { detector . process ( left ) ; for ( int i = 0 ; i < detector . getNumberOfSets ( ) ; i ++ ) { PointDescSet < TD > set = detector . getFeatureSet ( i ) ; FastQueue < Point2D_F64 > l = info . location [ i ] ; FastQueue < TD > d = info . description [ i ] ; for ( int j = 0 ; j < set . getNumberOfFeatures ( ) ; j ++ ) { l . grow ( ) . set ( set . getLocation ( j ) ) ; d . grow ( ) . setTo ( set . getDescription ( j ) ) ; } } } | Computes image features and stores the results in info | 156 | 10 |
26,624 | private boolean estimateMotion ( ) { modelFitData . reset ( ) ; Point2D_F64 normLeft = new Point2D_F64 ( ) ; Point2D_F64 normRight = new Point2D_F64 ( ) ; // use 0 -> 1 stereo associations to estimate each feature's 3D position for ( int i = 0 ; i < quadViews . size ; i ++ ) { QuadView obs = quadViews . get ( i ) ; // convert old stereo view to normalized coordinates leftImageToNorm . compute ( obs . v0 . x , obs . v0 . y , normLeft ) ; rightImageToNorm . compute ( obs . v1 . x , obs . v1 . y , normRight ) ; // compute 3D location using triangulation triangulate . triangulate ( normLeft , normRight , leftToRight , obs . X ) ; // add to data set for fitting if not at infinity if ( ! Double . isInfinite ( obs . X . normSq ( ) ) ) { Stereo2D3D data = modelFitData . grow ( ) ; leftImageToNorm . compute ( obs . v2 . x , obs . v2 . y , data . leftObs ) ; rightImageToNorm . compute ( obs . v3 . x , obs . v3 . y , data . rightObs ) ; data . location . set ( obs . X ) ; } } // robustly match the data if ( ! matcher . process ( modelFitData . toList ( ) ) ) return false ; Se3_F64 oldToNew = matcher . getModelParameters ( ) ; // System.out.println("matcher rot = "+toString(oldToNew)); // optionally refine the results if ( modelRefiner != null ) { Se3_F64 found = new Se3_F64 ( ) ; if ( modelRefiner . fitModel ( matcher . getMatchSet ( ) , oldToNew , found ) ) { // System.out.println("matcher rot = "+toString(found)); found . invert ( newToOld ) ; } else { oldToNew . invert ( newToOld ) ; // System.out.println("Fit failed!"); } } else { oldToNew . invert ( newToOld ) ; } // compound the just found motion with the previously found motion Se3_F64 temp = new Se3_F64 ( ) ; newToOld . concat ( leftCamToWorld , temp ) ; leftCamToWorld . set ( temp ) ; return true ; } | Estimates camera egomotion between the two most recent image frames | 551 | 13 |
26,625 | @ Override public void setEquirectangularShape ( int width , int height ) { super . setEquirectangularShape ( width , height ) ; declareVectors ( width , height ) ; // precompute vectors for each pixel for ( int y = 0 ; y < height ; y ++ ) { for ( int x = 0 ; x < width ; x ++ ) { tools . equiToNormFV ( x , y , vectors [ y * width + x ] ) ; } } } | Specifies the image s width and height | 105 | 8 |
26,626 | public static < T extends ImageBase < T > > TrackerObjectQuad < T > meanShiftLikelihood ( int maxIterations , int numBins , double maxPixelValue , MeanShiftLikelihoodType modelType , ImageType < T > imageType ) { PixelLikelihood < T > likelihood ; switch ( modelType ) { case HISTOGRAM : likelihood = FactoryTrackerObjectAlgs . likelihoodHistogramCoupled ( maxPixelValue , numBins , imageType ) ; break ; case HISTOGRAM_INDEPENDENT_RGB_to_HSV : if ( imageType . getNumBands ( ) != 3 ) throw new IllegalArgumentException ( "Expected RGB image as input with 3-bands" ) ; likelihood = FactoryTrackerObjectAlgs . likelihoodHueSatHistIndependent ( maxPixelValue , numBins , ( ImageType ) imageType ) ; break ; case HISTOGRAM_RGB_to_HSV : if ( imageType . getNumBands ( ) != 3 ) throw new IllegalArgumentException ( "Expected RGB image as input with 3-bands" ) ; likelihood = FactoryTrackerObjectAlgs . likelihoodHueSatHistCoupled ( maxPixelValue , numBins , ( ImageType ) imageType ) ; break ; default : throw new IllegalArgumentException ( "Unknown likelihood model " + modelType ) ; } TrackerMeanShiftLikelihood < T > alg = new TrackerMeanShiftLikelihood <> ( likelihood , maxIterations , 0.1f ) ; return new Msl_to_TrackerObjectQuad <> ( alg , likelihood , imageType ) ; } | Very basic and very fast implementation of mean - shift which uses a fixed sized rectangle for its region . Works best when the target is composed of a single color . | 351 | 32 |
26,627 | public static < T extends ImageBase < T > > TrackerObjectQuad < T > meanShiftComaniciu2003 ( ConfigComaniciu2003 config , ImageType < T > imageType ) { TrackerMeanShiftComaniciu2003 < T > alg = FactoryTrackerObjectAlgs . meanShiftComaniciu2003 ( config , imageType ) ; return new Comaniciu2003_to_TrackerObjectQuad <> ( alg , imageType ) ; } | Implementation of mean - shift which matches the histogram and can handle targets composed of multiple colors . The tracker can also be configured to estimate gradual changes in scale . The track region is composed of a rotated rectangle . | 102 | 43 |
26,628 | public void updateBackground ( T frame , GrayU8 segment ) { updateBackground ( frame ) ; segment ( frame , segment ) ; } | Updates the background and segments it at the same time . In some implementations this can be significantly faster than doing it with separate function calls . Segmentation is performed using the model which it has prior to the update . | 28 | 44 |
26,629 | public void append ( int bits , int numberOfBits , boolean swapOrder ) { if ( numberOfBits > 32 ) throw new IllegalArgumentException ( "Number of bits exceeds the size of bits" ) ; int indexTail = size ; growArray ( numberOfBits , true ) ; if ( swapOrder ) { for ( int i = 0 ; i < numberOfBits ; i ++ ) { set ( indexTail + i , ( bits >> i ) & 1 ) ; } } else { for ( int i = 0 ; i < numberOfBits ; i ++ ) { set ( indexTail + numberOfBits - i - 1 , ( bits >> i ) & 1 ) ; } } } | Appends bits on to the end of the stack . | 154 | 11 |
26,630 | public int read ( int location , int length , boolean swapOrder ) { if ( length < 0 || length > 32 ) throw new IllegalArgumentException ( "Length can't exceed 32" ) ; if ( location + length > size ) throw new IllegalArgumentException ( "Attempting to read past the end" ) ; // TODO speed up by reading in byte chunks int output = 0 ; if ( swapOrder ) { for ( int i = 0 ; i < length ; i ++ ) { output |= get ( location + i ) << ( length - i - 1 ) ; } } else { for ( int i = 0 ; i < length ; i ++ ) { output |= get ( location + i ) << i ; } } return output ; } | Read bits from the array and store them in an int | 158 | 11 |
26,631 | public void growArray ( int amountBits , boolean saveValue ) { size = size + amountBits ; int N = size / 8 + ( size % 8 == 0 ? 0 : 1 ) ; if ( N > data . length ) { // add in some buffer to avoid lots of calls to new int extra = Math . min ( 1024 , N + 10 ) ; byte [ ] tmp = new byte [ N + extra ] ; if ( saveValue ) System . arraycopy ( data , 0 , tmp , 0 , data . length ) ; this . data = tmp ; } } | Increases the size of the data array so that it can store an addition number of bits | 121 | 17 |
26,632 | protected boolean computeH ( DMatrixRMaj A , DMatrixRMaj H ) { if ( ! solverNullspace . process ( A . copy ( ) , 1 , H ) ) return true ; H . numRows = 3 ; H . numCols = 3 ; return false ; } | Computes the SVD of A and extracts the homography matrix from its null space | 64 | 17 |
26,633 | public static void undoNormalizationH ( DMatrixRMaj M , NormalizationPoint2D N1 , NormalizationPoint2D N2 ) { SimpleMatrix a = SimpleMatrix . wrap ( M ) ; SimpleMatrix b = SimpleMatrix . wrap ( N1 . matrix ( ) ) ; SimpleMatrix c_inv = SimpleMatrix . wrap ( N2 . matrixInv ( ) ) ; SimpleMatrix result = c_inv . mult ( a ) . mult ( b ) ; M . set ( result . getDDRM ( ) ) ; } | Undoes normalization for a homography matrix . | 114 | 10 |
26,634 | protected int addConicPairConstraints ( AssociatedPairConic a , AssociatedPairConic b , DMatrixRMaj A , int rowA ) { // s*C[i] = H^T*V[i]*H // C[i] = a, C[j] = b // Conic in view 1 is C and view 2 is V, e.g. x' = H*x. x' is in view 2 and x in view 1 UtilCurves_F64 . convert ( a . p1 , C1 ) ; UtilCurves_F64 . convert ( a . p2 , V1 ) ; CommonOps_DDF3 . invert ( C1 , C1_inv ) ; CommonOps_DDF3 . invert ( V1 , V1_inv ) ; UtilCurves_F64 . convert ( b . p1 , C2 ) ; UtilCurves_F64 . convert ( b . p2 , V2 ) ; CommonOps_DDF3 . invert ( C2 , C2_inv ) ; CommonOps_DDF3 . invert ( V2 , V2_inv ) ; // L = inv(V[i])*V[j] CommonOps_DDF3 . mult ( V1_inv , V2 , L ) ; // R = C[i]*inv(C[j]) CommonOps_DDF3 . mult ( C1_inv , C2 , R ) ; // clear this row int idxA = rowA * 9 ; // Arrays.fill(A.data,idxA,9*9,0); <-- has already been zeroed // NOTE: adding all 9 rows is redundant. The source paper doesn't attempt to reduce the number of rows // maybe this can be made to run faster if the rows can be intelligently pruned // inv(V[i])*V[j]*H - H*C[i]*inv(C[j]) == 0 for ( int row = 0 ; row < 3 ; row ++ ) { for ( int col = 0 ; col < 3 ; col ++ ) { for ( int i = 0 ; i < 3 ; i ++ ) { A . data [ idxA + 3 * i + col ] += L . get ( row , i ) ; A . data [ idxA + 3 * row + i ] -= R . get ( i , col ) ; } idxA += 9 ; } } return rowA + 9 ; } | Add constraint for a pair of conics | 545 | 8 |
26,635 | protected void initalize ( T input ) { this . input = input ; pixels . resize ( input . width * input . height ) ; initialSegments . reshape ( input . width , input . height ) ; // number of usable pixels that cluster centers can be placed in int numberOfUsable = ( input . width - 2 * BORDER ) * ( input . height - 2 * BORDER ) ; gridInterval = ( int ) Math . sqrt ( numberOfUsable / ( double ) numberOfRegions ) ; if ( gridInterval <= 0 ) throw new IllegalArgumentException ( "Too many regions for an image of this size" ) ; // See equation (1) adjustSpacial = m / gridInterval ; } | prepares all data structures | 158 | 5 |
26,636 | protected void initializeClusters ( ) { int offsetX = Math . max ( BORDER , ( ( input . width - 1 ) % gridInterval ) / 2 ) ; int offsetY = Math . max ( BORDER , ( ( input . height - 1 ) % gridInterval ) / 2 ) ; int clusterId = 0 ; clusters . reset ( ) ; for ( int y = offsetY ; y < input . height - BORDER ; y += gridInterval ) { for ( int x = offsetX ; x < input . width - BORDER ; x += gridInterval ) { Cluster c = clusters . grow ( ) ; c . id = clusterId ++ ; if ( c . color == null ) c . color = new float [ numBands ] ; // sets the location and color at the local minimal gradient point perturbCenter ( c , x , y ) ; } } } | initialize all the clusters at regularly spaced intervals . Their locations are perturbed a bit to reduce the likelihood of a bad location . Initial color is set to the image color at the location | 191 | 37 |
26,637 | protected void perturbCenter ( Cluster c , int x , int y ) { float best = Float . MAX_VALUE ; int bestX = 0 , bestY = 0 ; for ( int dy = - 1 ; dy <= 1 ; dy ++ ) { for ( int dx = - 1 ; dx <= 1 ; dx ++ ) { float d = gradient ( x + dx , y + dy ) ; if ( d < best ) { best = d ; bestX = dx ; bestY = dy ; } } } c . x = x + bestX ; c . y = y + bestY ; setColor ( c . color , x + bestX , y + bestY ) ; } | Set the cluster s center to be the pixel in a 3x3 neighborhood with the smallest gradient | 143 | 19 |
26,638 | protected float gradient ( int x , int y ) { float dx = getIntensity ( x + 1 , y ) - getIntensity ( x - 1 , y ) ; float dy = getIntensity ( x , y + 1 ) - getIntensity ( x , y - 1 ) ; return dx * dx + dy * dy ; } | Computes the gradient at the specified pixel | 71 | 8 |
26,639 | protected void computeClusterDistance ( ) { for ( int i = 0 ; i < pixels . size ; i ++ ) { pixels . data [ i ] . reset ( ) ; } for ( int i = 0 ; i < clusters . size && ! stopRequested ; i ++ ) { Cluster c = clusters . data [ i ] ; // compute search bounds int centerX = ( int ) ( c . x + 0.5f ) ; int centerY = ( int ) ( c . y + 0.5f ) ; int x0 = centerX - gridInterval ; int x1 = centerX + gridInterval + 1 ; int y0 = centerY - gridInterval ; int y1 = centerY + gridInterval + 1 ; if ( x0 < 0 ) x0 = 0 ; if ( y0 < 0 ) y0 = 0 ; if ( x1 > input . width ) x1 = input . width ; if ( y1 > input . height ) y1 = input . height ; for ( int y = y0 ; y < y1 ; y ++ ) { int indexPixel = y * input . width + x0 ; int indexInput = input . startIndex + y * input . stride + x0 ; int dy = y - centerY ; for ( int x = x0 ; x < x1 ; x ++ ) { int dx = x - centerX ; float distanceColor = colorDistance ( c . color , indexInput ++ ) ; float distanceSpacial = dx * dx + dy * dy ; pixels . data [ indexPixel ++ ] . add ( c , distanceColor + adjustSpacial * distanceSpacial ) ; } } } } | Computes how far away each cluster is from each pixel . Expectation step . | 353 | 16 |
26,640 | protected void updateClusters ( ) { for ( int i = 0 ; i < clusters . size ; i ++ ) { clusters . data [ i ] . reset ( ) ; } int indexPixel = 0 ; for ( int y = 0 ; y < input . height && ! stopRequested ; y ++ ) { int indexInput = input . startIndex + y * input . stride ; for ( int x = 0 ; x < input . width ; x ++ , indexPixel ++ , indexInput ++ ) { Pixel p = pixels . get ( indexPixel ) ; // convert the distance each cluster is from the pixel into weights p . computeWeights ( ) ; for ( int i = 0 ; i < p . clusters . size ; i ++ ) { ClusterDistance d = p . clusters . data [ i ] ; d . cluster . x += x * d . distance ; d . cluster . y += y * d . distance ; d . cluster . totalWeight += d . distance ; addColor ( d . cluster . color , indexInput , d . distance ) ; } } } // recompute the center of each cluster for ( int i = 0 ; i < clusters . size ; i ++ ) { clusters . data [ i ] . update ( ) ; } } | Update the value of each cluster using Maximization step . | 261 | 11 |
26,641 | public void assignLabelsToPixels ( GrayS32 pixelToRegions , GrowQueue_I32 regionMemberCount , FastQueue < float [ ] > regionColor ) { regionColor . reset ( ) ; for ( int i = 0 ; i < clusters . size ( ) ; i ++ ) { float [ ] r = regionColor . grow ( ) ; float [ ] c = clusters . get ( i ) . color ; for ( int j = 0 ; j < numBands ; j ++ ) { r [ j ] = c [ j ] ; } } regionMemberCount . resize ( clusters . size ( ) ) ; regionMemberCount . fill ( 0 ) ; int indexPixel = 0 ; for ( int y = 0 ; y < pixelToRegions . height ; y ++ ) { int indexOutput = pixelToRegions . startIndex + y * pixelToRegions . stride ; for ( int x = 0 ; x < pixelToRegions . width ; x ++ , indexPixel ++ , indexOutput ++ ) { Pixel p = pixels . data [ indexPixel ] ; // It is possible for a pixel to be unassigned if all the means move too far away from it // Default to a non-existant cluster if that's the case int best = - 1 ; float bestDistance = Float . MAX_VALUE ; // find the region/cluster which it is closest to for ( int j = 0 ; j < p . clusters . size ; j ++ ) { ClusterDistance d = p . clusters . data [ j ] ; if ( d . distance < bestDistance ) { bestDistance = d . distance ; best = d . cluster . id ; } } if ( best == - 1 ) { regionColor . grow ( ) ; best = regionMemberCount . size ( ) ; regionMemberCount . add ( 0 ) ; } pixelToRegions . data [ indexOutput ] = best ; regionMemberCount . data [ best ] ++ ; } } } | Selects which region each pixel belongs to based on which cluster it is the closest to | 410 | 17 |
26,642 | public void process ( DMatrixRMaj F , List < AssociatedPair > observations , int width , int height ) { int centerX = width / 2 ; int centerY = height / 2 ; MultiViewOps . extractEpipoles ( F , epipole1 , epipole2 ) ; checkEpipoleInside ( width , height ) ; // compute the transform H which will send epipole2 to infinity SimpleMatrix R = rotateEpipole ( epipole2 , centerX , centerY ) ; SimpleMatrix T = translateToOrigin ( centerX , centerY ) ; SimpleMatrix G = computeG ( epipole2 , centerX , centerY ) ; SimpleMatrix H = G . mult ( R ) . mult ( T ) ; //Find the two matching transforms SimpleMatrix Hzero = computeHZero ( F , epipole2 , H ) ; SimpleMatrix Ha = computeAffineH ( observations , H . getDDRM ( ) , Hzero . getDDRM ( ) ) ; rect1 . set ( Ha . mult ( Hzero ) . getDDRM ( ) ) ; rect2 . set ( H . getDDRM ( ) ) ; } | Compute rectification transforms for the stereo pair given a fundamental matrix and its observations . | 253 | 17 |
26,643 | private void checkEpipoleInside ( int width , int height ) { double x1 = epipole1 . x / epipole1 . z ; double y1 = epipole1 . y / epipole1 . z ; double x2 = epipole2 . x / epipole2 . z ; double y2 = epipole2 . y / epipole2 . z ; if ( x1 >= 0 && x1 < width && y1 >= 0 && y1 < height ) throw new IllegalArgumentException ( "First epipole is inside the image" ) ; if ( x2 >= 0 && x2 < width && y2 >= 0 && y2 < height ) throw new IllegalArgumentException ( "Second epipole is inside the image" ) ; } | The epipoles need to be outside the image | 170 | 10 |
26,644 | private SimpleMatrix translateToOrigin ( int x0 , int y0 ) { SimpleMatrix T = SimpleMatrix . identity ( 3 ) ; T . set ( 0 , 2 , - x0 ) ; T . set ( 1 , 2 , - y0 ) ; return T ; } | Create a transform which will move the specified point to the origin | 58 | 12 |
26,645 | private SimpleMatrix computeAffineH ( List < AssociatedPair > observations , DMatrixRMaj H , DMatrixRMaj Hzero ) { SimpleMatrix A = new SimpleMatrix ( observations . size ( ) , 3 ) ; SimpleMatrix b = new SimpleMatrix ( A . numRows ( ) , 1 ) ; Point2D_F64 c = new Point2D_F64 ( ) ; Point2D_F64 k = new Point2D_F64 ( ) ; for ( int i = 0 ; i < observations . size ( ) ; i ++ ) { AssociatedPair a = observations . get ( i ) ; GeometryMath_F64 . mult ( Hzero , a . p1 , k ) ; GeometryMath_F64 . mult ( H , a . p2 , c ) ; A . setRow ( i , 0 , k . x , k . y , 1 ) ; b . set ( i , 0 , c . x ) ; } SimpleMatrix x = A . solve ( b ) ; SimpleMatrix Ha = SimpleMatrix . identity ( 3 ) ; Ha . setRow ( 0 , 0 , x . getDDRM ( ) . data ) ; return Ha ; } | Finds the values of a b c which minimize | 256 | 10 |
26,646 | public static URL pathExampleURL ( String path ) { try { File fpath = new File ( path ) ; if ( fpath . isAbsolute ( ) ) return fpath . toURI ( ) . toURL ( ) ; // Assume we are running inside of the project come String pathToBase = getPathToBase ( ) ; if ( pathToBase != null ) { File pathExample = new File ( pathToBase , "data/example/" ) ; if ( pathExample . exists ( ) ) { return new File ( pathExample . getPath ( ) , path ) . getAbsoluteFile ( ) . toURL ( ) ; } } // System.out.println("-----------------------"); // maybe we are running inside an app and all data is stored inside as a resource // System.out.println("Attempting to load resource "+path); URL url = UtilIO . class . getClassLoader ( ) . getResource ( path ) ; if ( url == null ) { System . err . println ( ) ; System . err . println ( "Can't find data/example directory! There are three likely causes for this problem." ) ; System . err . println ( ) ; System . err . println ( "1) You checked out the source code from git and did not pull the data submodule too." ) ; System . err . println ( "2) You are trying to run an example from outside the BoofCV directory tree." ) ; System . err . println ( "3) You are trying to pass in your own image." ) ; System . err . println ( ) ; System . err . println ( "Solutions:" ) ; System . err . println ( "1) Follow instructions in the boofcv/readme.md file to grab the data directory." ) ; System . err . println ( "2) Launch the example from inside BoofCV's directory tree!" ) ; System . err . println ( "3) Don't use this function and just pass in the path directly" ) ; System . exit ( 1 ) ; } return url ; } catch ( MalformedURLException e ) { throw new RuntimeException ( e ) ; } } | Returns an absolute path to the file that is relative to the example directory | 456 | 14 |
26,647 | public static URL ensureURL ( String path ) { path = systemToUnix ( path ) ; URL url ; try { url = new URL ( path ) ; if ( url . getProtocol ( ) . equals ( "jar" ) ) { return simplifyJarPath ( url ) ; } } catch ( MalformedURLException e ) { // might just be a file reference. try { url = new File ( path ) . toURI ( ) . toURL ( ) ; // simplify the path. "1/2/../3" = "1/3" } catch ( MalformedURLException e2 ) { return null ; } } return url ; } | Given a path which may or may not be a URL return a URL | 140 | 14 |
26,648 | public static URL simplifyJarPath ( URL url ) { try { String segments [ ] = url . toString ( ) . split ( ".jar!/" ) ; String path = simplifyJarPath ( segments [ 1 ] ) ; return new URL ( segments [ 0 ] + ".jar!/" + path ) ; } catch ( IOException e ) { return url ; } } | Jar paths don t work if they include up directory . this wills trip those out . | 76 | 17 |
26,649 | public static String path ( String path ) { String pathToBase = getPathToBase ( ) ; if ( pathToBase == null ) return path ; return new File ( pathToBase , path ) . getAbsolutePath ( ) ; } | Searches for the root BoofCV directory and returns an absolute path from it . | 51 | 18 |
26,650 | public static String getPathToBase ( ) { String path = new File ( "." ) . getAbsoluteFile ( ) . getParent ( ) ; while ( path != null ) { File f = new File ( path ) ; if ( ! f . exists ( ) ) break ; String [ ] files = f . list ( ) ; if ( files == null ) break ; boolean foundMain = false ; boolean foundExamples = false ; boolean foundIntegration = false ; for ( String s : files ) { if ( s . compareToIgnoreCase ( "main" ) == 0 ) foundMain = true ; else if ( s . compareToIgnoreCase ( "examples" ) == 0 ) foundExamples = true ; else if ( s . compareToIgnoreCase ( "integration" ) == 0 ) foundIntegration = true ; } if ( foundMain && foundExamples && foundIntegration ) return path ; path = f . getParent ( ) ; } return null ; } | Steps back until it finds the base BoofCV directory . | 206 | 13 |
26,651 | public static String selectFile ( boolean exitOnCancel ) { String fileName = null ; JFileChooser fc = new JFileChooser ( ) ; int returnVal = fc . showOpenDialog ( null ) ; if ( returnVal == JFileChooser . APPROVE_OPTION ) { fileName = fc . getSelectedFile ( ) . getAbsolutePath ( ) ; } else if ( exitOnCancel ) { System . exit ( 0 ) ; } return fileName ; } | Opens up a dialog box asking the user to select a file . If the user cancels it either returns null or quits the program . | 109 | 29 |
26,652 | public static List < String > listByPrefix ( String directory , String prefix , String suffix ) { List < String > ret = new ArrayList <> ( ) ; File d = new File ( directory ) ; if ( ! d . isDirectory ( ) ) { try { URL url = new URL ( directory ) ; if ( url . getProtocol ( ) . equals ( "file" ) ) { d = new File ( url . getFile ( ) ) ; } else if ( url . getProtocol ( ) . equals ( "jar" ) ) { return listJarPrefix ( url , prefix , suffix ) ; } } catch ( MalformedURLException ignore ) { } } if ( ! d . isDirectory ( ) ) throw new IllegalArgumentException ( "Must specify an directory. " + directory ) ; File files [ ] = d . listFiles ( ) ; for ( File f : files ) { if ( f . isDirectory ( ) || f . isHidden ( ) ) continue ; if ( prefix == null || f . getName ( ) . startsWith ( prefix ) ) { if ( suffix == null || f . getName ( ) . endsWith ( suffix ) ) { ret . add ( f . getAbsolutePath ( ) ) ; } } } return ret ; } | Loads a list of files with the specified prefix . | 272 | 11 |
26,653 | public static List < String > listAllMime ( String directory , String type ) { List < String > ret = new ArrayList <> ( ) ; try { // see if it's a URL or not URL url = new URL ( directory ) ; if ( url . getProtocol ( ) . equals ( "file" ) ) { directory = url . getFile ( ) ; } else if ( url . getProtocol ( ) . equals ( "jar" ) ) { return listJarMime ( url , null , null ) ; } else { throw new RuntimeException ( "Not sure what to do with this url. " + url . toString ( ) ) ; } } catch ( MalformedURLException ignore ) { } File d = new File ( directory ) ; if ( ! d . isDirectory ( ) ) throw new IllegalArgumentException ( "Must specify an directory" ) ; File [ ] files = d . listFiles ( ) ; if ( files == null ) return ret ; for ( File f : files ) { if ( f . isDirectory ( ) ) continue ; try { String mimeType = Files . probeContentType ( f . toPath ( ) ) ; if ( mimeType . contains ( type ) ) ret . add ( f . getAbsolutePath ( ) ) ; } catch ( IOException ignore ) { } } Collections . sort ( ret ) ; return ret ; } | Lists all files in the directory with an MIME type that contains the string type | 295 | 17 |
26,654 | public boolean process ( CameraPinholeBrown intrinsic , Se3_F64 planeToCamera ) { proj . setPlaneToCamera ( planeToCamera , true ) ; proj . setIntrinsic ( intrinsic ) ; // find a bounding rectangle on the ground which is visible to the camera and at a high enough resolution double x0 = Double . MAX_VALUE ; double y0 = Double . MAX_VALUE ; double x1 = - Double . MAX_VALUE ; double y1 = - Double . MAX_VALUE ; for ( int y = 0 ; y < intrinsic . height ; y ++ ) { for ( int x = 0 ; x < intrinsic . width ; x ++ ) { if ( ! checkValidPixel ( x , y ) ) continue ; if ( plane0 . x < x0 ) x0 = plane0 . x ; if ( plane0 . x > x1 ) x1 = plane0 . x ; if ( plane0 . y < y0 ) y0 = plane0 . y ; if ( plane0 . y > y1 ) y1 = plane0 . y ; } } if ( x0 == Double . MAX_VALUE ) return false ; // compute parameters with the intent of maximizing viewing area double mapWidth = x1 - x0 ; double mapHeight = y1 - y0 ; overheadWidth = ( int ) Math . floor ( mapWidth / cellSize ) ; overheadHeight = ( int ) Math . floor ( mapHeight * viewHeightFraction / cellSize ) ; centerX = - x0 ; centerY = - ( y0 + mapHeight * ( 1 - viewHeightFraction ) / 2.0 ) ; return true ; } | Computes the view s characteristics | 352 | 6 |
26,655 | public < T extends ImageBase < T > > OverheadView createOverhead ( ImageType < T > imageType ) { OverheadView ret = new OverheadView ( ) ; ret . image = imageType . createImage ( overheadWidth , overheadHeight ) ; ret . cellSize = cellSize ; ret . centerX = centerX ; ret . centerY = centerY ; return ret ; } | Creates a new instance of the overhead view | 83 | 9 |
26,656 | public void start ( Device device , Resolution resolution , Listener listener ) { if ( resolution != Resolution . MEDIUM ) { throw new IllegalArgumentException ( "Depth image is always at medium resolution. Possible bug in kinect driver" ) ; } this . device = device ; this . listener = listener ; // Configure the kinect device . setDepthFormat ( DepthFormat . REGISTERED , resolution ) ; device . setVideoFormat ( VideoFormat . RGB , resolution ) ; // declare data structures int w = UtilOpenKinect . getWidth ( resolution ) ; int h = UtilOpenKinect . getHeight ( resolution ) ; dataDepth = new byte [ w * h * 2 ] ; dataRgb = new byte [ w * h * 3 ] ; depth . reshape ( w , h ) ; rgb . reshape ( w , h ) ; thread = new CombineThread ( ) ; thread . start ( ) ; // make sure the thread is running before moving on while ( ! thread . running ) Thread . yield ( ) ; // start the streaming device . startDepth ( new DepthHandler ( ) { @ Override public void onFrameReceived ( FrameMode mode , ByteBuffer frame , int timestamp ) { processDepth ( frame , timestamp ) ; } } ) ; device . startVideo ( new VideoHandler ( ) { @ Override public void onFrameReceived ( FrameMode mode , ByteBuffer frame , int timestamp ) { processRgb ( frame , timestamp ) ; } } ) ; } | Adds listeners to the device and sets its resolutions . | 313 | 10 |
26,657 | public void stop ( ) { thread . requestStop = true ; long start = System . currentTimeMillis ( ) + timeout ; while ( start > System . currentTimeMillis ( ) && thread . running ) Thread . yield ( ) ; device . stopDepth ( ) ; device . stopVideo ( ) ; device . close ( ) ; } | Stops all the threads from running and closes the video channels and video device | 71 | 15 |
26,658 | public boolean refine ( List < CameraPinhole > calibration , DMatrix4x4 Q ) { if ( calibration . size ( ) != cameras . size ) throw new RuntimeException ( "Calibration and cameras do not match" ) ; computeNumberOfCalibrationParameters ( ) ; func = new ResidualK ( ) ; if ( func . getNumOfInputsN ( ) > 6 * calibration . size ( ) ) throw new IllegalArgumentException ( "Need more views to refine. eqs=" + ( 3 * calibration . size ( ) + " unknowns=" + func . getNumOfInputsN ( ) ) ) ; // Declared new each time to ensure all variables are properly zeroed // plane at infinity to the null space of Q ConvertDMatrixStruct . convert ( Q , _Q ) ; nullspace . process ( _Q , 1 , p ) ; CommonOps_DDRM . divide ( p , p . get ( 3 ) ) ; p . numRows = 3 ; // Convert input objects into an array which can be understood by optimization encode ( calibration , p , param ) ; // Configure optimization // optimizer.setVerbose(System.out,0); optimizer . setFunction ( func , null ) ; // Compute using a numerical Jacobian optimizer . initialize ( param . data , converge . ftol , converge . gtol ) ; // Tell it to run for at most 100 iterations if ( ! UtilOptimize . process ( optimizer , converge . maxIterations ) ) return false ; // extract solution decode ( optimizer . getParameters ( ) , calibration , p ) ; recomputeQ ( p , Q ) ; return true ; } | Refine calibration matrix K given the dual absolute quadratic Q . | 358 | 14 |
26,659 | void recomputeQ ( DMatrixRMaj p , DMatrix4x4 Q ) { Equation eq = new Equation ( ) ; DMatrix3x3 K = new DMatrix3x3 ( ) ; encodeK ( K , 0 , 3 , param . data ) ; eq . alias ( p , "p" , K , "K" ) ; eq . process ( "w=K*K'" ) ; eq . process ( "Q=[w , -w*p;-p'*w , p'*w*p]" ) ; DMatrixRMaj _Q = eq . lookupDDRM ( "Q" ) ; CommonOps_DDRM . divide ( _Q , NormOps_DDRM . normF ( _Q ) ) ; ConvertDMatrixStruct . convert ( _Q , Q ) ; } | Compuets the absolute dual quadratic from the first camera parameters and plane at infinity | 183 | 18 |
26,660 | public int encodeK ( DMatrix3x3 K , int which , int offset , double params [ ] ) { if ( fixedAspectRatio ) { K . a11 = params [ offset ++ ] ; K . a22 = aspect . data [ which ] * K . a11 ; } else { K . a11 = params [ offset ++ ] ; K . a22 = params [ offset ++ ] ; } if ( ! zeroSkew ) { K . a12 = params [ offset ++ ] ; } if ( ! zeroPrinciplePoint ) { K . a13 = params [ offset ++ ] ; K . a23 = params [ offset ++ ] ; } K . a33 = 1 ; return offset ; } | Encode the calibration as a 3x3 matrix . K is assumed to zero initially or at least all non - zero elements will align with values that are written to . | 152 | 34 |
26,661 | public void initializeMerge ( int numRegions ) { mergeList . resize ( numRegions ) ; for ( int i = 0 ; i < numRegions ; i ++ ) mergeList . data [ i ] = i ; } | Must call before any other functions . | 49 | 7 |
26,662 | public void performMerge ( GrayS32 pixelToRegion , GrowQueue_I32 regionMemberCount ) { // update member counts flowIntoRootNode ( regionMemberCount ) ; // re-assign the number of the root node and trim excessive nodes from the lists setToRootNodeNewID ( regionMemberCount ) ; // change the labels in the pixelToRegion image BinaryImageOps . relabel ( pixelToRegion , mergeList . data ) ; } | Merges regions together and updates the provided data structures for said changes . | 96 | 14 |
26,663 | protected void flowIntoRootNode ( GrowQueue_I32 regionMemberCount ) { rootID . resize ( regionMemberCount . size ) ; int count = 0 ; for ( int i = 0 ; i < mergeList . size ; i ++ ) { int p = mergeList . data [ i ] ; // see if it is a root note if ( p == i ) { // mark the root nodes new ID rootID . data [ i ] = count ++ ; continue ; } // traverse down until it finds the root note int gp = mergeList . data [ p ] ; while ( gp != p ) { p = gp ; gp = mergeList . data [ p ] ; } // update the count and change this node into the root node regionMemberCount . data [ p ] += regionMemberCount . data [ i ] ; mergeList . data [ i ] = p ; } } | For each region in the merge list which is not a root node find its root node and add to the root node its member count and set the index in mergeList to the root node . If a node is a root node just note what its new ID will be after all the other segments are removed . | 184 | 61 |
26,664 | protected void setToRootNodeNewID ( GrowQueue_I32 regionMemberCount ) { tmpMemberCount . reset ( ) ; for ( int i = 0 ; i < mergeList . size ; i ++ ) { int p = mergeList . data [ i ] ; if ( p == i ) { mergeList . data [ i ] = rootID . data [ i ] ; tmpMemberCount . add ( regionMemberCount . data [ i ] ) ; } else { mergeList . data [ i ] = rootID . data [ mergeList . data [ i ] ] ; } } regionMemberCount . reset ( ) ; regionMemberCount . addAll ( tmpMemberCount ) ; } | Does much of the work needed to remove the redundant segments that are being merged into their root node . The list of member count is updated . mergeList is updated with the new segment IDs . | 143 | 38 |
26,665 | public static RefineEpipolar homographyRefine ( double tol , int maxIterations , EpipolarError type ) { ModelObservationResidualN residuals ; switch ( type ) { case SIMPLE : residuals = new HomographyResidualTransfer ( ) ; break ; case SAMPSON : residuals = new HomographyResidualSampson ( ) ; break ; default : throw new IllegalArgumentException ( "Type not supported: " + type ) ; } return new LeastSquaresHomography ( tol , maxIterations , residuals ) ; } | Creates a non - linear optimizer for refining estimates of homography matrices . | 123 | 17 |
26,666 | public static RefineEpipolar fundamentalRefine ( double tol , int maxIterations , EpipolarError type ) { switch ( type ) { case SAMPSON : return new LeastSquaresFundamental ( tol , maxIterations , true ) ; case SIMPLE : return new LeastSquaresFundamental ( tol , maxIterations , false ) ; } throw new IllegalArgumentException ( "Type not supported: " + type ) ; } | Creates a non - linear optimizer for refining estimates of fundamental or essential matrices . | 96 | 18 |
26,667 | public static EstimateNofPnP pnp_N ( EnumPNP which , int numIterations ) { MotionTransformPoint < Se3_F64 , Point3D_F64 > motionFit = FitSpecialEuclideanOps_F64 . fitPoints3D ( ) ; switch ( which ) { case P3P_GRUNERT : P3PGrunert grunert = new P3PGrunert ( PolynomialOps . createRootFinder ( 5 , RootFinderType . STURM ) ) ; return new WrapP3PLineDistance ( grunert , motionFit ) ; case P3P_FINSTERWALDER : P3PFinsterwalder finster = new P3PFinsterwalder ( PolynomialOps . createRootFinder ( 4 , RootFinderType . STURM ) ) ; return new WrapP3PLineDistance ( finster , motionFit ) ; case EPNP : Estimate1ofPnP epnp = pnp_1 ( which , numIterations , 0 ) ; return new Estimate1toNofPnP ( epnp ) ; case IPPE : Estimate1ofEpipolar H = FactoryMultiView . homographyTLS ( ) ; return new Estimate1toNofPnP ( new IPPE_to_EstimatePnP ( H ) ) ; } throw new IllegalArgumentException ( "Type " + which + " not known" ) ; } | Creates an estimator for the PnP problem that uses only three observations which is the minimal case and known as P3P . | 318 | 28 |
26,668 | public static Estimate1ofPnP pnp_1 ( EnumPNP which , int numIterations , int numTest ) { if ( which == EnumPNP . EPNP ) { PnPLepetitEPnP alg = new PnPLepetitEPnP ( 0.1 ) ; alg . setNumIterations ( numIterations ) ; return new WrapPnPLepetitEPnP ( alg ) ; } else if ( which == EnumPNP . IPPE ) { Estimate1ofEpipolar H = FactoryMultiView . homographyTLS ( ) ; return new IPPE_to_EstimatePnP ( H ) ; } FastQueue < Se3_F64 > solutions = new FastQueue <> ( 4 , Se3_F64 . class , true ) ; return new EstimateNto1ofPnP ( pnp_N ( which , - 1 ) , solutions , numTest ) ; } | Created an estimator for the P3P problem that selects a single solution by considering additional observations . | 213 | 20 |
26,669 | public static Estimate1ofPnP computePnPwithEPnP ( int numIterations , double magicNumber ) { PnPLepetitEPnP alg = new PnPLepetitEPnP ( magicNumber ) ; alg . setNumIterations ( numIterations ) ; return new WrapPnPLepetitEPnP ( alg ) ; } | Returns a solution to the PnP problem for 4 or more points using EPnP . Fast and fairly accurate algorithm . Can handle general and planar scenario automatically . | 86 | 34 |
26,670 | public static < K extends Kernel2D > SteerableKernel < K > gaussian ( Class < K > kernelType , int orderX , int orderY , double sigma , int radius ) { if ( orderX < 0 || orderX > 4 ) throw new IllegalArgumentException ( "derivX must be from 0 to 4 inclusive." ) ; if ( orderY < 0 || orderY > 4 ) throw new IllegalArgumentException ( "derivT must be from 0 to 4 inclusive." ) ; int order = orderX + orderY ; if ( order > 4 ) { throw new IllegalArgumentException ( "The total order of x and y can't be greater than 4" ) ; } int maxOrder = Math . max ( orderX , orderY ) ; if ( sigma <= 0 ) sigma = ( float ) FactoryKernelGaussian . sigmaForRadius ( radius , maxOrder ) ; else if ( radius <= 0 ) radius = FactoryKernelGaussian . radiusForSigma ( sigma , maxOrder ) ; Class kernel1DType = FactoryKernel . get1DType ( kernelType ) ; Kernel1D kerX = FactoryKernelGaussian . derivativeK ( kernel1DType , orderX , sigma , radius ) ; Kernel1D kerY = FactoryKernelGaussian . derivativeK ( kernel1DType , orderY , sigma , radius ) ; Kernel2D kernel = GKernelMath . convolve ( kerY , kerX ) ; Kernel2D [ ] basis = new Kernel2D [ order + 1 ] ; // convert it into an image which can be rotated ImageGray image = GKernelMath . convertToImage ( kernel ) ; ImageGray imageRotated = ( ImageGray ) image . createNew ( image . width , image . height ) ; basis [ 0 ] = kernel ; // form the basis by created rotated versions of the kernel double angleStep = Math . PI / basis . length ; for ( int index = 1 ; index <= order ; index ++ ) { float angle = ( float ) ( angleStep * index ) ; GImageMiscOps . fill ( imageRotated , 0 ) ; new FDistort ( image , imageRotated ) . rotate ( angle ) . apply ( ) ; basis [ index ] = GKernelMath . convertToKernel ( imageRotated ) ; } SteerableKernel < K > ret ; if ( kernelType == Kernel2D_F32 . class ) ret = ( SteerableKernel < K > ) new SteerableKernel_F32 ( ) ; else ret = ( SteerableKernel < K > ) new SteerableKernel_I32 ( ) ; ret . setBasis ( FactorySteerCoefficients . polynomial ( order ) , basis ) ; return ret ; } | Steerable filter for 2D Gaussian derivatives . The basis is composed of a set of rotated kernels . | 603 | 22 |
26,671 | public void process ( GrayU8 input ) { // input = im_0 removedWatersheds = false ; output . reshape ( input . width + 2 , input . height + 2 ) ; distance . reshape ( input . width + 2 , input . height + 2 ) ; ImageMiscOps . fill ( output , INIT ) ; ImageMiscOps . fill ( distance , 0 ) ; fifo . reset ( ) ; // sort pixels sortPixels ( input ) ; currentLabel = 0 ; for ( int i = 0 ; i < histogram . length ; i ++ ) { GrowQueue_I32 level = histogram [ i ] ; if ( level . size == 0 ) continue ; // Go through each pixel at this level and mark them according to their neighbors for ( int j = 0 ; j < level . size ; j ++ ) { int index = level . data [ j ] ; output . data [ index ] = MASK ; // see if its neighbors has been labeled, if so set its distance and add to queue assignNewToNeighbors ( index ) ; } currentDistance = 1 ; fifo . add ( MARKER_PIXEL ) ; while ( true ) { int p = fifo . popHead ( ) ; // end of a cycle. Exit the loop if it is done or increase the distance and continue processing if ( p == MARKER_PIXEL ) { if ( fifo . isEmpty ( ) ) break ; else { fifo . add ( MARKER_PIXEL ) ; currentDistance ++ ; p = fifo . popHead ( ) ; } } // look at its neighbors and see if they have been labeled or belong to a watershed // and update its distance checkNeighborsAssign ( p ) ; } // see if new minima have been discovered for ( int j = 0 ; j < level . size ; j ++ ) { int index = level . get ( j ) ; // distance associated with p is reset to 0 distance . data [ index ] = 0 ; if ( output . data [ index ] == MASK ) { currentLabel ++ ; fifo . add ( index ) ; output . data [ index ] = currentLabel ; // grow the new region into the surrounding connected pixels while ( ! fifo . isEmpty ( ) ) { checkNeighborsMasks ( fifo . popHead ( ) ) ; } } } } } | Perform watershed segmentation on the provided input image . New basins are created at each local minima . | 500 | 22 |
26,672 | protected void sortPixels ( GrayU8 input ) { // initialize histogram for ( int i = 0 ; i < histogram . length ; i ++ ) { histogram [ i ] . reset ( ) ; } // sort by creating a histogram for ( int y = 0 ; y < input . height ; y ++ ) { int index = input . startIndex + y * input . stride ; int indexOut = ( y + 1 ) * output . stride + 1 ; for ( int x = 0 ; x < input . width ; x ++ , index ++ , indexOut ++ ) { int value = input . data [ index ] & 0xFF ; histogram [ value ] . add ( indexOut ) ; } } } | Very fast histogram based sorting . Index of each pixel is placed inside a list for its intensity level . | 152 | 21 |
26,673 | public static int numDigits ( int number ) { if ( number == 0 ) return 1 ; int adjustment = 0 ; if ( number < 0 ) { adjustment = 1 ; number = - number ; } return adjustment + ( int ) Math . log10 ( number ) + 1 ; } | Returns the number of digits in a number . E . g . 345 = 3 - 345 = 4 0 = 1 | 59 | 23 |
26,674 | public static void boundRectangleInside ( ImageBase b , ImageRectangle r ) { if ( r . x0 < 0 ) r . x0 = 0 ; if ( r . x1 > b . width ) r . x1 = b . width ; if ( r . y0 < 0 ) r . y0 = 0 ; if ( r . y1 > b . height ) r . y1 = b . height ; } | Bounds the provided rectangle to be inside the image . | 91 | 11 |
26,675 | public static boolean checkInside ( ImageBase b , int x , int y , int radius ) { if ( x - radius < 0 ) return false ; if ( x + radius >= b . width ) return false ; if ( y - radius < 0 ) return false ; if ( y + radius >= b . height ) return false ; return true ; } | Returns true if the point is contained inside the image and radius away from the image border . | 72 | 18 |
26,676 | public static void pause ( long milli ) { final Thread t = Thread . currentThread ( ) ; long start = System . currentTimeMillis ( ) ; while ( System . currentTimeMillis ( ) - start < milli ) { synchronized ( t ) { try { long target = milli - ( System . currentTimeMillis ( ) - start ) ; if ( target > 0 ) t . wait ( target ) ; } catch ( InterruptedException ignore ) { } } } } | Invokes wait until the elapsed time has passed . In the thread is interrupted the interrupt is ignored . | 102 | 20 |
26,677 | private void processStream ( CameraPinholeBrown intrinsic , SimpleImageSequence < GrayU8 > sequence , ImagePanel gui , long pauseMilli ) { Font font = new Font ( "Serif" , Font . BOLD , 24 ) ; Se3_F64 fiducialToCamera = new Se3_F64 ( ) ; int frameNumber = 0 ; while ( sequence . hasNext ( ) ) { long before = System . currentTimeMillis ( ) ; GrayU8 input = sequence . next ( ) ; BufferedImage buffered = sequence . getGuiImage ( ) ; try { detector . detect ( input ) ; } catch ( RuntimeException e ) { System . err . println ( "BUG!!! saving image to crash_image.png" ) ; UtilImageIO . saveImage ( buffered , "crash_image.png" ) ; throw e ; } Graphics2D g2 = buffered . createGraphics ( ) ; for ( int i = 0 ; i < detector . totalFound ( ) ; i ++ ) { detector . getFiducialToCamera ( i , fiducialToCamera ) ; long id = detector . getId ( i ) ; double width = detector . getWidth ( i ) ; VisualizeFiducial . drawCube ( fiducialToCamera , intrinsic , width , 3 , g2 ) ; VisualizeFiducial . drawLabelCenter ( fiducialToCamera , intrinsic , "" + id , g2 ) ; } saveResults ( frameNumber ++ ) ; if ( intrinsicPath == null ) { g2 . setColor ( Color . RED ) ; g2 . setFont ( font ) ; g2 . drawString ( "Uncalibrated" , 10 , 20 ) ; } gui . setImage ( buffered ) ; long after = System . currentTimeMillis ( ) ; long time = Math . max ( 0 , pauseMilli - ( after - before ) ) ; if ( time > 0 ) { try { Thread . sleep ( time ) ; } catch ( InterruptedException ignore ) { } } } } | Displays a continuous stream of images | 441 | 7 |
26,678 | private void processImage ( CameraPinholeBrown intrinsic , BufferedImage buffered , ImagePanel gui ) { Font font = new Font ( "Serif" , Font . BOLD , 24 ) ; GrayU8 gray = new GrayU8 ( buffered . getWidth ( ) , buffered . getHeight ( ) ) ; ConvertBufferedImage . convertFrom ( buffered , gray ) ; Se3_F64 fiducialToCamera = new Se3_F64 ( ) ; try { detector . detect ( gray ) ; } catch ( RuntimeException e ) { System . err . println ( "BUG!!! saving image to crash_image.png" ) ; UtilImageIO . saveImage ( buffered , "crash_image.png" ) ; throw e ; } Graphics2D g2 = buffered . createGraphics ( ) ; for ( int i = 0 ; i < detector . totalFound ( ) ; i ++ ) { detector . getFiducialToCamera ( i , fiducialToCamera ) ; long id = detector . getId ( i ) ; double width = detector . getWidth ( i ) ; VisualizeFiducial . drawCube ( fiducialToCamera , intrinsic , width , 3 , g2 ) ; VisualizeFiducial . drawLabelCenter ( fiducialToCamera , intrinsic , "" + id , g2 ) ; } saveResults ( 0 ) ; if ( intrinsicPath == null ) { g2 . setColor ( Color . RED ) ; g2 . setFont ( font ) ; g2 . drawString ( "Uncalibrated" , 10 , 20 ) ; } gui . setImage ( buffered ) ; } | Displays a simple image | 356 | 5 |
26,679 | public byte [ ] readFrame ( DataInputStream in ) { try { if ( findMarker ( in , SOI ) && in . available ( ) > 0 ) { return readJpegData ( in , EOI ) ; } } catch ( IOException e ) { } return null ; } | Read a single frame at a time | 63 | 7 |
26,680 | void applyToBorder ( GrayU8 input , GrayU8 output , int y0 , int y1 , int x0 , int x1 , ApplyHelper h ) { // top-left corner h . computeHistogram ( 0 , 0 , input ) ; h . applyToBlock ( 0 , 0 , x0 + 1 , y0 + 1 , input , output ) ; // top-middle for ( int x = x0 + 1 ; x < x1 ; x ++ ) { h . updateHistogramX ( x - x0 , 0 , input ) ; h . applyToBlock ( x , 0 , x + 1 , y0 , input , output ) ; } // top-right h . updateHistogramX ( x1 - x0 , 0 , input ) ; h . applyToBlock ( x1 , 0 , input . width , y0 + 1 , input , output ) ; // middle-right for ( int y = y0 + 1 ; y < y1 ; y ++ ) { h . updateHistogramY ( x1 - x0 , y - y0 , input ) ; h . applyToBlock ( x1 , y , input . width , y + 1 , input , output ) ; } // bottom-right h . updateHistogramY ( x1 - x0 , y1 - y0 , input ) ; h . applyToBlock ( x1 , y1 , input . width , input . height , input , output ) ; //Start over in the top-left. Yes this step could be avoided... // middle-left h . computeHistogram ( 0 , 0 , input ) ; for ( int y = y0 + 1 ; y < y1 ; y ++ ) { h . updateHistogramY ( 0 , y - y0 , input ) ; h . applyToBlock ( 0 , y , x0 , y + 1 , input , output ) ; } // bottom-left h . updateHistogramY ( 0 , y1 - y0 , input ) ; h . applyToBlock ( 0 , y1 , x0 + 1 , input . height , input , output ) ; // bottom-middle for ( int x = x0 + 1 ; x < x1 ; x ++ ) { h . updateHistogramX ( x - x0 , y1 - y0 , input ) ; h . applyToBlock ( x , y1 , x + 1 , input . height , input , output ) ; } } | Apply around the image border . Use a region that s the full size but apply to all pixels that the region would go outside of it was centered on them . | 518 | 32 |
26,681 | public static PixelTransform < Point2D_F32 > createPixelTransform ( InvertibleTransform transform ) { PixelTransform < Point2D_F32 > pixelTran ; if ( transform instanceof Homography2D_F64 ) { Homography2D_F32 t = ConvertFloatType . convert ( ( Homography2D_F64 ) transform , null ) ; pixelTran = new PixelTransformHomography_F32 ( t ) ; } else if ( transform instanceof Homography2D_F32 ) { pixelTran = new PixelTransformHomography_F32 ( ( Homography2D_F32 ) transform ) ; } else if ( transform instanceof Affine2D_F64 ) { Affine2D_F32 t = UtilAffine . convert ( ( Affine2D_F64 ) transform , null ) ; pixelTran = new PixelTransformAffine_F32 ( t ) ; } else if ( transform instanceof Affine2D_F32 ) { pixelTran = new PixelTransformAffine_F32 ( ( Affine2D_F32 ) transform ) ; } else { throw new RuntimeException ( "Unknown model type" ) ; } return pixelTran ; } | Given a motion model create a PixelTransform used to distort the image | 262 | 13 |
26,682 | public static < T extends ImageGray < T > > OrientationImage < T > sift ( ConfigSiftScaleSpace configSS , ConfigSiftOrientation configOri , Class < T > imageType ) { if ( configSS == null ) configSS = new ConfigSiftScaleSpace ( ) ; configSS . checkValidity ( ) ; OrientationHistogramSift < GrayF32 > ori = FactoryOrientationAlgs . sift ( configOri , GrayF32 . class ) ; SiftScaleSpace ss = new SiftScaleSpace ( configSS . firstOctave , configSS . lastOctave , configSS . numScales , configSS . sigma0 ) ; return new OrientationSiftToImage <> ( ori , ss , imageType ) ; } | Creates an implementation of the SIFT orientation estimation algorithm | 169 | 11 |
26,683 | public static List < Point2D_F64 > gridChess ( int numRows , int numCols , double squareWidth ) { List < Point2D_F64 > all = new ArrayList <> ( ) ; // convert it into the number of calibration points numCols = numCols - 1 ; numRows = numRows - 1 ; // center the grid around the origin. length of a size divided by two double startX = - ( ( numCols - 1 ) * squareWidth ) / 2.0 ; double startY = - ( ( numRows - 1 ) * squareWidth ) / 2.0 ; for ( int i = numRows - 1 ; i >= 0 ; i -- ) { double y = startY + i * squareWidth ; for ( int j = 0 ; j < numCols ; j ++ ) { double x = startX + j * squareWidth ; all . add ( new Point2D_F64 ( x , y ) ) ; } } return all ; } | This target is composed of a checkered chess board like squares . Each corner of an interior square touches an adjacent square but the sides are separated . Only interior square corners provide calibration points . | 219 | 38 |
26,684 | public static < T extends ImageGray < T > > void naiveGradient ( T ii , double tl_x , double tl_y , double samplePeriod , int regionSize , double kernelSize , boolean useHaar , double [ ] derivX , double derivY [ ] ) { SparseScaleGradient < T , ? > gg = SurfDescribeOps . createGradient ( useHaar , ( Class < T > ) ii . getClass ( ) ) ; gg . setWidth ( kernelSize ) ; gg . setImage ( ii ) ; SparseGradientSafe g = new SparseGradientSafe ( gg ) ; // add 0.5 to c_x and c_y to have it round when converted to an integer pixel // this is faster than the straight forward method tl_x += 0.5 ; tl_y += 0.5 ; int i = 0 ; for ( int y = 0 ; y < regionSize ; y ++ ) { for ( int x = 0 ; x < regionSize ; x ++ , i ++ ) { int xx = ( int ) ( tl_x + x * samplePeriod ) ; int yy = ( int ) ( tl_y + y * samplePeriod ) ; GradientValue deriv = g . compute ( xx , yy ) ; derivX [ i ] = deriv . getX ( ) ; derivY [ i ] = deriv . getY ( ) ; // System.out.printf("%2d %2d %2d %2d dx = %6.2f dy = %6.2f\n",x,y,xx,yy,derivX[i],derivY[i]); } } } | Simple algorithm for computing the gradient of a region . Can handle image borders | 368 | 14 |
26,685 | public void setImageGradient ( D derivX , D derivY ) { InputSanityCheck . checkSameShape ( derivX , derivY ) ; if ( derivX . stride != derivY . stride || derivX . startIndex != derivY . startIndex ) throw new IllegalArgumentException ( "stride and start index must be the same" ) ; savedAngle . reshape ( derivX . width , derivX . height ) ; savedMagnitude . reshape ( derivX . width , derivX . height ) ; imageDerivX . wrap ( derivX ) ; imageDerivY . wrap ( derivY ) ; precomputeAngles ( derivX ) ; } | Sets the gradient and precomputes pixel orientation and magnitude | 145 | 12 |
26,686 | public void process ( ) { int width = widthSubregion * widthGrid ; int radius = width / 2 ; int X0 = radius , X1 = savedAngle . width - radius ; int Y0 = radius , Y1 = savedAngle . height - radius ; int numX = ( int ) ( ( X1 - X0 ) / periodColumns ) ; int numY = ( int ) ( ( Y1 - Y0 ) / periodRows ) ; descriptors . reset ( ) ; sampleLocations . reset ( ) ; for ( int i = 0 ; i < numY ; i ++ ) { int y = ( Y1 - Y0 ) * i / ( numY - 1 ) + Y0 ; for ( int j = 0 ; j < numX ; j ++ ) { int x = ( X1 - X0 ) * j / ( numX - 1 ) + X0 ; TupleDesc_F64 desc = descriptors . grow ( ) ; computeDescriptor ( x , y , desc ) ; sampleLocations . grow ( ) . set ( x , y ) ; } } } | Computes SIFT descriptors across the entire image | 237 | 10 |
26,687 | void precomputeAngles ( D image ) { int savecIndex = 0 ; for ( int y = 0 ; y < image . height ; y ++ ) { int pixelIndex = y * image . stride + image . startIndex ; for ( int x = 0 ; x < image . width ; x ++ , pixelIndex ++ , savecIndex ++ ) { float spacialDX = imageDerivX . getF ( pixelIndex ) ; float spacialDY = imageDerivY . getF ( pixelIndex ) ; savedAngle . data [ savecIndex ] = UtilAngle . domain2PI ( Math . atan2 ( spacialDY , spacialDX ) ) ; savedMagnitude . data [ savecIndex ] = ( float ) Math . sqrt ( spacialDX * spacialDX + spacialDY * spacialDY ) ; } } } | Computes the angle of each pixel and its gradient magnitude | 189 | 11 |
26,688 | public void computeDescriptor ( int cx , int cy , TupleDesc_F64 desc ) { desc . fill ( 0 ) ; int widthPixels = widthSubregion * widthGrid ; int radius = widthPixels / 2 ; for ( int i = 0 ; i < widthPixels ; i ++ ) { int angleIndex = ( cy - radius + i ) * savedAngle . width + ( cx - radius ) ; float subY = i / ( float ) widthSubregion ; for ( int j = 0 ; j < widthPixels ; j ++ , angleIndex ++ ) { float subX = j / ( float ) widthSubregion ; double angle = savedAngle . data [ angleIndex ] ; float weightGaussian = gaussianWeight [ i * widthPixels + j ] ; float weightGradient = savedMagnitude . data [ angleIndex ] ; // trilinear interpolation intro descriptor trilinearInterpolation ( weightGaussian * weightGradient , subX , subY , angle , desc ) ; } } normalizeDescriptor ( desc , maxDescriptorElementValue ) ; } | Computes the descriptor centered at the specified coordinate | 239 | 9 |
26,689 | static public void naive4 ( GrayF32 _intensity , GrayS8 direction , GrayF32 output ) { final int w = _intensity . width ; final int h = _intensity . height ; ImageBorder_F32 intensity = ( ImageBorder_F32 ) FactoryImageBorderAlgs . value ( _intensity , 0 ) ; BoofConcurrency . loopFor ( 0 , h , y -> { for ( int x = 0 ; x < w ; x ++ ) { int dir = direction . get ( x , y ) ; int dx , dy ; if ( dir == 0 ) { dx = 1 ; dy = 0 ; } else if ( dir == 1 ) { dx = 1 ; dy = 1 ; } else if ( dir == 2 ) { dx = 0 ; dy = 1 ; } else { dx = 1 ; dy = - 1 ; } float left = intensity . get ( x - dx , y - dy ) ; float middle = intensity . get ( x , y ) ; float right = intensity . get ( x + dx , y + dy ) ; // suppress the value if either of its neighboring values are more than or equal to it if ( left > middle || right > middle ) { output . set ( x , y , 0 ) ; } else { output . set ( x , y , middle ) ; } } } ) ; } | Slow algorithm which processes the whole image . | 281 | 8 |
26,690 | public void reset ( ) { for ( int i = 0 ; i < 4 ; i ++ ) { ppCorner . get ( i ) . set ( 0 , 0 ) ; ppDown . get ( i ) . set ( 0 , 0 ) ; ppRight . get ( i ) . set ( 0 , 0 ) ; } this . threshCorner = 0 ; this . threshDown = 0 ; this . threshRight = 0 ; version = - 1 ; error = L ; mask = QrCodeMaskPattern . M111 ; alignment . reset ( ) ; mode = Mode . UNKNOWN ; failureCause = Failure . NONE ; rawbits = null ; corrected = null ; message = null ; } | Resets the QR - Code so that it s in its initial state . | 148 | 15 |
26,691 | public void set ( QrCode o ) { this . version = o . version ; this . error = o . error ; this . mask = o . mask ; this . mode = o . mode ; this . rawbits = o . rawbits == null ? null : o . rawbits . clone ( ) ; this . corrected = o . corrected == null ? null : o . corrected . clone ( ) ; this . message = o . message ; this . threshCorner = o . threshCorner ; this . threshDown = o . threshDown ; this . threshRight = o . threshRight ; this . ppCorner . set ( o . ppCorner ) ; this . ppDown . set ( o . ppDown ) ; this . ppRight . set ( o . ppRight ) ; this . failureCause = o . failureCause ; this . bounds . set ( o . bounds ) ; this . alignment . reset ( ) ; for ( int i = 0 ; i < o . alignment . size ; i ++ ) { this . alignment . grow ( ) . set ( o . alignment . get ( i ) ) ; } this . Hinv . set ( o . Hinv ) ; } | Sets this so that it s equivalent to o . | 255 | 11 |
26,692 | public static void ensureDeterminantOfOne ( List < Homography2D_F64 > homography0toI ) { int N = homography0toI . size ( ) ; for ( int i = 0 ; i < N ; i ++ ) { Homography2D_F64 H = homography0toI . get ( i ) ; double d = CommonOps_DDF3 . det ( H ) ; // System.out.println("Before = "+d); if ( d < 0 ) CommonOps_DDF3 . divide ( H , - Math . pow ( - d , 1.0 / 3 ) ) ; else CommonOps_DDF3 . divide ( H , Math . pow ( d , 1.0 / 3 ) ) ; // System.out.println("determinant = "+ CommonOps_DDF3.det(H)); } } | Scales all homographies so that their determinants are equal to one | 186 | 14 |
26,693 | private boolean extractCalibration ( DMatrixRMaj x , CameraPinhole calibration ) { double s = x . data [ 5 ] ; double cx = calibration . cx = x . data [ 2 ] / s ; double cy = calibration . cy = x . data [ 4 ] / s ; double fy = calibration . fy = Math . sqrt ( x . data [ 3 ] / s - cy * cy ) ; double sk = calibration . skew = ( x . data [ 1 ] / s - cx * cy ) / fy ; calibration . fx = Math . sqrt ( x . data [ 0 ] / s - sk * sk - cx * cx ) ; if ( calibration . fx < 0 || calibration . fy < 0 ) return false ; if ( UtilEjml . isUncountable ( fy ) || UtilEjml . isUncountable ( calibration . fx ) ) return false ; if ( UtilEjml . isUncountable ( sk ) ) return false ; return true ; } | Extracts camera parameters from the solution . Checks for errors | 222 | 12 |
26,694 | private static WlBorderCoef < WlCoef_F32 > computeBorderCoefficients ( BorderIndex1D border , WlCoef_F32 forward , WlCoef_F32 inverse ) { int N = Math . max ( forward . getScalingLength ( ) , forward . getWaveletLength ( ) ) ; N += N % 2 ; N *= 2 ; border . setLength ( N ) ; // Because the wavelet transform is a linear invertible system the inverse coefficients // can be found by creating a matrix and inverting the matrix. Boundary conditions are then // extracted from this inverted matrix. DMatrixRMaj A = new DMatrixRMaj ( N , N ) ; for ( int i = 0 ; i < N ; i += 2 ) { for ( int j = 0 ; j < forward . scaling . length ; j ++ ) { int index = border . getIndex ( j + i + forward . offsetScaling ) ; A . add ( i , index , forward . scaling [ j ] ) ; } for ( int j = 0 ; j < forward . wavelet . length ; j ++ ) { int index = border . getIndex ( j + i + forward . offsetWavelet ) ; A . add ( i + 1 , index , forward . wavelet [ j ] ) ; } } LinearSolverDense < DMatrixRMaj > solver = LinearSolverFactory_DDRM . linear ( N ) ; if ( ! solver . setA ( A ) || solver . quality ( ) < 1e-5 ) { throw new IllegalArgumentException ( "Can't invert matrix" ) ; } DMatrixRMaj A_inv = new DMatrixRMaj ( N , N ) ; solver . invert ( A_inv ) ; int numBorder = UtilWavelet . borderForwardLower ( inverse ) / 2 ; WlBorderCoefFixed < WlCoef_F32 > ret = new WlBorderCoefFixed <> ( numBorder , numBorder + 1 ) ; ret . setInnerCoef ( inverse ) ; // add the lower coefficients first for ( int i = 0 ; i < ret . getLowerLength ( ) ; i ++ ) { computeLowerCoef ( inverse , A_inv , ret , i * 2 ) ; } // add upper coefficients for ( int i = 0 ; i < ret . getUpperLength ( ) ; i ++ ) { computeUpperCoef ( inverse , N , A_inv , ret , i * 2 ) ; } return ret ; } | Computes inverse coefficients | 551 | 4 |
26,695 | public static WlBorderCoefFixed < WlCoef_I32 > convertToInt ( WlBorderCoefFixed < WlCoef_F32 > orig , WlCoef_I32 inner ) { WlBorderCoefFixed < WlCoef_I32 > ret = new WlBorderCoefFixed <> ( orig . getLowerLength ( ) , orig . getUpperLength ( ) ) ; for ( int i = 0 ; i < orig . getLowerLength ( ) ; i ++ ) { WlCoef_F32 o = orig . getLower ( i ) ; WlCoef_I32 r = new WlCoef_I32 ( ) ; ret . setLower ( i , r ) ; convertCoef_F32_to_I32 ( inner . denominatorScaling , inner . denominatorWavelet , o , r ) ; } for ( int i = 0 ; i < orig . getUpperLength ( ) ; i ++ ) { WlCoef_F32 o = orig . getUpper ( i ) ; WlCoef_I32 r = new WlCoef_I32 ( ) ; ret . setUpper ( i , r ) ; convertCoef_F32_to_I32 ( inner . denominatorScaling , inner . denominatorWavelet , o , r ) ; } ret . setInnerCoef ( inner ) ; return ret ; } | todo rename and move to a utility function? | 311 | 10 |
26,696 | public int updateMixture ( float [ ] pixelValue , float [ ] dataRow , int modelIndex ) { // see which gaussian is the best fit based on Mahalanobis distance int index = modelIndex ; float bestDistance = maxDistance * numBands ; int bestIndex = - 1 ; int ng ; // number of gaussians in use for ( ng = 0 ; ng < maxGaussians ; ng ++ , index += gaussianStride ) { float variance = dataRow [ index + 1 ] ; if ( variance <= 0 ) { break ; } float mahalanobis = 0 ; for ( int i = 0 ; i < numBands ; i ++ ) { float mean = dataRow [ index + 2 + i ] ; float delta = pixelValue [ i ] - mean ; mahalanobis += delta * delta / variance ; } if ( mahalanobis < bestDistance ) { bestDistance = mahalanobis ; bestIndex = index ; } } // Update the model for the best gaussian if ( bestIndex != - 1 ) { // If there is a good fit update the model float weight = dataRow [ bestIndex ] ; float variance = dataRow [ bestIndex + 1 ] ; weight += learningRate * ( 1f - weight ) ; dataRow [ bestIndex ] = 1 ; // set to one so that it can't possible go negative float sumDeltaSq = 0 ; for ( int i = 0 ; i < numBands ; i ++ ) { float mean = dataRow [ bestIndex + 2 + i ] ; float delta = pixelValue [ i ] - mean ; dataRow [ bestIndex + 2 + i ] = mean + delta * learningRate / weight ; sumDeltaSq += delta * delta ; } sumDeltaSq /= numBands ; dataRow [ bestIndex + 1 ] = variance + ( learningRate / weight ) * ( sumDeltaSq * 1.2F - variance ) ; // 1.2f is a fudge factor. Empirical testing shows that the above equation is biased. Can't be bothered // to verify the derivation and see if there's a mistake // Update Gaussian weights and prune models updateWeightAndPrune ( dataRow , modelIndex , ng , bestIndex , weight ) ; return weight >= significantWeight ? 0 : 1 ; } else if ( ng < maxGaussians ) { // if there is no good fit then create a new model, if there is room bestIndex = modelIndex + ng * gaussianStride ; dataRow [ bestIndex ] = 1 ; // weight is changed later or it's the only model dataRow [ bestIndex + 1 ] = initialVariance ; for ( int i = 0 ; i < numBands ; i ++ ) { dataRow [ bestIndex + 2 + i ] = pixelValue [ i ] ; } // There are no models. Return unknown if ( ng == 0 ) return unknownValue ; updateWeightAndPrune ( dataRow , modelIndex , ng + 1 , bestIndex , learningRate ) ; return 1 ; } else { // didn't match any models and can't create a new model return 1 ; } } | Updates the mixtures of gaussian and determines if the pixel matches the background model | 665 | 17 |
26,697 | public void updateWeightAndPrune ( float [ ] dataRow , int modelIndex , int ng , int bestIndex , float bestWeight ) { int index = modelIndex ; float weightTotal = 0 ; for ( int i = 0 ; i < ng ; ) { float weight = dataRow [ index ] ; // if( ng > 1 ) // System.out.println("["+i+"] = "+ng+" weight "+weight); weight = weight - learningRate * ( weight + decay ) ; // <-- original equation // weight = weight - learningRate*decay; if ( weight <= 0 ) { // copy the last Gaussian into this location int indexLast = modelIndex + ( ng - 1 ) * gaussianStride ; for ( int j = 0 ; j < gaussianStride ; j ++ ) { dataRow [ index + j ] = dataRow [ indexLast + j ] ; } // see if the best Gaussian just got moved to here if ( indexLast == bestIndex ) bestIndex = index ; // mark it as unused by setting variance to zero dataRow [ indexLast + 1 ] = 0 ; // decrease the number of gaussians ng -= 1 ; } else { dataRow [ index ] = weight ; weightTotal += weight ; index += gaussianStride ; i ++ ; } } // undo the change to the best model. It was done in the for loop to avoid an if statement which would // have slowed it down if ( bestIndex != - 1 ) { weightTotal -= dataRow [ bestIndex ] ; weightTotal += bestWeight ; dataRow [ bestIndex ] = bestWeight ; } // Normalize the weight so that it sums up to one index = modelIndex ; for ( int i = 0 ; i < ng ; i ++ , index += gaussianStride ) { dataRow [ index ] /= weightTotal ; } } | Updates the weight of each Gaussian and prunes one which have a negative weight after the update . | 392 | 21 |
26,698 | public int checkBackground ( float [ ] pixelValue , float [ ] dataRow , int modelIndex ) { // see which gaussian is the best fit based on Mahalanobis distance int index = modelIndex ; float bestDistance = maxDistance * numBands ; float bestWeight = 0 ; int ng ; // number of gaussians in use for ( ng = 0 ; ng < maxGaussians ; ng ++ , index += gaussianStride ) { float variance = dataRow [ index + 1 ] ; if ( variance <= 0 ) { break ; } float mahalanobis = 0 ; for ( int i = 0 ; i < numBands ; i ++ ) { float mean = dataRow [ index + 2 + i ] ; float delta = pixelValue [ i ] - mean ; mahalanobis += delta * delta / variance ; } if ( mahalanobis < bestDistance ) { bestDistance = mahalanobis ; bestWeight = dataRow [ index ] ; } } if ( ng == 0 ) // There are no models. Return unknown return unknownValue ; return bestWeight >= significantWeight ? 0 : 1 ; } | Checks to see if the the pivel value refers to the background or foreground | 238 | 17 |
26,699 | public static < T extends ImageGray < T > > T yuvToGray ( ByteBuffer bufferY , int width , int height , int strideRow , T output , BWorkArrays workArrays , Class < T > outputType ) { if ( outputType == GrayU8 . class ) { return ( T ) yuvToGray ( bufferY , width , height , strideRow , ( GrayU8 ) output ) ; } else if ( outputType == GrayF32 . class ) { return ( T ) yuvToGray ( bufferY , width , height , strideRow , ( GrayF32 ) output , workArrays ) ; } else { throw new IllegalArgumentException ( "Unsupported BoofCV Image Type " + outputType . getSimpleName ( ) ) ; } } | Converts an YUV 420 888 into gray | 167 | 10 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.