idx
int64
0
165k
question
stringlengths
73
4.15k
target
stringlengths
5
918
len_question
int64
21
890
len_target
int64
3
255
27,600
public void writeOverSet ( int which , List < Point2D_I32 > points ) { BlockIndexLength set = sets . get ( which ) ; if ( set . length != points . size ( ) ) throw new IllegalArgumentException ( "points and set don't have the same length" ) ; for ( int i = 0 ; i < set . length ; i ++ ) { int index = set . start + i * 2 ; int blockIndex = set . block + index / blockLength ; index %= blockLength ; Point2D_I32 p = points . get ( i ) ; int block [ ] = blocks . get ( blockIndex ) ; block [ index ] = p . x ; block [ index + 1 ] = p . y ; } }
Overwrites the points in the set with the list of points .
162
14
27,601
public void viewUpdated ( ) { BufferedImage active = null ; if ( controls . selectedView == 0 ) { active = original ; } else if ( controls . selectedView == 1 ) { synchronized ( lockProcessing ) { VisualizeBinaryData . renderBinary ( detector . getBinary ( ) , false , work ) ; } active = work ; work . setRGB ( 0 , 0 , work . getRGB ( 0 , 0 ) ) ; // hack so that Swing knows it's been modified } else { Graphics2D g2 = work . createGraphics ( ) ; g2 . setColor ( Color . BLACK ) ; g2 . fillRect ( 0 , 0 , work . getWidth ( ) , work . getHeight ( ) ) ; active = work ; } guiImage . setBufferedImage ( active ) ; guiImage . setScale ( controls . zoom ) ; guiImage . repaint ( ) ; }
Called when how the data is visualized has changed
193
11
27,602
void disconnectSingleConnections ( ) { List < SquareNode > open = new ArrayList <> ( ) ; List < SquareNode > open2 = new ArrayList <> ( ) ; for ( int i = 0 ; i < nodes . size ( ) ; i ++ ) { SquareNode n = nodes . get ( i ) ; checkDisconnectSingleEdge ( open , n ) ; } while ( ! open . isEmpty ( ) ) { for ( int i = 0 ; i < open . size ( ) ; i ++ ) { SquareNode n = open . get ( i ) ; checkDisconnectSingleEdge ( open2 , n ) ; open . clear ( ) ; List < SquareNode > tmp = open ; open = open2 ; open2 = tmp ; } } }
Nodes that have only a single connection to one other node are disconnected since they are likely to be noise . This is done recursively
162
28
27,603
boolean areMiddlePointsClose ( Point2D_F64 p0 , Point2D_F64 p1 , Point2D_F64 p2 , Point2D_F64 p3 ) { UtilLine2D_F64 . convert ( p0 , p3 , line ) ; // (computed expected length of a square) * (fractional tolerance) double tol1 = p0 . distance ( p1 ) * distanceTol ; // see if inner points are close to the line if ( Distance2D_F64 . distance ( line , p1 ) > tol1 ) return false ; double tol2 = p2 . distance ( p3 ) * distanceTol ; if ( Distance2D_F64 . distance ( lineB , p2 ) > tol2 ) return false ; //------------ Now see if the line defined by one side of a square is close to the closest point on the same // side on the other square UtilLine2D_F64 . convert ( p0 , p1 , line ) ; if ( Distance2D_F64 . distance ( line , p2 ) > tol2 ) return false ; UtilLine2D_F64 . convert ( p3 , p2 , line ) ; if ( Distance2D_F64 . distance ( line , p1 ) > tol1 ) return false ; return true ; }
Returns true if point p1 and p2 are close to the line defined by points p0 and p3 .
297
23
27,604
public boolean process ( T left , T right ) { // System.out.println("----------- Process --------------"); this . inputLeft = left ; this . inputRight = right ; tick ++ ; trackerLeft . process ( left ) ; trackerRight . process ( right ) ; if ( first ) { addNewTracks ( ) ; first = false ; } else { mutualTrackDrop ( ) ; selectCandidateTracks ( ) ; boolean failed = ! estimateMotion ( ) ; dropUnusedTracks ( ) ; if ( failed ) return false ; int N = matcher . getMatchSet ( ) . size ( ) ; if ( modelRefiner != null ) refineMotionEstimate ( ) ; if ( thresholdAdd <= 0 || N < thresholdAdd ) { changePoseToReference ( ) ; addNewTracks ( ) ; } } return true ; }
Updates motion estimate using the stereo pair .
178
9
27,605
private void refineMotionEstimate ( ) { // use observations from the inlier set List < Stereo2D3D > data = new ArrayList <> ( ) ; int N = matcher . getMatchSet ( ) . size ( ) ; for ( int i = 0 ; i < N ; i ++ ) { int index = matcher . getInputIndex ( i ) ; PointTrack l = candidates . get ( index ) ; LeftTrackInfo info = l . getCookie ( ) ; PointTrack r = info . right ; Stereo2D3D stereo = info . location ; // compute normalized image coordinate for track in left and right image leftImageToNorm . compute ( l . x , l . y , info . location . leftObs ) ; rightImageToNorm . compute ( r . x , r . y , info . location . rightObs ) ; data . add ( stereo ) ; } // refine the motion estimate using non-linear optimization Se3_F64 keyToCurr = currToKey . invert ( null ) ; Se3_F64 found = new Se3_F64 ( ) ; if ( modelRefiner . fitModel ( data , keyToCurr , found ) ) { found . invert ( currToKey ) ; } }
Non - linear refinement of motion estimate
270
7
27,606
private boolean estimateMotion ( ) { // organize the data List < Stereo2D3D > data = new ArrayList <> ( ) ; for ( PointTrack l : candidates ) { LeftTrackInfo info = l . getCookie ( ) ; PointTrack r = info . right ; Stereo2D3D stereo = info . location ; // compute normalized image coordinate for track in left and right image leftImageToNorm . compute ( l . x , l . y , info . location . leftObs ) ; rightImageToNorm . compute ( r . x , r . y , info . location . rightObs ) ; data . add ( stereo ) ; } // Robustly estimate left camera motion if ( ! matcher . process ( data ) ) return false ; Se3_F64 keyToCurr = matcher . getModelParameters ( ) ; keyToCurr . invert ( currToKey ) ; // mark tracks that are in the inlier set int N = matcher . getMatchSet ( ) . size ( ) ; for ( int i = 0 ; i < N ; i ++ ) { int index = matcher . getInputIndex ( i ) ; LeftTrackInfo info = candidates . get ( index ) . getCookie ( ) ; info . lastInlier = tick ; } // System.out.println("Inlier set size: "+N); return true ; }
Given the set of active tracks estimate the cameras motion robustly
293
12
27,607
private void mutualTrackDrop ( ) { for ( PointTrack t : trackerLeft . getDroppedTracks ( null ) ) { LeftTrackInfo info = t . getCookie ( ) ; trackerRight . dropTrack ( info . right ) ; } for ( PointTrack t : trackerRight . getDroppedTracks ( null ) ) { RightTrackInfo info = t . getCookie ( ) ; // a track could be dropped twice here, such requests are ignored by the tracker trackerLeft . dropTrack ( info . left ) ; } }
If a track was dropped in one image make sure it was dropped in the other image
113
17
27,608
private void selectCandidateTracks ( ) { // mark tracks in right frame that are active List < PointTrack > activeRight = trackerRight . getActiveTracks ( null ) ; for ( PointTrack t : activeRight ) { RightTrackInfo info = t . getCookie ( ) ; info . lastActiveList = tick ; } int mutualActive = 0 ; List < PointTrack > activeLeft = trackerLeft . getActiveTracks ( null ) ; candidates . clear ( ) ; for ( PointTrack left : activeLeft ) { LeftTrackInfo info = left . getCookie ( ) ; // if( info == null || info.right == null ) { // System.out.println("Oh Crap"); // } // for each active left track, see if its right track has been marked as active RightTrackInfo infoRight = info . right . getCookie ( ) ; if ( infoRight . lastActiveList != tick ) { continue ; } // check epipolar constraint and see if it is still valid if ( stereoCheck . checkPixel ( left , info . right ) ) { info . lastConsistent = tick ; candidates . add ( left ) ; } mutualActive ++ ; } // System.out.println("Active Tracks: Left "+trackerLeft.getActiveTracks(null).size()+" right "+ // trackerRight.getActiveTracks(null).size()); // System.out.println("All Tracks: Left "+trackerLeft.getAllTracks(null).size()+" right "+ // trackerRight.getAllTracks(null).size()); // System.out.println("Candidates = "+candidates.size()+" mutual active = "+mutualActive); }
Searches for tracks which are active and meet the epipolar constraints
359
14
27,609
public void createImages ( ) { image = UtilImageIO . loadImage ( UtilIO . pathExample ( "standard/barbara.jpg" ) ) ; gray = ConvertBufferedImage . convertFromSingle ( image , null , GrayU8 . class ) ; derivX = GeneralizedImageOps . createSingleBand ( GrayS16 . class , gray . getWidth ( ) , gray . getHeight ( ) ) ; derivY = GeneralizedImageOps . createSingleBand ( GrayS16 . class , gray . getWidth ( ) , gray . getHeight ( ) ) ; GImageDerivativeOps . gradient ( DerivativeType . SOBEL , gray , derivX , derivY , BorderType . EXTENDED ) ; }
Load and generate images
157
4
27,610
public static void fillRectangle ( InterleavedS32 img , int value , int x0 , int y0 , int width , int height ) { int x1 = x0 + width ; int y1 = y0 + height ; if ( x0 < 0 ) x0 = 0 ; if ( x1 > img . width ) x1 = img . width ; if ( y0 < 0 ) y0 = 0 ; if ( y1 > img . height ) y1 = img . height ; int length = ( x1 - x0 ) * img . numBands ; for ( int y = y0 ; y < y1 ; y ++ ) { int index = img . startIndex + y * img . stride + x0 * img . numBands ; int indexEnd = index + length ; while ( index < indexEnd ) { img . data [ index ++ ] = value ; } } }
Draws a filled rectangle that is aligned along the image axis inside the image . All bands are filled with the same value .
192
25
27,611
public static void flipVertical ( GrayS32 input ) { int h2 = input . height / 2 ; for ( int y = 0 ; y < h2 ; y ++ ) { int index1 = input . getStartIndex ( ) + y * input . getStride ( ) ; int index2 = input . getStartIndex ( ) + ( input . height - y - 1 ) * input . getStride ( ) ; int end = index1 + input . width ; while ( index1 < end ) { int tmp = input . data [ index1 ] ; input . data [ index1 ++ ] = input . data [ index2 ] ; input . data [ index2 ++ ] = ( int ) tmp ; } } }
Flips the image from top to bottom
154
8
27,612
public static void flipHorizontal ( GrayS32 input ) { int w2 = input . width / 2 ; for ( int y = 0 ; y < input . height ; y ++ ) { int index1 = input . getStartIndex ( ) + y * input . getStride ( ) ; int index2 = index1 + input . width - 1 ; int end = index1 + w2 ; while ( index1 < end ) { int tmp = input . data [ index1 ] ; input . data [ index1 ++ ] = input . data [ index2 ] ; input . data [ index2 -- ] = ( int ) tmp ; } } }
Flips the image from left to right
137
8
27,613
public static void rotateCCW ( GrayS64 image ) { if ( image . width != image . height ) throw new IllegalArgumentException ( "Image must be square" ) ; int w = image . height / 2 + image . height % 2 ; int h = image . height / 2 ; for ( int y0 = 0 ; y0 < h ; y0 ++ ) { int y1 = image . height - y0 - 1 ; for ( int x0 = 0 ; x0 < w ; x0 ++ ) { int x1 = image . width - x0 - 1 ; int index0 = image . startIndex + y0 * image . stride + x0 ; int index1 = image . startIndex + x0 * image . stride + y1 ; int index2 = image . startIndex + y1 * image . stride + x1 ; int index3 = image . startIndex + x1 * image . stride + y0 ; long tmp0 = image . data [ index0 ] ; image . data [ index0 ] = image . data [ index1 ] ; image . data [ index1 ] = image . data [ index2 ] ; image . data [ index2 ] = image . data [ index3 ] ; image . data [ index3 ] = ( long ) tmp0 ; } } }
In - place 90 degree image rotation in the counter - clockwise direction . Only works on square images .
277
21
27,614
public static void rotateCCW ( GrayS64 input , GrayS64 output ) { if ( input . width != output . height || input . height != output . width ) throw new IllegalArgumentException ( "Incompatible shapes" ) ; int w = input . width - 1 ; for ( int y = 0 ; y < input . height ; y ++ ) { int indexIn = input . startIndex + y * input . stride ; for ( int x = 0 ; x < input . width ; x ++ ) { output . unsafe_set ( y , w - x , input . data [ indexIn ++ ] ) ; } } }
Rotates the image 90 degrees in the counter - clockwise direction .
133
14
27,615
public static void fillBand ( InterleavedF64 input , int band , double value ) { final int numBands = input . numBands ; for ( int y = 0 ; y < input . height ; y ++ ) { int index = input . getStartIndex ( ) + y * input . getStride ( ) + band ; int end = index + input . width * numBands - band ; for ( ; index < end ; index += numBands ) { input . data [ index ] = value ; } } }
Fills one band in the image with the specified value
113
11
27,616
public static void fillBorder ( GrayF64 input , double value , int radius ) { // top and bottom for ( int y = 0 ; y < radius ; y ++ ) { int indexTop = input . startIndex + y * input . stride ; int indexBottom = input . startIndex + ( input . height - y - 1 ) * input . stride ; for ( int x = 0 ; x < input . width ; x ++ ) { input . data [ indexTop ++ ] = value ; input . data [ indexBottom ++ ] = value ; } } // left and right int h = input . height - radius ; int indexStart = input . startIndex + radius * input . stride ; for ( int x = 0 ; x < radius ; x ++ ) { int indexLeft = indexStart + x ; int indexRight = indexStart + input . width - 1 - x ; for ( int y = radius ; y < h ; y ++ ) { input . data [ indexLeft ] = value ; input . data [ indexRight ] = value ; indexLeft += input . stride ; indexRight += input . stride ; } } }
Fills the outside border with the specified value
235
9
27,617
public static void fillRectangle ( GrayF64 img , double value , int x0 , int y0 , int width , int height ) { int x1 = x0 + width ; int y1 = y0 + height ; if ( x0 < 0 ) x0 = 0 ; if ( x1 > img . width ) x1 = img . width ; if ( y0 < 0 ) y0 = 0 ; if ( y1 > img . height ) y1 = img . height ; for ( int y = y0 ; y < y1 ; y ++ ) { for ( int x = x0 ; x < x1 ; x ++ ) { img . set ( x , y , value ) ; } } }
Draws a filled rectangle that is aligned along the image axis inside the image .
152
16
27,618
public static RectangleLength2D_F32 boundBoxInside ( int srcWidth , int srcHeight , PixelTransform < Point2D_F32 > transform , Point2D_F32 work ) { List < Point2D_F32 > points = computeBoundingPoints ( srcWidth , srcHeight , transform , work ) ; Point2D_F32 center = new Point2D_F32 ( ) ; UtilPoint2D_F32 . mean ( points , center ) ; float x0 , x1 , y0 , y1 ; x0 = y0 = Float . MAX_VALUE ; x1 = y1 = - Float . MAX_VALUE ; for ( int i = 0 ; i < points . size ( ) ; i ++ ) { Point2D_F32 p = points . get ( i ) ; if ( p . x < x0 ) x0 = p . x ; if ( p . x > x1 ) x1 = p . x ; if ( p . y < y0 ) y0 = p . y ; if ( p . y > y1 ) y1 = p . y ; } x0 -= center . x ; x1 -= center . x ; y0 -= center . y ; y1 -= center . y ; float ox0 = x0 ; float oy0 = y0 ; float ox1 = x1 ; float oy1 = y1 ; for ( int i = 0 ; i < points . size ( ) ; i ++ ) { Point2D_F32 p = points . get ( i ) ; float dx = p . x - center . x ; float dy = p . y - center . y ; // see if the point is inside the box if ( dx > x0 && dy > y0 && dx < x1 && dy < y1 ) { // find smallest reduction in side length and closest to original rectangle float d0 = ( float ) ( float ) Math . abs ( dx - x0 ) + x0 - ox0 ; float d1 = ( float ) ( float ) Math . abs ( dx - x1 ) + ox1 - x1 ; float d2 = ( float ) ( float ) Math . abs ( dy - y0 ) + y0 - oy0 ; float d3 = ( float ) ( float ) Math . abs ( dy - y1 ) + oy1 - y1 ; if ( d0 <= d1 && d0 <= d2 && d0 <= d3 ) { x0 = dx ; } else if ( d1 <= d2 && d1 <= d3 ) { x1 = dx ; } else if ( d2 <= d3 ) { y0 = dy ; } else { y1 = dy ; } } } return new RectangleLength2D_F32 ( x0 + center . x , y0 + center . y , x1 - x0 , y1 - y0 ) ; }
Ensures that the entire box will be inside
615
10
27,619
public void initialize ( T image , RectangleRotate_F32 initial ) { this . region . set ( initial ) ; calcHistogram . computeHistogram ( image , initial ) ; System . arraycopy ( calcHistogram . getHistogram ( ) , 0 , keyHistogram , 0 , keyHistogram . length ) ; this . minimumWidth = initial . width * minimumSizeRatio ; }
Specifies the initial image to learn the target description
84
10
27,620
public void track ( T image ) { // configure the different regions based on size region0 . set ( region ) ; region1 . set ( region ) ; region2 . set ( region ) ; region0 . width *= 1 - scaleChange ; region0 . height *= 1 - scaleChange ; region2 . width *= 1 + scaleChange ; region2 . height *= 1 + scaleChange ; // distance from histogram double distance0 = 1 , distance1 , distance2 = 1 ; // perform mean-shift at the different sizes and compute their distance if ( ! constantScale ) { if ( region0 . width >= minimumWidth ) { updateLocation ( image , region0 ) ; distance0 = distanceHistogram ( keyHistogram , calcHistogram . getHistogram ( ) ) ; if ( updateHistogram ) System . arraycopy ( calcHistogram . getHistogram ( ) , 0 , histogram0 , 0 , histogram0 . length ) ; } updateLocation ( image , region2 ) ; distance2 = distanceHistogram ( keyHistogram , calcHistogram . getHistogram ( ) ) ; if ( updateHistogram ) System . arraycopy ( calcHistogram . getHistogram ( ) , 0 , histogram2 , 0 , histogram2 . length ) ; } // update the no scale change hypothesis updateLocation ( image , region1 ) ; if ( ! constantScale ) { distance1 = distanceHistogram ( keyHistogram , calcHistogram . getHistogram ( ) ) ; } else { // force it to select distance1 = 0 ; } if ( updateHistogram ) System . arraycopy ( calcHistogram . getHistogram ( ) , 0 , histogram1 , 0 , histogram1 . length ) ; RectangleRotate_F32 selected = null ; float selectedHist [ ] = null ; switch ( selectBest ( distance0 , distance1 , distance2 ) ) { case 0 : selected = region0 ; selectedHist = histogram0 ; break ; case 1 : selected = region1 ; selectedHist = histogram1 ; break ; case 2 : selected = region2 ; selectedHist = histogram2 ; break ; default : throw new RuntimeException ( "Bug in selectBest" ) ; } // Set region to the best scale, but reduce sensitivity by weighting it against the original size // equation 14 float w = selected . width * ( 1 - gamma ) + gamma * region . width ; float h = selected . height * ( 1 - gamma ) + gamma * region . height ; region . set ( selected ) ; region . width = w ; region . height = h ; if ( updateHistogram ) { System . arraycopy ( selectedHist , 0 , keyHistogram , 0 , keyHistogram . length ) ; } }
Searches for the target in the most recent image .
578
12
27,621
private int selectBest ( double a , double b , double c ) { if ( a < b ) { if ( a < c ) return 0 ; else return 2 ; } else if ( b <= c ) { return 1 ; } else { return 2 ; } }
Given the 3 scores return the index of the best
55
10
27,622
protected void updateLocation ( T image , RectangleRotate_F32 region ) { double bestHistScore = Double . MAX_VALUE ; float bestX = - 1 , bestY = - 1 ; for ( int i = 0 ; i < maxIterations ; i ++ ) { calcHistogram . computeHistogram ( image , region ) ; float histogram [ ] = calcHistogram . getHistogram ( ) ; updateWeights ( histogram ) ; // the histogram fit doesn't always improve with each mean-shift iteration // save the best one and use it later on double histScore = distanceHistogram ( keyHistogram , histogram ) ; if ( histScore < bestHistScore ) { bestHistScore = histScore ; bestX = region . cx ; bestY = region . cy ; } List < Point2D_F32 > samples = calcHistogram . getSamplePts ( ) ; int sampleHistIndex [ ] = calcHistogram . getSampleHistIndex ( ) ; // Compute equation 13 float meanX = 0 ; float meanY = 0 ; float totalWeight = 0 ; for ( int j = 0 ; j < samples . size ( ) ; j ++ ) { Point2D_F32 samplePt = samples . get ( j ) ; int histIndex = sampleHistIndex [ j ] ; if ( histIndex < 0 ) continue ; // compute the weight derived from the Bhattacharyya coefficient. Equation 10. float w = weightHistogram [ histIndex ] ; meanX += w * samplePt . x ; meanY += w * samplePt . y ; totalWeight += w ; } meanX /= totalWeight ; meanY /= totalWeight ; // convert to image pixels calcHistogram . squareToImageSample ( meanX , meanY , region ) ; meanX = calcHistogram . imageX ; meanY = calcHistogram . imageY ; // see if the change is below the threshold boolean done = Math . abs ( meanX - region . cx ) <= minimumChange && Math . abs ( meanY - region . cy ) <= minimumChange ; region . cx = meanX ; region . cy = meanY ; if ( done ) { break ; } } // use the best location found region . cx = bestX ; region . cy = bestY ; }
Updates the region s location using the standard mean - shift algorithm
488
13
27,623
private void updateWeights ( float [ ] histogram ) { for ( int j = 0 ; j < weightHistogram . length ; j ++ ) { float h = histogram [ j ] ; if ( h != 0 ) { weightHistogram [ j ] = ( float ) Math . sqrt ( keyHistogram [ j ] / h ) ; } } }
Update the weights for each element in the histogram . Weights are used to favor colors which are less than expected .
76
24
27,624
protected double distanceHistogram ( float histogramA [ ] , float histogramB [ ] ) { double sumP = 0 ; for ( int i = 0 ; i < histogramA . length ; i ++ ) { float q = histogramA [ i ] ; float p = histogramB [ i ] ; sumP += Math . abs ( q - p ) ; } return sumP ; }
Computes the difference between two histograms using SAD .
84
12
27,625
public void setImageGradient ( Deriv derivX , Deriv derivY ) { this . imageDerivX . wrap ( derivX ) ; this . imageDerivY . wrap ( derivY ) ; }
Sets the image spacial derivatives . These should be computed from an image at the appropriate scale in scale - space .
45
24
27,626
public void process ( double c_x , double c_y , double sigma , double orientation , TupleDesc_F64 descriptor ) { descriptor . fill ( 0 ) ; computeRawDescriptor ( c_x , c_y , sigma , orientation , descriptor ) ; normalizeDescriptor ( descriptor , maxDescriptorElementValue ) ; }
Computes the SIFT descriptor for the specified key point
76
11
27,627
void computeRawDescriptor ( double c_x , double c_y , double sigma , double orientation , TupleDesc_F64 descriptor ) { double c = Math . cos ( orientation ) ; double s = Math . sin ( orientation ) ; float fwidthSubregion = widthSubregion ; int sampleWidth = widthGrid * widthSubregion ; double sampleRadius = sampleWidth / 2 ; double sampleToPixels = sigma * sigmaToPixels ; Deriv image = ( Deriv ) imageDerivX . getImage ( ) ; for ( int sampleY = 0 ; sampleY < sampleWidth ; sampleY ++ ) { float subY = sampleY / fwidthSubregion ; double y = sampleToPixels * ( sampleY - sampleRadius ) ; for ( int sampleX = 0 ; sampleX < sampleWidth ; sampleX ++ ) { // coordinate of samples in terms of sub-region. Center of sample point, hence + 0.5f float subX = sampleX / fwidthSubregion ; // recentered local pixel sample coordinate double x = sampleToPixels * ( sampleX - sampleRadius ) ; // pixel coordinate in the image that is to be sampled. Note the rounding // If the pixel coordinate is -1 < x < 0 then it will round to 0 instead of -1, but the rounding // method below is WAY faster than Math.round() so this is a small loss. int pixelX = ( int ) ( x * c - y * s + c_x + 0.5 ) ; int pixelY = ( int ) ( x * s + y * c + c_y + 0.5 ) ; // skip pixels outside of the image if ( image . isInBounds ( pixelX , pixelY ) ) { // spacial image derivative at this point float spacialDX = imageDerivX . unsafe_getF ( pixelX , pixelY ) ; float spacialDY = imageDerivY . unsafe_getF ( pixelX , pixelY ) ; double adjDX = c * spacialDX + s * spacialDY ; double adjDY = - s * spacialDX + c * spacialDY ; double angle = UtilAngle . domain2PI ( Math . atan2 ( adjDY , adjDX ) ) ; float weightGaussian = gaussianWeight [ sampleY * sampleWidth + sampleX ] ; float weightGradient = ( float ) Math . sqrt ( spacialDX * spacialDX + spacialDY * spacialDY ) ; // trilinear interpolation intro descriptor trilinearInterpolation ( weightGaussian * weightGradient , subX , subY , angle , descriptor ) ; } } } }
Computes the descriptor by sampling the input image . This is raw because the descriptor hasn t been massaged yet .
582
23
27,628
public static void normalizeDescriptor ( TupleDesc_F64 descriptor , double maxDescriptorElementValue ) { // normalize descriptor to unit length UtilFeature . normalizeL2 ( descriptor ) ; // clip the values for ( int i = 0 ; i < descriptor . size ( ) ; i ++ ) { double value = descriptor . value [ i ] ; if ( value > maxDescriptorElementValue ) { descriptor . value [ i ] = maxDescriptorElementValue ; } } // normalize again UtilFeature . normalizeL2 ( descriptor ) ; }
Adjusts the descriptor . This adds lighting invariance and reduces the affects of none - affine changes in lighting .
123
23
27,629
protected static float [ ] createGaussianWeightKernel ( double sigma , int radius ) { Kernel2D_F32 ker = FactoryKernelGaussian . gaussian2D_F32 ( sigma , radius , false , false ) ; float maxValue = KernelMath . maxAbs ( ker . data , 4 * radius * radius ) ; KernelMath . divide ( ker , maxValue ) ; return ker . data ; }
Creates a gaussian weighting kernel with an even number of elements along its width
90
17
27,630
protected void trilinearInterpolation ( float weight , float sampleX , float sampleY , double angle , TupleDesc_F64 descriptor ) { for ( int i = 0 ; i < widthGrid ; i ++ ) { double weightGridY = 1.0 - Math . abs ( sampleY - i ) ; if ( weightGridY <= 0 ) continue ; for ( int j = 0 ; j < widthGrid ; j ++ ) { double weightGridX = 1.0 - Math . abs ( sampleX - j ) ; if ( weightGridX <= 0 ) continue ; for ( int k = 0 ; k < numHistogramBins ; k ++ ) { double angleBin = k * histogramBinWidth ; double weightHistogram = 1.0 - UtilAngle . dist ( angle , angleBin ) / histogramBinWidth ; if ( weightHistogram <= 0 ) continue ; int descriptorIndex = ( i * widthGrid + j ) * numHistogramBins + k ; descriptor . value [ descriptorIndex ] += weight * weightGridX * weightGridY * weightHistogram ; } } } }
Applies trilinear interpolation across the descriptor
241
11
27,631
private void computeFeatureMask ( int numModules , int [ ] alignment , boolean hasVersion ) { // mark alignment patterns + format info markSquare ( 0 , 0 , 9 ) ; markRectangle ( numModules - 8 , 0 , 9 , 8 ) ; markRectangle ( 0 , numModules - 8 , 8 , 9 ) ; // timing pattern markRectangle ( 8 , 6 , 1 , numModules - 8 - 8 ) ; markRectangle ( 6 , 8 , numModules - 8 - 8 , 1 ) ; // version info if ( hasVersion ) { markRectangle ( numModules - 11 , 0 , 6 , 3 ) ; markRectangle ( 0 , numModules - 11 , 3 , 6 ) ; } // alignment patterns for ( int i = 0 ; i < alignment . length ; i ++ ) { int row = alignment [ i ] ; for ( int j = 0 ; j < alignment . length ; j ++ ) { if ( i == 0 & j == 0 ) continue ; if ( i == alignment . length - 1 & j == 0 ) continue ; if ( i == 0 & j == alignment . length - 1 ) continue ; int col = alignment [ j ] ; markSquare ( row - 2 , col - 2 , 5 ) ; } } }
Blocks out the location of features in the image . Needed for codeworld location extraction
271
17
27,632
private void computeBitLocations ( ) { int N = numRows ; int row = N - 1 ; int col = N - 1 ; int direction = - 1 ; while ( col > 0 ) { if ( col == 6 ) col -= 1 ; if ( ! get ( row , col ) ) { bits . add ( new Point2D_I32 ( col , row ) ) ; } if ( ! get ( row , col - 1 ) ) { bits . add ( new Point2D_I32 ( col - 1 , row ) ) ; } row += direction ; if ( row < 0 || row >= N ) { direction = - direction ; col -= 2 ; row += direction ; } } }
Snakes through and specifies the location of each bit for all the code words in the grid .
148
19
27,633
public static void drawRectangle ( Rectangle2D_I32 rect , Graphics2D g2 ) { g2 . drawLine ( rect . x0 , rect . y0 , rect . x1 , rect . y0 ) ; g2 . drawLine ( rect . x1 , rect . y0 , rect . x1 , rect . y1 ) ; g2 . drawLine ( rect . x0 , rect . y1 , rect . x1 , rect . y1 ) ; g2 . drawLine ( rect . x0 , rect . y1 , rect . x0 , rect . y0 ) ; }
Draws an axis aligned rectangle
132
6
27,634
public static SteerableCoefficients polynomial ( int order ) { if ( order == 1 ) return new PolyOrder1 ( ) ; else if ( order == 2 ) return new PolyOrder2 ( ) ; else if ( order == 3 ) return new PolyOrder3 ( ) ; else if ( order == 4 ) return new PolyOrder4 ( ) ; else throw new IllegalArgumentException ( "Only supports orders 1 to 4" ) ; }
Coefficients for even or odd parity polynomials .
95
14
27,635
private void pruneMatches ( ) { int index = 0 ; while ( index < matches . size ) { AssociatedTripleIndex a = matches . get ( index ) ; // not matched. Remove it from the list by copying that last element over it if ( a . c == - 1 ) { a . set ( matches . get ( matches . size - 1 ) ) ; matches . size -- ; } else { index ++ ; } } }
Removes by swapping all elements with a c index of - 1
92
13
27,636
public void setNumberControl ( int numControl ) { this . numControl = numControl ; if ( numControl == 4 ) { x0 . reshape ( 10 , 1 , false ) ; AA . reshape ( 10 , 9 , false ) ; yy . reshape ( 10 , 1 , false ) ; xx . reshape ( 9 , 1 , false ) ; numNull = 3 ; } else { x0 . reshape ( 6 , 1 , false ) ; AA . reshape ( 4 , 2 , false ) ; yy . reshape ( 4 , 1 , false ) ; xx . reshape ( 2 , 1 , false ) ; numNull = 1 ; } int index = 0 ; for ( int i = 0 ; i < numControl ; i ++ ) { for ( int j = i ; j < numControl ; j ++ ) { table [ i * numControl + j ] = table [ j * numControl + i ] = index ++ ; } } }
Specified the number of control points .
204
8
27,637
public void process ( DMatrixRMaj L_full , DMatrixRMaj y , double betas [ ] ) { svd . decompose ( L_full ) ; // extract null space V = svd . getV ( null , true ) ; // compute one possible solution pseudo . setA ( L_full ) ; pseudo . solve ( y , x0 ) ; // add additional constraints to reduce the number of possible solutions DMatrixRMaj alphas = solveConstraintMatrix ( ) ; // compute the final solution for ( int i = 0 ; i < x0 . numRows ; i ++ ) { for ( int j = 0 ; j < numNull ; j ++ ) { x0 . data [ i ] += alphas . data [ j ] * valueNull ( j , i ) ; } } if ( numControl == 4 ) { betas [ 0 ] = Math . sqrt ( Math . abs ( x0 . data [ 0 ] ) ) ; betas [ 1 ] = Math . sqrt ( Math . abs ( x0 . data [ 4 ] ) ) * Math . signum ( x0 . data [ 1 ] ) ; betas [ 2 ] = Math . sqrt ( Math . abs ( x0 . data [ 7 ] ) ) * Math . signum ( x0 . data [ 2 ] ) ; betas [ 3 ] = Math . sqrt ( Math . abs ( x0 . data [ 9 ] ) ) * Math . signum ( x0 . data [ 3 ] ) ; } else { betas [ 0 ] = Math . sqrt ( Math . abs ( x0 . data [ 0 ] ) ) ; betas [ 1 ] = Math . sqrt ( Math . abs ( x0 . data [ 3 ] ) ) * Math . signum ( x0 . data [ 1 ] ) ; betas [ 2 ] = Math . sqrt ( Math . abs ( x0 . data [ 5 ] ) ) * Math . signum ( x0 . data [ 2 ] ) ; } }
Estimates betas using relinearization .
432
10
27,638
protected DMatrixRMaj solveConstraintMatrix ( ) { int rowAA = 0 ; for ( int i = 0 ; i < numControl ; i ++ ) { for ( int j = i + 1 ; j < numControl ; j ++ ) { for ( int k = j ; k < numControl ; k ++ , rowAA ++ ) { // x_{ii}*x_{jk} = x_{ik}*x_{ji} extractXaXb ( getIndex ( i , i ) , getIndex ( j , k ) , XiiXjk ) ; extractXaXb ( getIndex ( i , k ) , getIndex ( j , i ) , XikXji ) ; for ( int l = 1 ; l <= AA . numCols ; l ++ ) { AA . set ( rowAA , l - 1 , XikXji [ l ] - XiiXjk [ l ] ) ; } yy . set ( rowAA , XiiXjk [ 0 ] - XikXji [ 0 ] ) ; } } } // AA.print(); CommonOps_DDRM . solve ( AA , yy , xx ) ; return xx ; }
Apply additional constraints to reduce the number of possible solutions
256
10
27,639
public static < T extends ImageGray < T > > void orderBandsIntoRGB ( Planar < T > image , BufferedImage input ) { boolean swap = swapBandOrder ( input ) ; // Output formats are: RGB and RGBA if ( swap ) { if ( image . getNumBands ( ) == 3 ) { int bufferedImageType = input . getType ( ) ; if ( bufferedImageType == BufferedImage . TYPE_3BYTE_BGR || bufferedImageType == BufferedImage . TYPE_INT_BGR ) { T tmp = image . getBand ( 0 ) ; image . bands [ 0 ] = image . getBand ( 2 ) ; image . bands [ 2 ] = tmp ; } } else if ( image . getNumBands ( ) == 4 ) { T [ ] temp = ( T [ ] ) Array . newInstance ( image . getBandType ( ) , 4 ) ; int bufferedImageType = input . getType ( ) ; if ( bufferedImageType == BufferedImage . TYPE_INT_ARGB ) { temp [ 0 ] = image . getBand ( 1 ) ; temp [ 1 ] = image . getBand ( 2 ) ; temp [ 2 ] = image . getBand ( 3 ) ; temp [ 3 ] = image . getBand ( 0 ) ; } else if ( bufferedImageType == BufferedImage . TYPE_4BYTE_ABGR ) { temp [ 0 ] = image . getBand ( 3 ) ; temp [ 1 ] = image . getBand ( 2 ) ; temp [ 2 ] = image . getBand ( 1 ) ; temp [ 3 ] = image . getBand ( 0 ) ; } image . bands [ 0 ] = temp [ 0 ] ; image . bands [ 1 ] = temp [ 1 ] ; image . bands [ 2 ] = temp [ 2 ] ; image . bands [ 3 ] = temp [ 3 ] ; } } }
If a Planar was created from a BufferedImage its colors might not be in the expected order . Invoking this function ensures that the image will have the expected ordering . For images with 3 bands it will be RGB and for 4 bands it will be ARGB .
409
54
27,640
public static boolean isKnownByteFormat ( BufferedImage image ) { int type = image . getType ( ) ; return type != BufferedImage . TYPE_BYTE_INDEXED && type != BufferedImage . TYPE_BYTE_BINARY && type != BufferedImage . TYPE_CUSTOM ; }
Checks to see if it is a known byte format
68
11
27,641
public static List < BufferedImage > loadImages ( String directory , final String regex ) { List < String > paths = UtilIO . listByRegex ( directory , regex ) ; List < BufferedImage > ret = new ArrayList <> ( ) ; if ( paths . size ( ) == 0 ) return ret ; // Sort so that the order is deterministic Collections . sort ( paths ) ; for ( String path : paths ) { BufferedImage img = loadImage ( path ) ; if ( img != null ) ret . add ( img ) ; } return ret ; }
Loads all the image in the specified directory which match the provided regex
121
14
27,642
public static BufferedImage loadImage ( URL url ) { if ( url == null ) return null ; try { BufferedImage buffered = ImageIO . read ( url ) ; if ( buffered != null ) return buffered ; if ( url . getProtocol ( ) . equals ( "file" ) ) { String path = URLDecoder . decode ( url . getPath ( ) , "UTF-8" ) ; if ( ! new File ( path ) . exists ( ) ) { System . err . println ( "File does not exist: " + path ) ; return null ; } } } catch ( IOException ignore ) { } try { InputStream stream = url . openStream ( ) ; String path = url . toString ( ) ; if ( path . toLowerCase ( ) . endsWith ( "ppm" ) ) { return loadPPM ( stream , null ) ; } else if ( path . toLowerCase ( ) . endsWith ( "pgm" ) ) { return loadPGM ( stream , null ) ; } stream . close ( ) ; } catch ( IOException ignore ) { } return null ; }
A function that load the specified image . If anything goes wrong it returns a null .
239
17
27,643
public static < T extends ImageGray < T > > T loadImage ( String fileName , Class < T > imageType ) { BufferedImage img = loadImage ( fileName ) ; if ( img == null ) return null ; return ConvertBufferedImage . convertFromSingle ( img , ( T ) null , imageType ) ; }
Loads the image and converts into the specified image type .
70
12
27,644
public static BufferedImage loadPPM ( String fileName , BufferedImage storage ) throws IOException { return loadPPM ( new FileInputStream ( fileName ) , storage ) ; }
Loads a PPM image from a file .
40
10
27,645
public static BufferedImage loadPGM ( String fileName , BufferedImage storage ) throws IOException { return loadPGM ( new FileInputStream ( fileName ) , storage ) ; }
Loads a PGM image from a file .
40
10
27,646
public static void savePPM ( Planar < GrayU8 > rgb , String fileName , GrowQueue_I8 temp ) throws IOException { File out = new File ( fileName ) ; DataOutputStream os = new DataOutputStream ( new FileOutputStream ( out ) ) ; String header = String . format ( "P6\n%d %d\n255\n" , rgb . width , rgb . height ) ; os . write ( header . getBytes ( ) ) ; if ( temp == null ) temp = new GrowQueue_I8 ( ) ; temp . resize ( rgb . width * rgb . height * 3 ) ; byte data [ ] = temp . data ; GrayU8 band0 = rgb . getBand ( 0 ) ; GrayU8 band1 = rgb . getBand ( 1 ) ; GrayU8 band2 = rgb . getBand ( 2 ) ; int indexOut = 0 ; for ( int y = 0 ; y < rgb . height ; y ++ ) { int index = rgb . startIndex + y * rgb . stride ; for ( int x = 0 ; x < rgb . width ; x ++ , index ++ ) { data [ indexOut ++ ] = band0 . data [ index ] ; data [ indexOut ++ ] = band1 . data [ index ] ; data [ indexOut ++ ] = band2 . data [ index ] ; } } os . write ( data , 0 , temp . size ) ; os . close ( ) ; }
Saves an image in PPM format .
311
9
27,647
public static void savePGM ( GrayU8 gray , String fileName ) throws IOException { File out = new File ( fileName ) ; DataOutputStream os = new DataOutputStream ( new FileOutputStream ( out ) ) ; String header = String . format ( "P5\n%d %d\n255\n" , gray . width , gray . height ) ; os . write ( header . getBytes ( ) ) ; os . write ( gray . data , 0 , gray . width * gray . height ) ; os . close ( ) ; }
Saves an image in PGM format .
119
9
27,648
public static < T extends KernelBase > T gaussian ( Class < T > kernelType , double sigma , int radius ) { if ( Kernel1D_F32 . class == kernelType ) { return gaussian ( 1 , true , 32 , sigma , radius ) ; } else if ( Kernel1D_F64 . class == kernelType ) { return gaussian ( 1 , true , 64 , sigma , radius ) ; } else if ( Kernel1D_S32 . class == kernelType ) { return gaussian ( 1 , false , 32 , sigma , radius ) ; } else if ( Kernel2D_S32 . class == kernelType ) { return gaussian ( 2 , false , 32 , sigma , radius ) ; } else if ( Kernel2D_F32 . class == kernelType ) { return gaussian ( 2 , true , 32 , sigma , radius ) ; } else if ( Kernel2D_F64 . class == kernelType ) { return gaussian ( 2 , true , 64 , sigma , radius ) ; } else { throw new RuntimeException ( "Unknown kernel type. " + kernelType . getSimpleName ( ) ) ; } }
Creates a Gaussian kernel of the specified type .
250
11
27,649
public static < T extends ImageGray < T > , K extends Kernel1D > K gaussian1D ( Class < T > imageType , double sigma , int radius ) { boolean isFloat = GeneralizedImageOps . isFloatingPoint ( imageType ) ; int numBits = GeneralizedImageOps . getNumBits ( imageType ) ; if ( numBits < 32 ) numBits = 32 ; return gaussian ( 1 , isFloat , numBits , sigma , radius ) ; }
Creates a 1D Gaussian kernel of the specified type .
109
13
27,650
public static < T extends ImageGray < T > , K extends Kernel2D > K gaussian2D ( Class < T > imageType , double sigma , int radius ) { boolean isFloat = GeneralizedImageOps . isFloatingPoint ( imageType ) ; int numBits = Math . max ( 32 , GeneralizedImageOps . getNumBits ( imageType ) ) ; return gaussian ( 2 , isFloat , numBits , sigma , radius ) ; }
Creates a 2D Gaussian kernel of the specified type .
102
13
27,651
public static < T extends KernelBase > T gaussian ( int DOF , boolean isFloat , int numBits , double sigma , int radius ) { if ( radius <= 0 ) radius = FactoryKernelGaussian . radiusForSigma ( sigma , 0 ) ; else if ( sigma <= 0 ) sigma = FactoryKernelGaussian . sigmaForRadius ( radius , 0 ) ; if ( DOF == 2 ) { if ( numBits == 32 ) { Kernel2D_F32 k = gaussian2D_F32 ( sigma , radius , true , isFloat ) ; if ( isFloat ) return ( T ) k ; return ( T ) KernelMath . convert ( k , MIN_FRAC ) ; } else if ( numBits == 64 ) { Kernel2D_F64 k = gaussian2D_F64 ( sigma , radius , true , isFloat ) ; if ( isFloat ) return ( T ) k ; else throw new IllegalArgumentException ( "64bit int kernels supported" ) ; } else { throw new IllegalArgumentException ( "Bits must be 32 or 64" ) ; } } else if ( DOF == 1 ) { if ( numBits == 32 ) { Kernel1D_F32 k = gaussian1D_F32 ( sigma , radius , true , isFloat ) ; if ( isFloat ) return ( T ) k ; return ( T ) KernelMath . convert ( k , MIN_FRAC ) ; } else if ( numBits == 64 ) { Kernel1D_F64 k = gaussian1D_F64 ( sigma , radius , true , isFloat ) ; if ( isFloat ) return ( T ) k ; return ( T ) KernelMath . convert ( k , MIN_FRACD ) ; } else { throw new IllegalArgumentException ( "Bits must be 32 or 64 not " + numBits ) ; } } else { throw new IllegalArgumentException ( "DOF not supported" ) ; } }
Creates a Gaussian kernel with the specified properties .
434
11
27,652
public static < T extends Kernel1D > T derivative ( int order , boolean isFloat , double sigma , int radius ) { // zero order is a regular gaussian if ( order == 0 ) { return gaussian ( 1 , isFloat , 32 , sigma , radius ) ; } if ( radius <= 0 ) radius = FactoryKernelGaussian . radiusForSigma ( sigma , order ) ; else if ( sigma <= 0 ) { sigma = FactoryKernelGaussian . sigmaForRadius ( radius , order ) ; } Kernel1D_F32 k = derivative1D_F32 ( order , sigma , radius , true ) ; if ( isFloat ) return ( T ) k ; return ( T ) KernelMath . convert ( k , MIN_FRAC ) ; }
Creates a 1D Gaussian kernel with the specified properties .
169
13
27,653
public static Kernel2D_F32 gaussian2D_F32 ( double sigma , int radius , boolean odd , boolean normalize ) { Kernel1D_F32 kernel1D = gaussian1D_F32 ( sigma , radius , odd , false ) ; Kernel2D_F32 ret = KernelMath . convolve2D ( kernel1D , kernel1D ) ; if ( normalize ) { KernelMath . normalizeSumToOne ( ret ) ; } return ret ; }
Creates a kernel for a 2D convolution . This should only be used for validation purposes .
107
20
27,654
protected static Kernel1D_F32 derivative1D_F32 ( int order , double sigma , int radius , boolean normalize ) { Kernel1D_F32 ret = new Kernel1D_F32 ( radius * 2 + 1 ) ; float [ ] gaussian = ret . data ; int index = 0 ; switch ( order ) { case 1 : for ( int i = radius ; i >= - radius ; i -- ) { gaussian [ index ++ ] = ( float ) UtilGaussian . derivative1 ( 0 , sigma , i ) ; } break ; case 2 : for ( int i = radius ; i >= - radius ; i -- ) { gaussian [ index ++ ] = ( float ) UtilGaussian . derivative2 ( 0 , sigma , i ) ; } break ; case 3 : for ( int i = radius ; i >= - radius ; i -- ) { gaussian [ index ++ ] = ( float ) UtilGaussian . derivative3 ( 0 , sigma , i ) ; } break ; case 4 : for ( int i = radius ; i >= - radius ; i -- ) { gaussian [ index ++ ] = ( float ) UtilGaussian . derivative4 ( 0 , sigma , i ) ; } break ; default : throw new IllegalArgumentException ( "Only derivatives of order 1 to 4 are supported" ) ; } // multiply by the same factor as the gaussian would be normalized by // otherwise it will effective change the intensity of the input image if ( normalize ) { double sum = 0 ; for ( int i = radius ; i >= - radius ; i -- ) { sum += UtilGaussian . computePDF ( 0 , sigma , i ) ; } for ( int i = 0 ; i < gaussian . length ; i ++ ) { gaussian [ i ] /= sum ; } } return ret ; }
Computes the derivative of a Gaussian kernel .
393
10
27,655
public static Kernel2D_F64 gaussianWidth ( double sigma , int width ) { if ( sigma <= 0 ) sigma = sigmaForRadius ( width / 2 , 0 ) ; else if ( width <= 0 ) throw new IllegalArgumentException ( "Must specify the width since it doesn't know if it should be even or odd" ) ; if ( width % 2 == 0 ) { int r = width / 2 - 1 ; Kernel2D_F64 ret = new Kernel2D_F64 ( width ) ; double sum = 0 ; for ( int y = 0 ; y < width ; y ++ ) { double dy = y <= r ? Math . abs ( y - r ) + 0.5 : Math . abs ( y - r - 1 ) + 0.5 ; for ( int x = 0 ; x < width ; x ++ ) { double dx = x <= r ? Math . abs ( x - r ) + 0.5 : Math . abs ( x - r - 1 ) + 0.5 ; double d = Math . sqrt ( dx * dx + dy * dy ) ; double val = UtilGaussian . computePDF ( 0 , sigma , d ) ; ret . set ( x , y , val ) ; sum += val ; } } for ( int i = 0 ; i < ret . data . length ; i ++ ) { ret . data [ i ] /= sum ; } return ret ; } else { return gaussian2D_F64 ( sigma , width / 2 , true , true ) ; } }
Create a gaussian kernel based on its width . Supports kernels of even or odd widths .
331
19
27,656
public boolean process ( List < AssociatedTriple > associated , int width , int height ) { init ( width , height ) ; // Fit a trifocal tensor to the input observations if ( ! robustFitTrifocal ( associated ) ) return false ; // estimate the scene's structure if ( ! estimateProjectiveScene ( ) ) return false ; if ( ! projectiveToMetric ( ) ) return false ; // Run bundle adjustment while make sure a valid solution is found setupMetricBundleAdjustment ( inliers ) ; bundleAdjustment = FactoryMultiView . bundleSparseMetric ( configSBA ) ; findBestValidSolution ( bundleAdjustment ) ; // Prune outliers and run bundle adjustment one last time pruneOutliers ( bundleAdjustment ) ; return true ; }
Determines the metric scene . The principle point is assumed to be zero in the passed in pixel coordinates . Typically this is done by subtracting the image center from each pixel coordinate for each view .
167
40
27,657
private boolean robustFitTrifocal ( List < AssociatedTriple > associated ) { // Fit a trifocal tensor to the observations robustly ransac . process ( associated ) ; inliers = ransac . getMatchSet ( ) ; TrifocalTensor model = ransac . getModelParameters ( ) ; if ( verbose != null ) verbose . println ( "Remaining after RANSAC " + inliers . size ( ) + " / " + associated . size ( ) ) ; // estimate using all the inliers // No need to re-scale the input because the estimator automatically adjusts the input on its own if ( ! trifocalEstimator . process ( inliers , model ) ) { if ( verbose != null ) { verbose . println ( "Trifocal estimator failed" ) ; } return false ; } return true ; }
Fits a trifocal tensor to the list of matches features using a robust method
190
18
27,658
private void pruneOutliers ( BundleAdjustment < SceneStructureMetric > bundleAdjustment ) { // see if it's configured to not prune if ( pruneFraction == 1.0 ) return ; PruneStructureFromSceneMetric pruner = new PruneStructureFromSceneMetric ( structure , observations ) ; pruner . pruneObservationsByErrorRank ( pruneFraction ) ; pruner . pruneViews ( 10 ) ; pruner . prunePoints ( 1 ) ; bundleAdjustment . setParameters ( structure , observations ) ; bundleAdjustment . optimize ( structure ) ; if ( verbose != null ) { verbose . println ( "\nCamera" ) ; for ( int i = 0 ; i < structure . cameras . length ; i ++ ) { verbose . println ( structure . cameras [ i ] . getModel ( ) . toString ( ) ) ; } verbose . println ( "\n\nworldToView" ) ; for ( int i = 0 ; i < structure . views . length ; i ++ ) { verbose . println ( structure . views [ i ] . worldToView . toString ( ) ) ; } verbose . println ( "Fit Score: " + bundleAdjustment . getFitScore ( ) ) ; } }
Prunes the features with the largest reprojection error
275
10
27,659
private boolean estimateProjectiveScene ( ) { List < AssociatedTriple > inliers = ransac . getMatchSet ( ) ; TrifocalTensor model = ransac . getModelParameters ( ) ; MultiViewOps . extractCameraMatrices ( model , P2 , P3 ) ; // Most of the time this makes little difference, but in some edges cases this enables it to // converge correctly RefineThreeViewProjective refineP23 = FactoryMultiView . threeViewRefine ( null ) ; if ( ! refineP23 . process ( inliers , P2 , P3 , P2 , P3 ) ) { if ( verbose != null ) { verbose . println ( "Can't refine P2 and P3!" ) ; } return false ; } return true ; }
Estimate the projective scene from the trifocal tensor
169
13
27,660
private void setupMetricBundleAdjustment ( List < AssociatedTriple > inliers ) { // Construct bundle adjustment data structure structure = new SceneStructureMetric ( false ) ; observations = new SceneObservations ( 3 ) ; structure . initialize ( 3 , 3 , inliers . size ( ) ) ; for ( int i = 0 ; i < listPinhole . size ( ) ; i ++ ) { CameraPinhole cp = listPinhole . get ( i ) ; BundlePinholeSimplified bp = new BundlePinholeSimplified ( ) ; bp . f = cp . fx ; structure . setCamera ( i , false , bp ) ; structure . setView ( i , i == 0 , worldToView . get ( i ) ) ; structure . connectViewToCamera ( i , i ) ; } for ( int i = 0 ; i < inliers . size ( ) ; i ++ ) { AssociatedTriple t = inliers . get ( i ) ; observations . getView ( 0 ) . add ( i , ( float ) t . p1 . x , ( float ) t . p1 . y ) ; observations . getView ( 1 ) . add ( i , ( float ) t . p2 . x , ( float ) t . p2 . y ) ; observations . getView ( 2 ) . add ( i , ( float ) t . p3 . x , ( float ) t . p3 . y ) ; structure . connectPointToView ( i , 0 ) ; structure . connectPointToView ( i , 1 ) ; structure . connectPointToView ( i , 2 ) ; } // Initial estimate for point 3D locations triangulatePoints ( structure , observations ) ; }
Using the initial metric reconstruction provide the initial configurations for bundle adjustment
368
12
27,661
private boolean checkBehindCamera ( SceneStructureMetric structure ) { int totalBehind = 0 ; Point3D_F64 X = new Point3D_F64 ( ) ; for ( int i = 0 ; i < structure . points . length ; i ++ ) { structure . points [ i ] . get ( X ) ; if ( X . z < 0 ) totalBehind ++ ; } if ( verbose != null ) { verbose . println ( "points behind " + totalBehind + " / " + structure . points . length ) ; } return totalBehind > structure . points . length / 2 ; }
Checks to see if a solution was converged to where the points are behind the camera . This is pysically impossible
128
25
27,662
private static void flipAround ( SceneStructureMetric structure , SceneObservations observations ) { // The first view will be identity for ( int i = 1 ; i < structure . views . length ; i ++ ) { Se3_F64 w2v = structure . views [ i ] . worldToView ; w2v . set ( w2v . invert ( null ) ) ; } triangulatePoints ( structure , observations ) ; }
Flip the camera pose around . This seems to help it converge to a valid solution if it got it backwards even if it s not technically something which can be inverted this way
95
35
27,663
public void setImage ( II grayII , Planar < II > colorII ) { InputSanityCheck . checkSameShape ( grayII , colorII ) ; if ( colorII . getNumBands ( ) != numBands ) throw new IllegalArgumentException ( "Expected planar images to have " + numBands + " not " + colorII . getNumBands ( ) ) ; this . grayII = grayII ; this . colorII = colorII ; }
Specifies input image shapes .
103
6
27,664
public static void hsvToRgb ( double h , double s , double v , double [ ] rgb ) { if ( s == 0 ) { rgb [ 0 ] = v ; rgb [ 1 ] = v ; rgb [ 2 ] = v ; return ; } h /= d60_F64 ; int h_int = ( int ) h ; double remainder = h - h_int ; double p = v * ( 1 - s ) ; double q = v * ( 1 - s * remainder ) ; double t = v * ( 1 - s * ( 1 - remainder ) ) ; if ( h_int < 1 ) { rgb [ 0 ] = v ; rgb [ 1 ] = t ; rgb [ 2 ] = p ; } else if ( h_int < 2 ) { rgb [ 0 ] = q ; rgb [ 1 ] = v ; rgb [ 2 ] = p ; } else if ( h_int < 3 ) { rgb [ 0 ] = p ; rgb [ 1 ] = v ; rgb [ 2 ] = t ; } else if ( h_int < 4 ) { rgb [ 0 ] = p ; rgb [ 1 ] = q ; rgb [ 2 ] = v ; } else if ( h_int < 5 ) { rgb [ 0 ] = t ; rgb [ 1 ] = p ; rgb [ 2 ] = v ; } else { rgb [ 0 ] = v ; rgb [ 1 ] = p ; rgb [ 2 ] = q ; } }
Convert HSV color into RGB color
308
8
27,665
public void configure ( CameraPinholeBrown intrinsic , Se3_F64 planeToCamera , double centerX , double centerY , double cellSize , int overheadWidth , int overheadHeight ) { this . overheadWidth = overheadWidth ; this . overheadHeight = overheadHeight ; Point2Transform2_F64 normToPixel = LensDistortionFactory . narrow ( intrinsic ) . distort_F64 ( false , true ) ; // Declare storage for precomputed pixel locations int overheadPixels = overheadHeight * overheadWidth ; if ( mapPixels == null || mapPixels . length < overheadPixels ) { mapPixels = new Point2D_F32 [ overheadPixels ] ; } points . reset ( ) ; // -------- storage for intermediate results Point2D_F64 pixel = new Point2D_F64 ( ) ; // coordinate on the plane Point3D_F64 pt_plane = new Point3D_F64 ( ) ; // coordinate in camera reference frame Point3D_F64 pt_cam = new Point3D_F64 ( ) ; int indexOut = 0 ; for ( int i = 0 ; i < overheadHeight ; i ++ ) { pt_plane . x = - ( i * cellSize - centerY ) ; for ( int j = 0 ; j < overheadWidth ; j ++ , indexOut ++ ) { pt_plane . z = j * cellSize - centerX ; // plane to camera reference frame SePointOps_F64 . transform ( planeToCamera , pt_plane , pt_cam ) ; // can't see behind the camera if ( pt_cam . z > 0 ) { // compute normalized then convert to pixels normToPixel . compute ( pt_cam . x / pt_cam . z , pt_cam . y / pt_cam . z , pixel ) ; float x = ( float ) pixel . x ; float y = ( float ) pixel . y ; // make sure it's in the image if ( BoofMiscOps . checkInside ( intrinsic . width , intrinsic . height , x , y ) ) { Point2D_F32 p = points . grow ( ) ; p . set ( x , y ) ; mapPixels [ indexOut ] = p ; } else { mapPixels [ indexOut ] = null ; } } } } }
Specifies camera configurations .
489
5
27,666
public boolean detect ( T input ) { detections . reset ( ) ; detector . process ( input ) ; FastQueue < FoundFiducial > found = detector . getFound ( ) ; for ( int i = 0 ; i < found . size ( ) ; i ++ ) { FoundFiducial fid = found . get ( i ) ; int gridIndex = isExpected ( fid . id ) ; if ( gridIndex >= 0 ) { Detection d = lookupDetection ( fid . id , gridIndex ) ; d . location . set ( fid . distortedPixels ) ; d . numDetected ++ ; } } for ( int i = detections . size - 1 ; i >= 0 ; i -- ) { if ( detections . get ( i ) . numDetected != 1 ) { detections . remove ( i ) ; } } return detections . size > 0 ; }
Searches for the fiducial inside the image . If at least a partial match is found true is returned .
187
24
27,667
private int isExpected ( long found ) { int bestHamming = 2 ; int bestNumber = - 1 ; for ( int i = 0 ; i < numbers . length ; i ++ ) { int hamming = DescriptorDistance . hamming ( ( int ) found ^ ( int ) numbers [ i ] ) ; if ( hamming < bestHamming ) { bestHamming = hamming ; bestNumber = i ; } } return bestNumber ; }
Checks to see if the provided ID number is expected or not
96
13
27,668
private Detection lookupDetection ( long found , int gridIndex ) { for ( int i = 0 ; i < detections . size ( ) ; i ++ ) { Detection d = detections . get ( i ) ; if ( d . id == found ) { return d ; } } Detection d = detections . grow ( ) ; d . reset ( ) ; d . id = found ; d . gridIndex = gridIndex ; return d ; }
Looks up a detection given the fiducial ID number . If not seen before the gridIndex is saved and a new instance returned .
93
27
27,669
public void process ( GrayU8 binary , GrayS32 labeled ) { // initialize data structures labeled . reshape ( binary . width , binary . height ) ; // ensure that the image border pixels are filled with zero by enlarging the image if ( border . width != binary . width + 2 || border . height != binary . height + 2 ) { border . reshape ( binary . width + 2 , binary . height + 2 ) ; ImageMiscOps . fillBorder ( border , 0 , 1 ) ; } border . subimage ( 1 , 1 , border . width - 1 , border . height - 1 , null ) . setTo ( binary ) ; // labeled image must initially be filled with zeros ImageMiscOps . fill ( labeled , 0 ) ; binary = border ; packedPoints . reset ( ) ; contours . reset ( ) ; tracer . setInputs ( binary , labeled , packedPoints ) ; // Outside border is all zeros so it can be ignored int endY = binary . height - 1 , enxX = binary . width - 1 ; for ( y = 1 ; y < endY ; y ++ ) { indexIn = binary . startIndex + y * binary . stride + 1 ; indexOut = labeled . startIndex + ( y - 1 ) * labeled . stride ; x = 1 ; int delta = scanForOne ( binary . data , indexIn , indexIn + enxX - x ) - indexIn ; x += delta ; indexIn += delta ; indexOut += delta ; while ( x < enxX ) { int label = labeled . data [ indexOut ] ; boolean handled = false ; if ( label == 0 && binary . data [ indexIn - binary . stride ] != 1 ) { handleStep1 ( ) ; handled = true ; label = contours . size ; } // could be an external and internal contour if ( binary . data [ indexIn + binary . stride ] == 0 ) { handleStep2 ( labeled , label ) ; handled = true ; } if ( ! handled ) { // Step 3: Must not be part of the contour but an inner pixel and the pixel to the left must be // labeled if ( labeled . data [ indexOut ] == 0 ) labeled . data [ indexOut ] = labeled . data [ indexOut - 1 ] ; } delta = scanForOne ( binary . data , indexIn + 1 , indexIn + enxX - x ) - indexIn ; x += delta ; indexIn += delta ; indexOut += delta ; } } }
Processes the binary image to find the contour of and label blobs .
529
16
27,670
private int scanForOne ( byte [ ] data , int index , int end ) { while ( index < end && data [ index ] != 1 ) { index ++ ; } return index ; }
Faster when there s a specialized function which searches for one pixels
40
13
27,671
public static < T extends ImageGray < T > > QrCodePreciseDetector < T > qrcode ( ConfigQrCode config , Class < T > imageType ) { if ( config == null ) config = new ConfigQrCode ( ) ; config . checkValidity ( ) ; InputToBinary < T > inputToBinary = FactoryThresholdBinary . threshold ( config . threshold , imageType ) ; DetectPolygonBinaryGrayRefine < T > squareDetector = FactoryShapeDetector . polygon ( config . polygon , imageType ) ; QrCodePositionPatternDetector < T > detectPositionPatterns = new QrCodePositionPatternDetector <> ( squareDetector , config . versionMaximum ) ; return new QrCodePreciseDetector <> ( inputToBinary , detectPositionPatterns , config . forceEncoding , false , imageType ) ; }
Returns a QR Code detector
194
5
27,672
public void initialize ( T image , int x0 , int y0 , int x1 , int y1 ) { if ( imagePyramid == null || imagePyramid . getInputWidth ( ) != image . width || imagePyramid . getInputHeight ( ) != image . height ) { int minSize = ( config . trackerFeatureRadius * 2 + 1 ) * 5 ; int scales [ ] = selectPyramidScale ( image . width , image . height , minSize ) ; imagePyramid = FactoryPyramid . discreteGaussian ( scales , - 1 , 1 , true , image . getImageType ( ) ) ; } imagePyramid . process ( image ) ; reacquiring = false ; targetRegion . set ( x0 , y0 , x1 , y1 ) ; createCascadeRegion ( image . width , image . height ) ; template . reset ( ) ; fern . reset ( ) ; tracking . initialize ( imagePyramid ) ; variance . setImage ( image ) ; template . setImage ( image ) ; fern . setImage ( image ) ; adjustRegion . init ( image . width , image . height ) ; learning . initialLearning ( targetRegion , cascadeRegions ) ; strongMatch = true ; previousTrackArea = targetRegion . area ( ) ; }
Starts tracking the rectangular region .
271
7
27,673
private void createCascadeRegion ( int imageWidth , int imageHeight ) { cascadeRegions . reset ( ) ; int rectWidth = ( int ) ( targetRegion . getWidth ( ) + 0.5 ) ; int rectHeight = ( int ) ( targetRegion . getHeight ( ) + 0.5 ) ; for ( int scaleInt = - config . scaleSpread ; scaleInt <= config . scaleSpread ; scaleInt ++ ) { // try several scales as specified in the paper double scale = Math . pow ( 1.2 , scaleInt ) ; // the actual rectangular region being tested at this scale int actualWidth = ( int ) ( rectWidth * scale ) ; int actualHeight = ( int ) ( rectHeight * scale ) ; // see if the region is too small or too large if ( actualWidth < config . detectMinimumSide || actualHeight < config . detectMinimumSide ) continue ; if ( actualWidth >= imageWidth || actualHeight >= imageHeight ) continue ; // step size at this scale int stepWidth = ( int ) ( rectWidth * scale * 0.1 ) ; int stepHeight = ( int ) ( rectHeight * scale * 0.1 ) ; if ( stepWidth < 1 ) stepWidth = 1 ; if ( stepHeight < 1 ) stepHeight = 1 ; // maximum allowed values int maxX = imageWidth - actualWidth ; int maxY = imageHeight - actualHeight ; // start at (1,1). Otherwise a more complex algorithm needs to be used for integral images for ( int y0 = 1 ; y0 < maxY ; y0 += stepHeight ) { for ( int x0 = 1 ; x0 < maxX ; x0 += stepWidth ) { ImageRectangle r = cascadeRegions . grow ( ) ; r . x0 = x0 ; r . y0 = y0 ; r . x1 = x0 + actualWidth ; r . y1 = y0 + actualHeight ; } } } }
Creates a list containing all the regions which need to be tested
409
13
27,674
public boolean track ( T image ) { boolean success = true ; valid = false ; imagePyramid . process ( image ) ; template . setImage ( image ) ; variance . setImage ( image ) ; fern . setImage ( image ) ; if ( reacquiring ) { // It can reinitialize if there is a single detection detection . detectionCascade ( cascadeRegions ) ; if ( detection . isSuccess ( ) && ! detection . isAmbiguous ( ) ) { TldRegion region = detection . getBest ( ) ; reacquiring = false ; valid = false ; // set it to the detected region ImageRectangle r = region . rect ; targetRegion . set ( r . x0 , r . y0 , r . x1 , r . y1 ) ; // get tracking running again tracking . initialize ( imagePyramid ) ; checkNewTrackStrong ( region . confidence ) ; } else { success = false ; } } else { detection . detectionCascade ( cascadeRegions ) ; // update the previous track region using the tracker trackerRegion . set ( targetRegion ) ; boolean trackingWorked = tracking . process ( imagePyramid , trackerRegion ) ; trackingWorked &= adjustRegion . process ( tracking . getPairs ( ) , trackerRegion ) ; TldHelperFunctions . convertRegion ( trackerRegion , trackerRegion_I32 ) ; if ( hypothesisFusion ( trackingWorked , detection . isSuccess ( ) ) ) { // if it found a hypothesis and it is valid for learning, then learn if ( valid && performLearning ) { learning . updateLearning ( targetRegion ) ; } } else { reacquiring = true ; success = false ; } } if ( strongMatch ) { previousTrackArea = targetRegion . area ( ) ; } return success ; }
Updates track region .
375
5
27,675
protected boolean hypothesisFusion ( boolean trackingWorked , boolean detectionWorked ) { valid = false ; boolean uniqueDetection = detectionWorked && ! detection . isAmbiguous ( ) ; TldRegion detectedRegion = detection . getBest ( ) ; double confidenceTarget ; if ( trackingWorked ) { // get the scores from tracking and detection double scoreTrack = template . computeConfidence ( trackerRegion_I32 ) ; double scoreDetected = 0 ; if ( uniqueDetection ) { scoreDetected = detectedRegion . confidence ; } double adjustment = strongMatch ? 0.07 : 0.02 ; if ( uniqueDetection && scoreDetected > scoreTrack + adjustment ) { // if there is a unique detection and it has higher confidence than the // track region, use the detected region TldHelperFunctions . convertRegion ( detectedRegion . rect , targetRegion ) ; confidenceTarget = detectedRegion . confidence ; // if it's far away from the current track, re-evaluate if it's a strongMatch checkNewTrackStrong ( scoreDetected ) ; } else { // Otherwise use the tracker region targetRegion . set ( trackerRegion ) ; confidenceTarget = scoreTrack ; strongMatch |= confidenceTarget > config . confidenceThresholdStrong ; // see if the most likely detected region overlaps the track region if ( strongMatch && confidenceTarget >= config . confidenceThresholdLower ) { valid = true ; } } } else if ( uniqueDetection ) { // just go with the best detected region detectedRegion = detection . getBest ( ) ; TldHelperFunctions . convertRegion ( detectedRegion . rect , targetRegion ) ; confidenceTarget = detectedRegion . confidence ; strongMatch = confidenceTarget > config . confidenceThresholdStrong ; } else { return false ; } return confidenceTarget >= config . confidenceAccept ; }
Combines hypotheses from tracking and detection .
376
8
27,676
public static int [ ] selectPyramidScale ( int imageWidth , int imageHeight , int minSize ) { int w = Math . max ( imageWidth , imageHeight ) ; int maxScale = w / minSize ; int n = 1 ; int scale = 1 ; while ( scale * 2 < maxScale ) { n ++ ; scale *= 2 ; } int ret [ ] = new int [ n ] ; scale = 1 ; for ( int i = 0 ; i < n ; i ++ ) { ret [ i ] = scale ; scale *= 2 ; } return ret ; }
Selects the scale for the image pyramid based on image size and feature size
122
15
27,677
public void imageToGrid ( Point2D_F64 pixel , Point2D_F64 grid ) { transformGrid . imageToGrid ( pixel . x , pixel . y , grid ) ; }
Converts a pixel coordinate into a grid coordinate .
42
10
27,678
public int readBit ( int row , int col ) { // todo use adjustments from near by alignment patterns float center = 0.5f ; // if( pixel.x < -0.5 || pixel.y < -0.5 || pixel.x > imageWidth || pixel.y > imageHeight ) // return -1; transformGrid . gridToImage ( row + center - 0.2f , col + center , pixel ) ; float pixel01 = interpolate . get ( pixel . x , pixel . y ) ; transformGrid . gridToImage ( row + center + 0.2f , col + center , pixel ) ; float pixel21 = interpolate . get ( pixel . x , pixel . y ) ; transformGrid . gridToImage ( row + center , col + center - 0.2f , pixel ) ; float pixel10 = interpolate . get ( pixel . x , pixel . y ) ; transformGrid . gridToImage ( row + center , col + center + 0.2f , pixel ) ; float pixel12 = interpolate . get ( pixel . x , pixel . y ) ; transformGrid . gridToImage ( row + center , col + center , pixel ) ; float pixel00 = interpolate . get ( pixel . x , pixel . y ) ; // float threshold = this.threshold*1.25f; int total = 0 ; if ( pixel01 < threshold ) total ++ ; if ( pixel21 < threshold ) total ++ ; if ( pixel10 < threshold ) total ++ ; if ( pixel12 < threshold ) total ++ ; if ( pixel00 < threshold ) total ++ ; if ( total >= 3 ) return 1 ; else return 0 ; // float value = (pixel01+pixel21+pixel10+pixel12)*0.25f; // value = value*0.5f + pixel00*0.5f; // in at least one situation this was found to improve the reading // float threshold; // if( qr != null ) { // int N = qr.getNumberOfModules(); // if( row > N/2 ) { // if( col < N/2 ) // threshold = (float)qr.threshDown; // else { // threshold = (float)(qr.threshDown+qr.threshRight)/2f; // } // } else if( col < N/2 ) { // threshold = (float)qr.threshCorner; // } else { // threshold = (float)qr.threshRight; // } // } else { // threshold = this.threshold; // } // if( pixel00 < threshold ) // return 1; // else // return 0; }
Reads a bit from the qr code s data matrix while adjusting for location distortions using known feature locations .
569
22
27,679
public static Webcam openDefault ( int desiredWidth , int desiredHeight ) { Webcam webcam = Webcam . getDefault ( ) ; // Webcam doesn't list all available resolutions. Just pass in a custom // resolution and hope it works adjustResolution ( webcam , desiredWidth , desiredHeight ) ; webcam . open ( ) ; return webcam ; }
Opens the default camera while adjusting its resolution
72
9
27,680
public void process ( List < EllipseInfo > ellipses , List < List < Node > > output ) { init ( ellipses ) ; connect ( ellipses ) ; output . clear ( ) ; for ( int i = 0 ; i < clusters . size ( ) ; i ++ ) { List < Node > c = clusters . get ( i ) ; // remove noise removeSingleConnections ( c ) ; if ( c . size ( ) >= minimumClusterSize ) { output . add ( c ) ; } } }
Processes the ellipses and creates clusters .
112
10
27,681
static void removeSingleConnections ( List < Node > cluster ) { List < Node > open = new ArrayList <> ( ) ; List < Node > future = new ArrayList <> ( ) ; open . addAll ( cluster ) ; while ( ! open . isEmpty ( ) ) { for ( int i = open . size ( ) - 1 ; i >= 0 ; i -- ) { Node n = open . get ( i ) ; if ( n . connections . size == 1 ) { // clear it's connections and remove it from the cluster int index = findNode ( n . which , cluster ) ; cluster . remove ( index ) ; // Remove the reference to this node from its one connection int parent = findNode ( n . connections . get ( 0 ) , cluster ) ; n . connections . reset ( ) ; if ( parent == - 1 ) throw new RuntimeException ( "BUG!" ) ; Node p = cluster . get ( parent ) ; int edge = p . connections . indexOf ( n . which ) ; if ( edge == - 1 ) throw new RuntimeException ( "BUG!" ) ; p . connections . remove ( edge ) ; // if the parent now only has one connection if ( p . connections . size == 1 ) { future . add ( p ) ; } } } open . clear ( ) ; List < Node > tmp = open ; open = future ; future = tmp ; } }
Removes stray connections that are highly likely to be noise . If a node has one connection it then removed . Then it s only connection is considered for removal .
293
32
27,682
void init ( List < EllipseInfo > ellipses ) { nodes . resize ( ellipses . size ( ) ) ; clusters . reset ( ) ; for ( int i = 0 ; i < ellipses . size ( ) ; i ++ ) { Node n = nodes . get ( i ) ; n . connections . reset ( ) ; n . which = i ; n . cluster = - 1 ; } nn . setPoints ( ellipses , true ) ; }
Recycles and initializes all internal data structures
101
10
27,683
void joinClusters ( int mouth , int food ) { List < Node > listMouth = clusters . get ( mouth ) ; List < Node > listFood = clusters . get ( food ) ; // put all members of food into mouth for ( int i = 0 ; i < listFood . size ( ) ; i ++ ) { listMouth . add ( listFood . get ( i ) ) ; listFood . get ( i ) . cluster = mouth ; } // zero food members listFood . clear ( ) ; }
Moves all the members of food into mouth
109
9
27,684
@ Override public void set ( int x , int y , int value ) { if ( ! isInBounds ( x , y ) ) throw new ImageAccessException ( "Requested pixel is out of bounds: " + x + " " + y ) ; data [ getIndex ( x , y ) ] = ( byte ) value ; }
Sets the value of the specified pixel .
72
9
27,685
public static void process ( GrayU8 orig , GrayS16 derivX , GrayS16 derivY ) { final byte [ ] data = orig . data ; final short [ ] imgX = derivX . data ; final short [ ] imgY = derivY . data ; final int width = orig . getWidth ( ) ; final int height = orig . getHeight ( ) - 1 ; //CONCURRENT_BELOW BoofConcurrency.loopFor(1,height,y->{ for ( int y = 1 ; y < height ; y ++ ) { int endX = width * y + width - 1 ; for ( int index = width * y + 1 ; index < endX ; index ++ ) { int v = ( data [ index + width + 1 ] & 0xFF ) - ( data [ index - width - 1 ] & 0xFF ) ; int w = ( data [ index + width - 1 ] & 0xFF ) - ( data [ index - width + 1 ] & 0xFF ) ; imgY [ index ] = ( short ) ( ( ( data [ index + width ] & 0xFF ) - ( data [ index - width ] & 0xFF ) ) * 2 + v + w ) ; imgX [ index ] = ( short ) ( ( ( data [ index + 1 ] & 0xFF ) - ( data [ index - 1 ] & 0xFF ) ) * 2 + v - w ) ; } } //CONCURRENT_ABOVE }); }
Computes derivative of GrayU8 . None of the images can be sub - images .
319
18
27,686
public static void process_sub ( GrayU8 orig , GrayS16 derivX , GrayS16 derivY ) { final byte [ ] data = orig . data ; final short [ ] imgX = derivX . data ; final short [ ] imgY = derivY . data ; final int width = orig . getWidth ( ) ; final int height = orig . getHeight ( ) - 1 ; final int strideSrc = orig . getStride ( ) ; //CONCURRENT_BELOW BoofConcurrency.loopFor(1,height,y->{ for ( int y = 1 ; y < height ; y ++ ) { int indexSrc = orig . startIndex + orig . stride * y + 1 ; final int endX = indexSrc + width - 2 ; int indexX = derivX . startIndex + derivX . stride * y + 1 ; int indexY = derivY . startIndex + derivY . stride * y + 1 ; for ( ; indexSrc < endX ; indexSrc ++ ) { int v = ( data [ indexSrc + strideSrc + 1 ] & 0xFF ) - ( data [ indexSrc - strideSrc - 1 ] & 0xFF ) ; int w = ( data [ indexSrc + strideSrc - 1 ] & 0xFF ) - ( data [ indexSrc - strideSrc + 1 ] & 0xFF ) ; imgY [ indexY ++ ] = ( short ) ( ( ( data [ indexSrc + strideSrc ] & 0xFF ) - ( data [ indexSrc - strideSrc ] & 0xFF ) ) * 2 + v + w ) ; imgX [ indexX ++ ] = ( short ) ( ( ( data [ indexSrc + 1 ] & 0xFF ) - ( data [ indexSrc - 1 ] & 0xFF ) ) * 2 + v - w ) ; } } //CONCURRENT_ABOVE }); }
Computes derivative of GrayU8 . Inputs can be sub - images .
420
16
27,687
public void setScaleFactors ( double ... scaleFactors ) { // see if the scale factors have not changed if ( scale != null && scale . length == scaleFactors . length ) { boolean theSame = true ; for ( int i = 0 ; i < scale . length ; i ++ ) { if ( scale [ i ] != scaleFactors [ i ] ) { theSame = false ; break ; } } // no changes needed if ( theSame ) return ; } // 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 .
142
7
27,688
public static double variance ( int [ ] histogram , double mean , int N ) { return variance ( histogram , mean , count ( histogram , N ) , N ) ; }
Computes the variance of pixel intensity values for a GrayU8 image represented by the given histogram .
38
21
27,689
public static double variance ( int [ ] histogram , double mean , int counts , int N ) { double sum = 0.0 ; for ( int i = 0 ; i < N ; i ++ ) { double d = i - mean ; sum += ( d * d ) * histogram [ i ] ; } return sum / counts ; }
Computes the variance of elements in the histogram
71
10
27,690
public static int count ( int [ ] histogram , int N ) { int counts = 0 ; for ( int i = 0 ; i < N ; i ++ ) { counts += histogram [ i ] ; } return counts ; }
Counts sum of all the bins inside the histogram
48
11
27,691
public static void maxf ( Planar < GrayF32 > inX , Planar < GrayF32 > inY , GrayF32 outX , GrayF32 outY ) { // input and output should be the same shape InputSanityCheck . checkSameShape ( inX , inY ) ; InputSanityCheck . reshapeOneIn ( inX , outX , outY ) ; // make sure that the pixel index is the same InputSanityCheck . checkIndexing ( inX , inY ) ; InputSanityCheck . checkIndexing ( outX , outY ) ; for ( int y = 0 ; y < inX . height ; y ++ ) { int indexIn = inX . startIndex + inX . stride * y ; int indexOut = outX . startIndex + outX . stride * y ; for ( int x = 0 ; x < inX . width ; x ++ , indexIn ++ , indexOut ++ ) { float maxValueX = inX . bands [ 0 ] . data [ indexIn ] ; float maxValueY = inY . bands [ 0 ] . data [ indexIn ] ; float maxNorm = maxValueX * maxValueX + maxValueY * maxValueY ; for ( int band = 1 ; band < inX . bands . length ; band ++ ) { float valueX = inX . bands [ band ] . data [ indexIn ] ; float valueY = inY . bands [ band ] . data [ indexIn ] ; float n = valueX * valueX + valueY * valueY ; if ( n > maxNorm ) { maxNorm = n ; maxValueX = valueX ; maxValueY = valueY ; } } outX . data [ indexOut ] = maxValueX ; outY . data [ indexOut ] = maxValueY ; } } }
Reduces the number of bands by selecting the band with the largest Frobenius norm and using its gradient to be the output gradient on a pixel - by - pixel basis
391
34
27,692
public static void histogram ( ) { BufferedImage buffered = UtilImageIO . loadImage ( UtilIO . pathExample ( imagePath ) ) ; GrayU8 gray = ConvertBufferedImage . convertFrom ( buffered , ( GrayU8 ) null ) ; GrayU8 adjusted = gray . createSameShape ( ) ; int histogram [ ] = new int [ 256 ] ; int transform [ ] = new int [ 256 ] ; ListDisplayPanel panel = new ListDisplayPanel ( ) ; ImageStatistics . histogram ( gray , 0 , histogram ) ; EnhanceImageOps . equalize ( histogram , transform ) ; EnhanceImageOps . applyTransform ( gray , transform , adjusted ) ; panel . addImage ( ConvertBufferedImage . convertTo ( adjusted , null ) , "Global" ) ; EnhanceImageOps . equalizeLocal ( gray , 50 , adjusted , 256 , null ) ; panel . addImage ( ConvertBufferedImage . convertTo ( adjusted , null ) , "Local" ) ; panel . addImage ( ConvertBufferedImage . convertTo ( gray , null ) , "Original" ) ; panel . setPreferredSize ( new Dimension ( gray . width , gray . height ) ) ; mainPanel . addItem ( panel , "Histogram" ) ; }
Histogram adjustment algorithms aim to spread out pixel intensity values uniformly across the allowed range . This if an image is dark it will have greater contrast and be brighter .
270
32
27,693
public static void sharpen ( ) { BufferedImage buffered = UtilImageIO . loadImage ( UtilIO . pathExample ( imagePath ) ) ; GrayU8 gray = ConvertBufferedImage . convertFrom ( buffered , ( GrayU8 ) null ) ; GrayU8 adjusted = gray . createSameShape ( ) ; ListDisplayPanel panel = new ListDisplayPanel ( ) ; EnhanceImageOps . sharpen4 ( gray , adjusted ) ; panel . addImage ( ConvertBufferedImage . convertTo ( adjusted , null ) , "Sharpen-4" ) ; EnhanceImageOps . sharpen8 ( gray , adjusted ) ; panel . addImage ( ConvertBufferedImage . convertTo ( adjusted , null ) , "Sharpen-8" ) ; panel . addImage ( ConvertBufferedImage . convertTo ( gray , null ) , "Original" ) ; panel . setPreferredSize ( new Dimension ( gray . width , gray . height ) ) ; mainPanel . addItem ( panel , "Sharpen" ) ; }
When an image is sharpened the intensity of edges are made more extreme while flat regions remain unchanged .
219
20
27,694
public boolean process ( T image ) { tracker . process ( image ) ; tick ++ ; inlierTracks . clear ( ) ; if ( first ) { addNewTracks ( ) ; first = false ; } else { if ( ! estimateMotion ( ) ) { return false ; } dropUnusedTracks ( ) ; int N = motionEstimator . getMatchSet ( ) . size ( ) ; if ( thresholdAdd <= 0 || N < thresholdAdd ) { changePoseToReference ( ) ; addNewTracks ( ) ; } // System.out.println(" num inliers = "+N+" num dropped "+numDropped+" total active "+tracker.getActivePairs().size()); } return true ; }
Estimates the motion given the left camera image . The latest information required by ImagePixelTo3D should be passed to the class before invoking this function .
156
31
27,695
private void addNewTracks ( ) { // System.out.println("----------- Adding new tracks ---------------"); tracker . spawnTracks ( ) ; List < PointTrack > spawned = tracker . getNewTracks ( null ) ; // estimate 3D coordinate using stereo vision for ( PointTrack t : spawned ) { Point2D3DTrack p = t . getCookie ( ) ; if ( p == null ) { t . cookie = p = new Point2D3DTrack ( ) ; } // discard point if it can't localized if ( ! pixelTo3D . process ( t . x , t . y ) || pixelTo3D . getW ( ) == 0 ) { tracker . dropTrack ( t ) ; } else { Point3D_F64 X = p . getLocation ( ) ; double w = pixelTo3D . getW ( ) ; X . set ( pixelTo3D . getX ( ) / w , pixelTo3D . getY ( ) / w , pixelTo3D . getZ ( ) / w ) ; // translate the point into the key frame // SePointOps_F64.transform(currToKey,X,X); // not needed since the current frame was just set to be the key frame p . lastInlier = tick ; pixelToNorm . compute ( t . x , t . y , p . observation ) ; } } }
Detects new features and computes their 3D coordinates
297
11
27,696
private boolean estimateMotion ( ) { List < PointTrack > active = tracker . getActiveTracks ( null ) ; List < Point2D3D > obs = new ArrayList <> ( ) ; for ( PointTrack t : active ) { Point2D3D p = t . getCookie ( ) ; pixelToNorm . compute ( t . x , t . y , p . observation ) ; obs . add ( p ) ; } // estimate the motion up to a scale factor in translation if ( ! motionEstimator . process ( obs ) ) return false ; if ( doublePass ) { if ( ! performSecondPass ( active , obs ) ) return false ; } tracker . finishTracking ( ) ; Se3_F64 keyToCurr ; if ( refine != null ) { keyToCurr = new Se3_F64 ( ) ; refine . fitModel ( motionEstimator . getMatchSet ( ) , motionEstimator . getModelParameters ( ) , keyToCurr ) ; } else { keyToCurr = motionEstimator . getModelParameters ( ) ; } keyToCurr . invert ( currToKey ) ; // mark tracks as being inliers and add to inlier list int N = motionEstimator . getMatchSet ( ) . size ( ) ; for ( int i = 0 ; i < N ; i ++ ) { int index = motionEstimator . getInputIndex ( i ) ; Point2D3DTrack t = active . get ( index ) . getCookie ( ) ; t . lastInlier = tick ; inlierTracks . add ( t ) ; } return true ; }
Estimates motion from the set of tracks and their 3D location
354
13
27,697
double scoreForTriangulation ( Motion motion ) { DMatrixRMaj H = new DMatrixRMaj ( 3 , 3 ) ; View viewA = motion . viewSrc ; View viewB = motion . viewDst ; // Compute initial estimate for H pairs . reset ( ) ; for ( int i = 0 ; i < motion . associated . size ( ) ; i ++ ) { AssociatedIndex ai = motion . associated . get ( i ) ; pairs . grow ( ) . set ( viewA . observationPixels . get ( ai . src ) , viewB . observationPixels . get ( ai . dst ) ) ; } if ( ! computeH . process ( pairs . toList ( ) , H ) ) return - 1 ; // remove bias from linear model if ( ! refineH . fitModel ( pairs . toList ( ) , H , H ) ) return - 1 ; // Compute 50% errors to avoid bias from outliers MultiViewOps . errorsHomographySymm ( pairs . toList ( ) , H , null , errors ) ; errors . sort ( ) ; return errors . getFraction ( 0.5 ) * Math . max ( 5 , pairs . size - 20 ) ; }
Compute score to decide which motion to initialize structure from . A homography is fit to the observations and the error compute . The homography should be a poor fit if the scene had 3D structure . The 50% homography error is then scaled by the number of pairs to bias the score good matches
259
61
27,698
public void configure ( LensDistortionNarrowFOV distortion , Se3_F64 worldToCamera ) { this . worldToCamera = worldToCamera ; normToPixel = distortion . distort_F64 ( false , true ) ; }
Specifies intrinsic camera parameters and the transform from world to camera .
50
13
27,699
public boolean transform ( Point3D_F64 worldPt , Point2D_F64 pixelPt ) { SePointOps_F64 . transform ( worldToCamera , worldPt , cameraPt ) ; // can't see the point if ( cameraPt . z <= 0 ) return false ; normToPixel . compute ( cameraPt . x / cameraPt . z , cameraPt . y / cameraPt . z , pixelPt ) ; return true ; }
Computes the observed location of the specified point in world coordinates in the camera pixel . If the object can t be viewed because it is behind the camera then false is returned .
105
35