idx
int64
0
165k
question
stringlengths
73
4.15k
target
stringlengths
5
918
len_question
int64
21
890
len_target
int64
3
255
26,500
protected double matchScale ( List < Point3D_F64 > nullPts , FastQueue < Point3D_F64 > controlWorldPts ) { Point3D_F64 meanNull = UtilPoint3D_F64 . mean ( nullPts , numControl , null ) ; Point3D_F64 meanWorld = UtilPoint3D_F64 . mean ( controlWorldPts . toList ( ) , numControl , null ) ; // compute the ratio of distance between world and null points from the centroid double top = 0 ; double bottom = 0 ; for ( int i = 0 ; i < numControl ; i ++ ) { Point3D_F64 wi = controlWorldPts . get ( i ) ; Point3D_F64 ni = nullPts . get ( i ) ; double dwx = wi . x - meanWorld . x ; double dwy = wi . y - meanWorld . y ; double dwz = wi . z - meanWorld . z ; double dnx = ni . x - meanNull . x ; double dny = ni . y - meanNull . y ; double dnz = ni . z - meanNull . z ; double n2 = dnx * dnx + dny * dny + dnz * dnz ; double w2 = dwx * dwx + dwy * dwy + dwz * dwz ; top += w2 ; bottom += n2 ; } // compute beta return Math . sqrt ( top / bottom ) ; }
Examines the distance each point is from the centroid to determine the scaling difference between world control points and the null points .
327
25
26,501
private double adjustBetaSign ( double beta , List < Point3D_F64 > nullPts ) { if ( beta == 0 ) return 0 ; int N = alphas . numRows ; int positiveCount = 0 ; for ( int i = 0 ; i < N ; i ++ ) { double z = 0 ; for ( int j = 0 ; j < numControl ; j ++ ) { Point3D_F64 c = nullPts . get ( j ) ; z += alphas . get ( i , j ) * c . z ; } if ( z > 0 ) positiveCount ++ ; } if ( positiveCount < N / 2 ) beta *= - 1 ; return beta ; }
Use the positive depth constraint to determine the sign of beta
148
11
26,502
protected void estimateCase1 ( double betas [ ] ) { betas [ 0 ] = matchScale ( nullPts [ 0 ] , controlWorldPts ) ; betas [ 0 ] = adjustBetaSign ( betas [ 0 ] , nullPts [ 0 ] ) ; betas [ 1 ] = 0 ; betas [ 2 ] = 0 ; betas [ 3 ] = 0 ; }
Simple analytical solution . Just need to solve for the scale difference in one set of potential control points .
84
20
26,503
protected void estimateCase3_planar ( double betas [ ] ) { relinearizeBeta . setNumberControl ( 3 ) ; relinearizeBeta . process ( L_full , y , betas ) ; refine ( betas ) ; }
If the data is planar use relinearize to estimate betas
54
15
26,504
private void gaussNewton ( double betas [ ] ) { A_temp . reshape ( L_full . numRows , numControl ) ; v_temp . reshape ( L_full . numRows , 1 ) ; x . reshape ( numControl , 1 , false ) ; // don't check numControl inside in hope that the JVM can optimize the code better if ( numControl == 4 ) { for ( int i = 0 ; i < numIterations ; i ++ ) { UtilLepetitEPnP . jacobian_Control4 ( L_full , betas , A_temp ) ; UtilLepetitEPnP . residuals_Control4 ( L_full , y , betas , v_temp . data ) ; if ( ! solver . setA ( A_temp ) ) return ; solver . solve ( v_temp , x ) ; for ( int j = 0 ; j < numControl ; j ++ ) { betas [ j ] -= x . data [ j ] ; } } } else { for ( int i = 0 ; i < numIterations ; i ++ ) { UtilLepetitEPnP . jacobian_Control3 ( L_full , betas , A_temp ) ; UtilLepetitEPnP . residuals_Control3 ( L_full , y , betas , v_temp . data ) ; if ( ! solver . setA ( A_temp ) ) return ; solver . solve ( v_temp , x ) ; for ( int j = 0 ; j < numControl ; j ++ ) { betas [ j ] -= x . data [ j ] ; } } } }
Optimize beta values using Gauss Newton .
371
9
26,505
public QrCodeEncoder addAutomatic ( String message ) { // very simple coding algorithm. Doesn't try to compress by using multiple formats if ( containsKanji ( message ) ) { // split into kanji and non-kanji segments int start = 0 ; boolean kanji = isKanji ( message . charAt ( 0 ) ) ; for ( int i = 0 ; i < message . length ( ) ; i ++ ) { if ( isKanji ( message . charAt ( i ) ) ) { if ( ! kanji ) { addAutomatic ( message . substring ( start , i ) ) ; start = i ; kanji = true ; } } else { if ( kanji ) { addKanji ( message . substring ( start , i ) ) ; start = i ; kanji = false ; } } } if ( kanji ) { addKanji ( message . substring ( start , message . length ( ) ) ) ; } else { addAutomatic ( message . substring ( start , message . length ( ) ) ) ; } return this ; } else if ( containsByte ( message ) ) { return addBytes ( message ) ; } else if ( containsAlphaNumeric ( message ) ) { return addAlphanumeric ( message ) ; } else { return addNumeric ( message ) ; } }
Select the encoding based on the letters in the message . A very simple algorithm is used internally .
284
19
26,506
public QrCodeEncoder addAlphanumeric ( String alphaNumeric ) { byte values [ ] = alphanumericToValues ( alphaNumeric ) ; MessageSegment segment = new MessageSegment ( ) ; segment . message = alphaNumeric ; segment . data = values ; segment . length = values . length ; segment . mode = QrCode . Mode . ALPHANUMERIC ; segment . encodedSizeBits += 4 ; segment . encodedSizeBits += 11 * ( segment . length / 2 ) ; if ( segment . length % 2 == 1 ) { segment . encodedSizeBits += 6 ; } segments . add ( segment ) ; return this ; }
Creates a QR - Code which encodes data in the alphanumeric format
142
16
26,507
public QrCodeEncoder addBytes ( byte [ ] data ) { StringBuilder builder = new StringBuilder ( data . length ) ; for ( int i = 0 ; i < data . length ; i ++ ) { builder . append ( ( char ) data [ i ] ) ; } MessageSegment segment = new MessageSegment ( ) ; segment . message = builder . toString ( ) ; segment . data = data ; segment . length = data . length ; segment . mode = QrCode . Mode . BYTE ; segment . encodedSizeBits += 4 ; segment . encodedSizeBits += 8 * segment . length ; segments . add ( segment ) ; return this ; }
Creates a QR - Code which encodes data in the byte format .
142
15
26,508
public QrCodeEncoder addKanji ( String message ) { byte [ ] bytes ; try { bytes = message . getBytes ( "Shift_JIS" ) ; } catch ( UnsupportedEncodingException ex ) { throw new IllegalArgumentException ( ex ) ; } MessageSegment segment = new MessageSegment ( ) ; segment . message = message ; segment . data = bytes ; segment . length = message . length ( ) ; segment . mode = QrCode . Mode . KANJI ; segment . encodedSizeBits += 4 ; segment . encodedSizeBits += 13 * segment . length ; segments . add ( segment ) ; return this ; }
Creates a QR - Code which encodes Kanji characters
141
12
26,509
private static int getLengthBits ( int version , int bitsA , int bitsB , int bitsC ) { int lengthBits ; if ( version < 10 ) lengthBits = bitsA ; else if ( version < 27 ) lengthBits = bitsB ; else lengthBits = bitsC ; return lengthBits ; }
Returns the length of the message length variable in bits . Dependent on version
70
15
26,510
public QrCode fixate ( ) { autoSelectVersionAndError ( ) ; // sanity check of code int expectedBitSize = bitsAtVersion ( qr . version ) ; qr . message = "" ; for ( MessageSegment m : segments ) { qr . message += m . message ; switch ( m . mode ) { case NUMERIC : encodeNumeric ( m . data , m . length ) ; break ; case ALPHANUMERIC : encodeAlphanumeric ( m . data , m . length ) ; break ; case BYTE : encodeBytes ( m . data , m . length ) ; break ; case KANJI : encodeKanji ( m . data , m . length ) ; break ; default : throw new RuntimeException ( "Unknown" ) ; } } if ( packed . size != expectedBitSize ) throw new RuntimeException ( "Bad size code. " + packed . size + " vs " + expectedBitSize ) ; int maxBits = QrCode . VERSION_INFO [ qr . version ] . codewords * 8 ; if ( packed . size > maxBits ) { throw new IllegalArgumentException ( "The message is longer than the max possible size" ) ; } if ( packed . size + 4 <= maxBits ) { // add the terminator to the bit stream packed . append ( 0b0000 , 4 , false ) ; } bitsToMessage ( packed ) ; if ( autoMask ) { qr . mask = selectMask ( qr ) ; } return qr ; }
Call this function after you are done adding to the QR code
328
12
26,511
static QrCodeMaskPattern selectMask ( QrCode qr ) { int N = qr . getNumberOfModules ( ) ; int totalBytes = QrCode . VERSION_INFO [ qr . version ] . codewords ; List < Point2D_I32 > locations = QrCode . LOCATION_BITS [ qr . version ] ; QrCodeMaskPattern bestMask = null ; double bestScore = Double . MAX_VALUE ; PackedBits8 bits = new PackedBits8 ( ) ; bits . size = totalBytes * 8 ; bits . data = qr . rawbits ; if ( bits . size > locations . size ( ) ) throw new RuntimeException ( "BUG in code" ) ; // Bit value of 0 = white. 1 = black QrCodeCodeWordLocations matrix = new QrCodeCodeWordLocations ( qr . version ) ; for ( QrCodeMaskPattern mask : QrCodeMaskPattern . values ( ) ) { double score = scoreMask ( N , locations , bits , matrix , mask ) ; if ( score < bestScore ) { bestScore = score ; bestMask = mask ; } } return bestMask ; }
Selects a mask by minimizing the appearance of certain patterns . This is inspired by what was described in the reference manual . I had a hard time understanding some of the specifics so I improvised .
256
38
26,512
static void detectAdjacentAndPositionPatterns ( int N , QrCodeCodeWordLocations matrix , FoundFeatures features ) { for ( int foo = 0 ; foo < 2 ; foo ++ ) { for ( int row = 0 ; row < N ; row ++ ) { int index = row * N ; for ( int col = 1 ; col < N ; col ++ , index ++ ) { if ( matrix . data [ index ] == matrix . data [ index + 1 ] ) features . adjacent ++ ; } index = row * N ; for ( int col = 6 ; col < N ; col ++ , index ++ ) { if ( matrix . data [ index ] && ! matrix . data [ index + 1 ] && matrix . data [ index + 2 ] && matrix . data [ index + 3 ] && matrix . data [ index + 4 ] && ! matrix . data [ index + 5 ] && matrix . data [ index + 6 ] ) features . position ++ ; } } CommonOps_BDRM . transposeSquare ( matrix ) ; } // subtract out false positives by the mask applied to position patterns, timing, mode features . adjacent -= 8 * 9 + 2 * 9 * 8 + ( N - 18 ) * 2 ; }
Look for adjacent blocks that are the same color as well as patterns that could be confused for position patterns 1 1 3 1 1 in vertical and horizontal directions
257
30
26,513
private int bitsAtVersion ( int version ) { int total = 0 ; for ( int i = 0 ; i < segments . size ( ) ; i ++ ) { total += segments . get ( i ) . sizeInBits ( version ) ; } return total ; }
Computes how many bits it takes to encode the message at this version number
56
15
26,514
public boolean process ( DMatrixRMaj F21 , double x1 , double y1 , double x2 , double y2 , Point2D_F64 p1 , Point2D_F64 p2 ) { // translations used to move points to the origin assignTinv ( T1 , x1 , y1 ) ; assignTinv ( T2 , x2 , y2 ) ; // take F to the new coordinate system // F1 = T2'*F*T1 PerspectiveOps . multTranA ( T2 , F21 , T1 , Ft ) ; extract . process ( Ft , e1 , e2 ) ; // normalize so that e[x]*e[x] + e[y]*e[y] == 1 normalizeEpipole ( e1 ) ; normalizeEpipole ( e2 ) ; assignR ( R1 , e1 ) ; assignR ( R2 , e2 ) ; // Ft = R2*Ft*R1' PerspectiveOps . multTranC ( R2 , Ft , R1 , Ft ) ; double f1 = e1 . z ; double f2 = e2 . z ; double a = Ft . get ( 1 , 1 ) ; double b = Ft . get ( 1 , 2 ) ; double c = Ft . get ( 2 , 1 ) ; double d = Ft . get ( 2 , 2 ) ; if ( ! solvePolynomial ( f1 , f2 , a , b , c , d ) ) return false ; if ( ! selectBestSolution ( rootFinder . getRoots ( ) , f1 , f2 , a , b , c , d ) ) return false ; // find the closeset point on the two lines below to the origin double t = solutionT ; l1 . set ( t * f1 , 1 , - t ) ; l2 . set ( - f2 * ( c * t + d ) , a * t + b , c * t + d ) ; closestPointToOrigin ( l1 , e1 ) ; // recycle epipole storage closestPointToOrigin ( l2 , e2 ) ; // original coordinates originalCoordinates ( T1 , R1 , e1 ) ; originalCoordinates ( T2 , R2 , e2 ) ; // back to 2D coordinates p1 . set ( e1 . x / e1 . z , e1 . y / e1 . z ) ; p2 . set ( e2 . x / e2 . z , e2 . y / e2 . z ) ; return true ; }
Minimizes the geometric error
552
6
26,515
public static boolean convert ( LineGeneral2D_F64 [ ] lines , Polygon2D_F64 poly ) { for ( int i = 0 ; i < poly . size ( ) ; i ++ ) { int j = ( i + 1 ) % poly . size ( ) ; if ( null == Intersection2D_F64 . intersection ( lines [ i ] , lines [ j ] , poly . get ( j ) ) ) return false ; } return true ; }
Finds the intersections between the four lines and converts it into a quadrilateral
100
16
26,516
public static void process ( GrayU8 orig , GrayF32 deriv ) { deriv . reshape ( orig . width , orig . height ) ; if ( BoofConcurrency . USE_CONCURRENT ) { DerivativeLaplacian_Inner_MT . process ( orig , deriv ) ; } else { DerivativeLaplacian_Inner . process ( orig , deriv ) ; } // if( border != null ) { // border.setImage(orig); // ConvolveJustBorder_General_SB.convolve(kernel_I32, border,deriv); // } }
Computes Laplacian on an U8 image but outputs derivative in a F32 image . Removes a step when processing images for feature detection
128
30
26,517
public void process ( List < List < SquareNode > > clusters ) { grids . reset ( ) ; for ( int i = 0 ; i < clusters . size ( ) ; i ++ ) { if ( checkPreconditions ( clusters . get ( i ) ) ) processCluster ( clusters . get ( i ) ) ; } }
Converts all the found clusters into grids if they are valid .
69
13
26,518
protected boolean checkPreconditions ( List < SquareNode > cluster ) { for ( int i = 0 ; i < cluster . size ( ) ; i ++ ) { SquareNode n = cluster . get ( i ) ; for ( int j = 0 ; j < n . square . size ( ) ; j ++ ) { SquareEdge e0 = n . edges [ j ] ; if ( e0 == null ) continue ; for ( int k = j + 1 ; k < n . square . size ( ) ; k ++ ) { SquareEdge e1 = n . edges [ k ] ; if ( e1 == null ) continue ; if ( e0 . destination ( n ) == e1 . destination ( n ) ) { return false ; } } } } return true ; }
Checks basic preconditions . 1 ) No node may be linked two more than once
161
18
26,519
protected void processCluster ( List < SquareNode > cluster ) { invalid = false ; // handle a special case if ( cluster . size ( ) == 1 ) { SquareNode n = cluster . get ( 0 ) ; if ( n . getNumberOfConnections ( ) == 0 ) { SquareGrid grid = grids . grow ( ) ; grid . reset ( ) ; grid . columns = grid . rows = 1 ; grid . nodes . add ( n ) ; return ; } } for ( int i = 0 ; i < cluster . size ( ) ; i ++ ) { cluster . get ( i ) . graph = SquareNode . RESET_GRAPH ; } SquareNode seed = findSeedNode ( cluster ) ; if ( seed == null ) return ; // find the first row List < SquareNode > firstRow ; if ( seed . getNumberOfConnections ( ) == 1 ) { firstRow = firstRow1 ( seed ) ; } else if ( seed . getNumberOfConnections ( ) == 2 ) { firstRow = firstRow2 ( seed ) ; } else { throw new RuntimeException ( "BUG" ) ; } if ( invalid || firstRow == null ) return ; // Add the next rows to the list, one after another List < List < SquareNode > > listRows = new ArrayList <> ( ) ; // TODO remove memory declaration here listRows . add ( firstRow ) ; while ( true ) { List < SquareNode > previous = listRows . get ( listRows . size ( ) - 1 ) ; if ( ! addNextRow ( previous . get ( 0 ) , listRows ) ) { break ; } } if ( invalid || listRows . size ( ) < 2 ) return ; // re-organize into a grid data structure SquareGrid grid = assembleGrid ( listRows ) ; // check the grids connectivity if ( grid == null || ! checkEdgeCount ( grid ) ) { grids . removeTail ( ) ; } }
Converts the cluster into a grid data structure . If its not a grid then nothing happens
417
18
26,520
private SquareGrid assembleGrid ( List < List < SquareNode > > listRows ) { SquareGrid grid = grids . grow ( ) ; grid . reset ( ) ; List < SquareNode > row0 = listRows . get ( 0 ) ; List < SquareNode > row1 = listRows . get ( 1 ) ; int offset = row0 . get ( 0 ) . getNumberOfConnections ( ) == 1 ? 0 : 1 ; grid . columns = row0 . size ( ) + row1 . size ( ) ; grid . rows = listRows . size ( ) ; // initialize grid to null for ( int i = 0 ; i < grid . columns * grid . rows ; i ++ ) { grid . nodes . add ( null ) ; } // fill in the grid for ( int row = 0 ; row < listRows . size ( ) ; row ++ ) { List < SquareNode > list = listRows . get ( row ) ; int startCol = offset - row % 2 == 0 ? 0 : 1 ; // make sure there is the expected number of elements in the row int adjustedLength = grid . columns - startCol ; if ( ( adjustedLength ) - adjustedLength / 2 != list . size ( ) ) { return null ; } int listIndex = 0 ; for ( int col = startCol ; col < grid . columns ; col += 2 ) { grid . set ( row , col , list . get ( listIndex ++ ) ) ; } } return grid ; }
Converts the list of rows into a grid . Since it is a chessboard pattern some of the grid elements will be null .
314
26
26,521
private boolean checkEdgeCount ( SquareGrid grid ) { int left = 0 , right = grid . columns - 1 ; int top = 0 , bottom = grid . rows - 1 ; for ( int row = 0 ; row < grid . rows ; row ++ ) { boolean skip = grid . get ( row , 0 ) == null ; for ( int col = 0 ; col < grid . columns ; col ++ ) { SquareNode n = grid . get ( row , col ) ; if ( skip ) { if ( n != null ) return false ; } else { boolean horizontalEdge = col == left || col == right ; boolean verticalEdge = row == top || row == bottom ; boolean outer = horizontalEdge || verticalEdge ; int connections = n . getNumberOfConnections ( ) ; if ( outer ) { if ( horizontalEdge && verticalEdge ) { if ( connections != 1 ) return false ; } else if ( connections != 2 ) return false ; } else { if ( connections != 4 ) return false ; } } skip = ! skip ; } } return true ; }
Looks at the edge count in each node and sees if it has the expected number
220
16
26,522
List < SquareNode > firstRow1 ( SquareNode seed ) { for ( int i = 0 ; i < seed . square . size ( ) ; i ++ ) { if ( isOpenEdge ( seed , i ) ) { List < SquareNode > list = new ArrayList <> ( ) ; seed . graph = 0 ; // Doesn't know which direction it can traverse along. See figure that out // by looking at the node its linked to int corner = seed . edges [ i ] . destinationSide ( seed ) ; SquareNode dst = seed . edges [ i ] . destination ( seed ) ; int l = addOffset ( corner , - 1 , dst . square . size ( ) ) ; int u = addOffset ( corner , 1 , dst . square . size ( ) ) ; if ( dst . edges [ u ] != null ) { list . add ( seed ) ; if ( ! addToRow ( seed , i , - 1 , true , list ) ) return null ; } else if ( dst . edges [ l ] != null ) { List < SquareNode > tmp = new ArrayList <> ( ) ; if ( ! addToRow ( seed , i , 1 , true , tmp ) ) return null ; flipAdd ( tmp , list ) ; list . add ( seed ) ; } else { // there is only a single node below it list . add ( seed ) ; } return list ; } } throw new RuntimeException ( "BUG" ) ; }
Adds the first row to the list of rows when the seed element has only one edge
305
17
26,523
List < SquareNode > firstRow2 ( SquareNode seed ) { int indexLower = lowerEdgeIndex ( seed ) ; int indexUpper = addOffset ( indexLower , 1 , seed . square . size ( ) ) ; List < SquareNode > listDown = new ArrayList <> ( ) ; List < SquareNode > list = new ArrayList <> ( ) ; if ( ! addToRow ( seed , indexUpper , 1 , true , listDown ) ) return null ; flipAdd ( listDown , list ) ; list . add ( seed ) ; seed . graph = 0 ; if ( ! addToRow ( seed , indexLower , - 1 , true , list ) ) return null ; return list ; }
Adds the first row to the list of rows when the seed element has two edges
151
16
26,524
static int lowerEdgeIndex ( SquareNode node ) { for ( int i = 0 ; i < node . square . size ( ) ; i ++ ) { if ( isOpenEdge ( node , i ) ) { int next = addOffset ( i , 1 , node . square . size ( ) ) ; if ( isOpenEdge ( node , next ) ) { return i ; } if ( i == 0 ) { int previous = node . square . size ( ) - 1 ; if ( isOpenEdge ( node , previous ) ) { return previous ; } } return i ; } } throw new RuntimeException ( "BUG!" ) ; }
Returns the open corner index which is first . Assuming that there are two adjacent corners .
132
17
26,525
static boolean isOpenEdge ( SquareNode node , int index ) { if ( node . edges [ index ] == null ) return false ; int marker = node . edges [ index ] . destination ( node ) . graph ; return marker == SquareNode . RESET_GRAPH ; }
Is the edge open and can be traversed to? Can t be null and can t have the marker set to a none RESET_GRAPH value .
58
32
26,526
boolean addToRow ( SquareNode n , int corner , int sign , boolean skip , List < SquareNode > row ) { SquareEdge e ; while ( ( e = n . edges [ corner ] ) != null ) { if ( e . a == n ) { n = e . b ; corner = e . sideB ; } else { n = e . a ; corner = e . sideA ; } if ( ! skip ) { if ( n . graph != SquareNode . RESET_GRAPH ) { // This should never happen in a valid grid. It can happen if two nodes link to each other multiple // times. Other situations as well invalid = true ; return false ; } n . graph = 0 ; row . add ( n ) ; } skip = ! skip ; sign *= - 1 ; corner = addOffset ( corner , sign , n . square . size ( ) ) ; } return true ; }
Given a node and the corner to the next node down the line add to the list every other node until it hits the end of the row .
192
29
26,527
static SquareNode findSeedNode ( List < SquareNode > cluster ) { SquareNode seed = null ; for ( int i = 0 ; i < cluster . size ( ) ; i ++ ) { SquareNode n = cluster . get ( i ) ; int numConnections = n . getNumberOfConnections ( ) ; if ( numConnections == 0 || numConnections > 2 ) continue ; seed = n ; break ; } return seed ; }
Finds a seed with 1 or 2 edges .
94
10
26,528
public void process ( GrayF32 input ) { // System.out.println("ENTER CHESSBOARD CORNER "+input.width+" x "+input.height); borderImg . setImage ( input ) ; gradient . process ( input , derivX , derivY ) ; interpX . setImage ( derivX ) ; interpY . setImage ( derivY ) ; cornerIntensity . process ( derivX , derivY , intensity ) ; intensityInterp . setImage ( intensity ) ; // adjust intensity value so that its between 0 and levels for OTSU thresholding float featmax = ImageStatistics . max ( intensity ) ; PixelMath . multiply ( intensity , GRAY_LEVELS / featmax , intensity ) ; // int N = intensity.width*input.height; // for (int i = 0; i < N; i++) { // if( intensity.data[i] <= 2f ) { // intensity.data[i] = 0f; // } // } // convert into a binary image with high feature intensity regions being 1 inputToBinary . process ( intensity , binary ) ; // find the small regions. Th se might be where corners are contourFinder . process ( binary ) ; corners . reset ( ) ; List < ContourPacked > packed = contourFinder . getContours ( ) ; // System.out.println(" * features.size = "+packed.size()); for ( int i = 0 ; i < packed . size ( ) ; i ++ ) { contourFinder . loadContour ( i , contour ) ; ChessboardCorner c = corners . grow ( ) ; UtilPoint2D_I32 . mean ( contour . toList ( ) , c ) ; // compensate for the bias caused by how pixels are counted. // Example: a 4x4 region is expected. Center should be at (2,2) but will instead be (1.5,1.5) c . x += 0.5 ; c . y += 0.5 ; computeFeatures ( c . x , c . y , c ) ; // System.out.println("radius = "+radius+" angle = "+c.angle); // System.out.println("intensity "+c.intensity); if ( c . intensity < cornerIntensityThreshold ) { corners . removeTail ( ) ; } else if ( useMeanShift ) { meanShiftLocation ( c ) ; // TODO does it make sense to use mean shift first? computeFeatures ( c . x , c . y , c ) ; } } // System.out.println("Dropped "+dropped+" / "+packed.size()); }
Computes chessboard corners inside the image
567
8
26,529
public void meanShiftLocation ( ChessboardCorner c ) { float meanX = ( float ) c . x ; float meanY = ( float ) c . y ; // The peak in intensity will be in -r to r region, but smaller values will be -2*r to 2*r int radius = this . shiRadius * 2 ; for ( int iteration = 0 ; iteration < 5 ; iteration ++ ) { float adjX = 0 ; float adjY = 0 ; float total = 0 ; for ( int y = - radius ; y < radius ; y ++ ) { float yy = y ; for ( int x = - radius ; x < radius ; x ++ ) { float xx = x ; float v = intensityInterp . get ( meanX + xx , meanY + yy ) ; // Again, this adjustment to account for how pixels are counted. See center from contour computation adjX += ( xx + 0.5 ) * v ; adjY += ( yy + 0.5 ) * v ; total += v ; } } meanX += adjX / total ; meanY += adjY / total ; } c . x = meanX ; c . y = meanY ; }
Use mean shift to improve the accuracy of the corner s location . A kernel is selected which is slightly larger than the flat intensity of the corner should be when over a chess pattern .
254
36
26,530
public void setThreadPoolSize ( int threads ) { if ( threads <= 0 ) throw new IllegalArgumentException ( "Number of threads must be greater than 0" ) ; if ( verbose ) Log . i ( TAG , "setThreadPoolSize(" + threads + ")" ) ; threadPool . setCorePoolSize ( threads ) ; threadPool . setMaximumPoolSize ( threads ) ; }
Specifies the number of threads in the thread - pool . If this is set to a value greater than one you better know how to write concurrent code or else you re going to have a bad time .
83
41
26,531
@ Override protected int selectResolution ( int widthTexture , int heightTexture , Size [ ] resolutions ) { // just wanted to make sure this has been cleaned up timeOfLastUpdated = 0 ; // select the resolution here int bestIndex = - 1 ; double bestAspect = Double . MAX_VALUE ; double bestArea = 0 ; for ( int i = 0 ; i < resolutions . length ; i ++ ) { Size s = resolutions [ i ] ; int width = s . getWidth ( ) ; int height = s . getHeight ( ) ; double aspectScore = Math . abs ( width * height - targetResolution ) ; if ( aspectScore < bestAspect ) { bestIndex = i ; bestAspect = aspectScore ; bestArea = width * height ; } else if ( Math . abs ( aspectScore - bestArea ) <= 1e-8 ) { bestIndex = i ; double area = width * height ; if ( area > bestArea ) { bestArea = area ; } } } return bestIndex ; }
Selects a resolution which has the number of pixels closest to the requested value
215
15
26,532
protected void setImageType ( ImageType type , ColorFormat colorFormat ) { synchronized ( boofImage . imageLock ) { boofImage . colorFormat = colorFormat ; if ( ! boofImage . imageType . isSameType ( type ) ) { boofImage . imageType = type ; boofImage . stackImages . clear ( ) ; } synchronized ( lockTiming ) { totalConverted = 0 ; periodConvert . reset ( ) ; } } }
Changes the type of image the camera frame is converted to
99
11
26,533
protected void renderBitmapImage ( BitmapMode mode , ImageBase image ) { switch ( mode ) { case UNSAFE : { if ( image . getWidth ( ) == bitmap . getWidth ( ) && image . getHeight ( ) == bitmap . getHeight ( ) ) ConvertBitmap . boofToBitmap ( image , bitmap , bitmapTmp ) ; } break ; case DOUBLE_BUFFER : { // TODO if there are multiple processing threads bad stuff will happen here. Need one work buffer // per thread // convert the image. this can be a slow operation if ( image . getWidth ( ) == bitmapWork . getWidth ( ) && image . getHeight ( ) == bitmapWork . getHeight ( ) ) ConvertBitmap . boofToBitmap ( image , bitmapWork , bitmapTmp ) ; // swap the two buffers. If it's locked don't swap. This will skip a frame but will not cause // a significant slow down if ( bitmapLock . tryLock ( ) ) { try { Bitmap tmp = bitmapWork ; bitmapWork = bitmap ; bitmap = tmp ; } finally { bitmapLock . unlock ( ) ; } } } break ; } }
Renders the bitmap image to output . If you don t wish to have this behavior then override this function . Jsut make sure you respect the bitmap mode or the image might not render as desired or you could crash the app .
262
49
26,534
protected void onDrawFrame ( SurfaceView view , Canvas canvas ) { // Code below is usefull when debugging display issues // Paint paintFill = new Paint(); // paintFill.setColor(Color.RED); // paintFill.setStyle(Paint.Style.FILL); // Paint paintBorder = new Paint(); // paintBorder.setColor(Color.BLUE); // paintBorder.setStyle(Paint.Style.STROKE); // paintBorder.setStrokeWidth(6*displayMetrics.density); // // Rect r = new Rect(0,0,view.getWidth(),view.getHeight()); // canvas.drawRect(r,paintFill); // canvas.drawRect(r,paintBorder); switch ( bitmapMode ) { case UNSAFE : canvas . drawBitmap ( this . bitmap , imageToView , null ) ; break ; case DOUBLE_BUFFER : bitmapLock . lock ( ) ; try { canvas . drawBitmap ( this . bitmap , imageToView , null ) ; } finally { bitmapLock . unlock ( ) ; } break ; } }
Renders the visualizations . Override and invoke super to add your own
243
15
26,535
public static < I extends ImageGray < I > , D extends ImageGray < D > > GeneralFeatureIntensity < I , D > median ( int radius , Class < I > imageType ) { BlurStorageFilter < I > filter = FactoryBlurFilter . median ( ImageType . single ( imageType ) , radius ) ; return new WrapperMedianCornerIntensity <> ( filter ) ; }
Feature intensity for median corner detector .
86
7
26,536
public static < I extends ImageGray < I > , D extends ImageGray < D > > GeneralFeatureIntensity < I , D > hessian ( HessianBlobIntensity . Type type , Class < D > derivType ) { return new WrapperHessianBlobIntensity <> ( type , derivType ) ; }
Blob detector which uses the image s second order derivatives directly .
71
13
26,537
@ Override public List < PointTrack > getInactiveTracks ( List < PointTrack > list ) { if ( list == null ) list = new ArrayList <> ( ) ; return list ; }
KLT does not have inactive tracks since all tracks are dropped if a problem occurs .
43
17
26,538
@ Override protected void horizontal ( ) { float [ ] dataX = derivX . data ; float [ ] dataY = derivY . data ; float [ ] hXX = horizXX . data ; float [ ] hXY = horizXY . data ; float [ ] hYY = horizYY . data ; final int imgHeight = derivX . getHeight ( ) ; final int imgWidth = derivX . getWidth ( ) ; int windowWidth = radius * 2 + 1 ; int radp1 = radius + 1 ; BoofConcurrency . loopFor ( 0 , imgHeight , row -> { int pix = row * imgWidth ; int end = pix + windowWidth ; float totalXX = 0 ; float totalXY = 0 ; float totalYY = 0 ; int indexX = derivX . startIndex + row * derivX . stride ; int indexY = derivY . startIndex + row * derivY . stride ; for ( ; pix < end ; pix ++ ) { float dx = dataX [ indexX ++ ] ; float dy = dataY [ indexY ++ ] ; totalXX += dx * dx ; totalXY += dx * dy ; totalYY += dy * dy ; } hXX [ pix - radp1 ] = totalXX ; hXY [ pix - radp1 ] = totalXY ; hYY [ pix - radp1 ] = totalYY ; end = row * imgWidth + imgWidth ; for ( ; pix < end ; pix ++ , indexX ++ , indexY ++ ) { float dx = dataX [ indexX - windowWidth ] ; float dy = dataY [ indexY - windowWidth ] ; // saving these multiplications in an array to avoid recalculating them made // the algorithm about 50% slower totalXX -= dx * dx ; totalXY -= dx * dy ; totalYY -= dy * dy ; dx = dataX [ indexX ] ; dy = dataY [ indexY ] ; totalXX += dx * dx ; totalXY += dx * dy ; totalYY += dy * dy ; hXX [ pix - radius ] = totalXX ; hXY [ pix - radius ] = totalXY ; hYY [ pix - radius ] = totalYY ; } } ) ; }
Compute the derivative sum along the x - axis while taking advantage of duplicate calculations for each window .
477
20
26,539
@ Override protected void vertical ( GrayF32 intensity ) { float [ ] hXX = horizXX . data ; float [ ] hXY = horizXY . data ; float [ ] hYY = horizYY . data ; final float [ ] inten = intensity . data ; final int imgHeight = horizXX . getHeight ( ) ; final int imgWidth = horizXX . getWidth ( ) ; final int kernelWidth = radius * 2 + 1 ; final int startX = radius ; final int endX = imgWidth - radius ; final int backStep = kernelWidth * imgWidth ; BoofConcurrency . loopBlocks ( radius , imgHeight - radius , ( y0 , y1 ) -> { final float [ ] tempXX = work . pop ( ) ; final float [ ] tempXY = work . pop ( ) ; final float [ ] tempYY = work . pop ( ) ; for ( int x = startX ; x < endX ; x ++ ) { // defines the A matrix, from which the eigenvalues are computed int srcIndex = x + ( y0 - radius ) * imgWidth ; int destIndex = imgWidth * y0 + x ; float totalXX = 0 , totalXY = 0 , totalYY = 0 ; int indexEnd = srcIndex + imgWidth * kernelWidth ; for ( ; srcIndex < indexEnd ; srcIndex += imgWidth ) { totalXX += hXX [ srcIndex ] ; totalXY += hXY [ srcIndex ] ; totalYY += hYY [ srcIndex ] ; } tempXX [ x ] = totalXX ; tempXY [ x ] = totalXY ; tempYY [ x ] = totalYY ; // compute the eigen values inten [ destIndex ] = this . intensity . compute ( totalXX , totalXY , totalYY ) ; destIndex += imgWidth ; } // change the order it is processed in to reduce cache misses for ( int y = y0 + 1 ; y < y1 ; y ++ ) { int srcIndex = ( y + radius ) * imgWidth + startX ; int destIndex = y * imgWidth + startX ; for ( int x = startX ; x < endX ; x ++ , srcIndex ++ , destIndex ++ ) { float totalXX = tempXX [ x ] - hXX [ srcIndex - backStep ] ; tempXX [ x ] = totalXX += hXX [ srcIndex ] ; float totalXY = tempXY [ x ] - hXY [ srcIndex - backStep ] ; tempXY [ x ] = totalXY += hXY [ srcIndex ] ; float totalYY = tempYY [ x ] - hYY [ srcIndex - backStep ] ; tempYY [ x ] = totalYY += hYY [ srcIndex ] ; inten [ destIndex ] = this . intensity . compute ( totalXX , totalXY , totalYY ) ; } } work . recycle ( tempXX ) ; work . recycle ( tempXY ) ; work . recycle ( tempYY ) ; } ) ; }
Compute the derivative sum along the y - axis while taking advantage of duplicate calculations for each window and avoiding cache misses . Then compute the eigen values
633
30
26,540
public static < Input extends ImageGray < Input > , Output extends ImageGray < Output > > void distortSingle ( Input input , Output output , PixelTransform < Point2D_F32 > transform , InterpolationType interpType , BorderType borderType ) { boolean skip = borderType == BorderType . SKIP ; if ( skip ) borderType = BorderType . EXTENDED ; Class < Input > inputType = ( Class < Input > ) input . getClass ( ) ; Class < Output > outputType = ( Class < Output > ) input . getClass ( ) ; InterpolatePixelS < Input > interp = FactoryInterpolation . createPixelS ( 0 , 255 , interpType , borderType , inputType ) ; ImageDistort < Input , Output > distorter = FactoryDistort . distortSB ( false , interp , outputType ) ; distorter . setRenderAll ( ! skip ) ; distorter . setModel ( transform ) ; distorter . apply ( input , output ) ; }
Applies a pixel transform to a single band image . Easier to use function .
213
17
26,541
public static < Input extends ImageGray < Input > , Output extends ImageGray < Output > > void distortSingle ( Input input , Output output , boolean renderAll , PixelTransform < Point2D_F32 > transform , InterpolatePixelS < Input > interp ) { Class < Output > inputType = ( Class < Output > ) input . getClass ( ) ; ImageDistort < Input , Output > distorter = FactoryDistort . distortSB ( false , interp , inputType ) ; distorter . setRenderAll ( renderAll ) ; distorter . setModel ( transform ) ; distorter . apply ( input , output ) ; }
Applies a pixel transform to a single band image . More flexible but order to use function .
135
19
26,542
@ Deprecated public static < T extends ImageBase < T > > void scale ( T input , T output , BorderType borderType , InterpolationType interpType ) { PixelTransformAffine_F32 model = DistortSupport . transformScale ( output , input , null ) ; if ( input instanceof ImageGray ) { distortSingle ( ( ImageGray ) input , ( ImageGray ) output , model , interpType , borderType ) ; } else if ( input instanceof Planar ) { distortPL ( ( Planar ) input , ( Planar ) output , model , borderType , interpType ) ; } }
Rescales the input image and writes the results into the output image . The scale factor is determined independently of the width and height .
132
27
26,543
public static RectangleLength2D_I32 boundBox ( int srcWidth , int srcHeight , int dstWidth , int dstHeight , Point2D_F32 work , PixelTransform < Point2D_F32 > transform ) { RectangleLength2D_I32 ret = boundBox ( srcWidth , srcHeight , work , transform ) ; int x0 = ret . x0 ; int y0 = ret . y0 ; int x1 = ret . x0 + ret . width ; int y1 = ret . y0 + ret . height ; if ( x0 < 0 ) x0 = 0 ; if ( x1 > dstWidth ) x1 = dstWidth ; if ( y0 < 0 ) y0 = 0 ; if ( y1 > dstHeight ) y1 = dstHeight ; return new RectangleLength2D_I32 ( x0 , y0 , x1 - x0 , y1 - y0 ) ; }
Finds an axis - aligned bounding box which would contain a image after it has been transformed . A sanity check is done to made sure it is contained inside the destination image s bounds . If it is totally outside then a rectangle with negative width or height is returned .
201
54
26,544
public boolean update ( Image input , RectangleRotate_F64 output ) { if ( trackLost ) return false ; trackFeatures ( input , region ) ; // See if there are enough points remaining. use of config.numberOfSamples is some what arbitrary if ( pairs . size ( ) < config . numberOfSamples ) { System . out . println ( "Lack of sample pairs" ) ; trackLost = true ; return false ; } // find the motion using tracked features if ( ! estimateMotion . process ( pairs . toList ( ) ) ) { System . out . println ( "estimate motion failed" ) ; trackLost = true ; return false ; } if ( estimateMotion . getFitQuality ( ) > config . robustMaxError ) { System . out . println ( "exceeded Max estimation error" ) ; trackLost = true ; return false ; } // update the target's location using the found motion ScaleTranslateRotate2D model = estimateMotion . getModelParameters ( ) ; region . width *= model . scale ; region . height *= model . scale ; double c = Math . cos ( model . theta ) ; double s = Math . sin ( model . theta ) ; double x = region . cx ; double y = region . cy ; region . cx = ( x * c - y * s ) * model . scale + model . transX ; region . cy = ( x * s + y * c ) * model . scale + model . transY ; region . theta += model . theta ; output . set ( region ) ; // make the current image into the previous image swapImages ( ) ; return true ; }
Given the input image compute the new location of the target region and store the results in output .
351
19
26,545
private void trackFeatures ( Image input , RectangleRotate_F64 region ) { pairs . reset ( ) ; currentImage . process ( input ) ; for ( int i = 0 ; i < currentImage . getNumLayers ( ) ; i ++ ) { Image layer = currentImage . getLayer ( i ) ; gradient . process ( layer , currentDerivX [ i ] , currentDerivY [ i ] ) ; } // convert to float to avoid excessive conversions from double to float float cx = ( float ) region . cx ; float cy = ( float ) region . cy ; float height = ( float ) ( region . height ) ; float width = ( float ) ( region . width ) ; float c = ( float ) Math . cos ( region . theta ) ; float s = ( float ) Math . sin ( region . theta ) ; float p = 1.0f / ( config . numberOfSamples - 1 ) ; for ( int i = 0 ; i < config . numberOfSamples ; i ++ ) { float y = ( p * i - 0.5f ) * height ; for ( int j = 0 ; j < config . numberOfSamples ; j ++ ) { float x = ( p * j - 0.5f ) * width ; float xx = cx + x * c - y * s ; float yy = cy + x * s + y * c ; // track in the forward direction track . x = xx ; track . y = yy ; klt . setImage ( previousImage , previousDerivX , previousDerivY ) ; if ( ! klt . setDescription ( track ) ) { continue ; } klt . setImage ( currentImage , currentDerivX , currentDerivY ) ; KltTrackFault fault = klt . track ( track ) ; if ( fault != KltTrackFault . SUCCESS ) { continue ; } float xc = track . x ; float yc = track . y ; // validate by tracking backwards if ( ! klt . setDescription ( track ) ) { continue ; } klt . setImage ( previousImage , previousDerivX , previousDerivY ) ; fault = klt . track ( track ) ; if ( fault != KltTrackFault . SUCCESS ) { continue ; } float error = UtilPoint2D_F32 . distanceSq ( track . x , track . y , xx , yy ) ; if ( error > maximumErrorFB ) { continue ; } // create a list of the observations AssociatedPair a = pairs . grow ( ) ; a . p1 . x = xx ; a . p1 . y = yy ; a . p2 . x = xc ; a . p2 . y = yc ; } } }
Tracks features from the previous image into the current image . Tracks are created inside the specified region in a grid pattern .
592
24
26,546
private void declarePyramid ( int imageWidth , int imageHeight ) { int minSize = ( config . trackerFeatureRadius * 2 + 1 ) * 5 ; int scales [ ] = TldTracker . selectPyramidScale ( imageWidth , imageHeight , minSize ) ; currentImage = FactoryPyramid . discreteGaussian ( scales , - 1 , 1 , false , ImageType . single ( imageType ) ) ; currentImage . initialize ( imageWidth , imageHeight ) ; previousImage = FactoryPyramid . discreteGaussian ( scales , - 1 , 1 , false , ImageType . single ( imageType ) ) ; previousImage . initialize ( imageWidth , imageHeight ) ; int numPyramidLayers = currentImage . getNumLayers ( ) ; previousDerivX = ( Derivative [ ] ) Array . newInstance ( derivType , numPyramidLayers ) ; previousDerivY = ( Derivative [ ] ) Array . newInstance ( derivType , numPyramidLayers ) ; currentDerivX = ( Derivative [ ] ) Array . newInstance ( derivType , numPyramidLayers ) ; currentDerivY = ( Derivative [ ] ) Array . newInstance ( derivType , numPyramidLayers ) ; for ( int i = 0 ; i < numPyramidLayers ; i ++ ) { int w = currentImage . getWidth ( i ) ; int h = currentImage . 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 ) ; } track = new PyramidKltFeature ( numPyramidLayers , config . trackerFeatureRadius ) ; }
Declares internal data structures
434
5
26,547
private void swapImages ( ) { ImagePyramid < Image > tempP ; tempP = currentImage ; currentImage = previousImage ; previousImage = tempP ; Derivative [ ] tempD ; tempD = previousDerivX ; previousDerivX = currentDerivX ; currentDerivX = tempD ; tempD = previousDerivY ; previousDerivY = currentDerivY ; currentDerivY = tempD ; }
Swaps the current and previous so that image derivative doesn t need to be recomputed or compied .
95
22
26,548
public void invalidateAll ( ) { int N = width * height ; for ( int i = 0 ; i < N ; i ++ ) data [ i ] . x = Float . NaN ; }
Marks all pixels as having an invalid flow
42
9
26,549
public boolean process ( EllipseRotated_F64 ellipse ) { // see if it's disabled if ( numContourPoints <= 0 ) { score = 0 ; return true ; } double cphi = Math . cos ( ellipse . phi ) ; double sphi = Math . sin ( ellipse . phi ) ; averageInside = 0 ; averageOutside = 0 ; int total = 0 ; for ( int contourIndex = 0 ; contourIndex < numContourPoints ; contourIndex ++ ) { double theta = contourIndex * Math . PI * 2.0 / numContourPoints ; // copied from UtilEllipse_F64.computePoint() reduced number of cos and sin double ct = Math . cos ( theta ) ; double st = Math . sin ( theta ) ; // location on ellipse in world frame double px = ellipse . center . x + ellipse . a * ct * cphi - ellipse . b * st * sphi ; double py = ellipse . center . y + ellipse . a * ct * sphi + ellipse . b * st * cphi ; // find direction of the tangent line // ellipse frame double edx = ellipse . a * ct * ellipse . b * ellipse . b ; double edy = ellipse . b * st * ellipse . a * ellipse . a ; double r = Math . sqrt ( edx * edx + edy * edy ) ; edx /= r ; edy /= r ; // rotate tangent into world frame double dx = edx * cphi - edy * sphi ; double dy = edx * sphi + edy * cphi ; // define the line integral double xin = px - dx * tangentDistance ; double yin = py - dy * tangentDistance ; double xout = px + dx * tangentDistance ; double yout = py + dy * tangentDistance ; if ( integral . isInside ( xin , yin ) && integral . isInside ( xout , yout ) ) { averageInside += integral . compute ( px , py , xin , yin ) ; averageOutside += integral . compute ( px , py , xout , yout ) ; total ++ ; } } score = 0 ; if ( total > 0 ) { score = Math . abs ( averageOutside - averageInside ) / ( total * tangentDistance ) ; } return score >= passThreshold ; }
Processes the edge along the ellipse and determines if the edge intensity is strong enough to pass or not
554
22
26,550
public void setImage ( GrayF32 image ) { scaleSpace . initialize ( image ) ; usedScales . clear ( ) ; do { for ( int i = 0 ; i < scaleSpace . getNumScales ( ) ; i ++ ) { GrayF32 scaleImage = scaleSpace . getImageScale ( i ) ; double sigma = scaleSpace . computeSigmaScale ( i ) ; double pixelCurrentToInput = scaleSpace . pixelScaleCurrentToInput ( ) ; ImageScale scale = allScales . get ( usedScales . size ( ) ) ; scale . derivX . reshape ( scaleImage . width , scaleImage . height ) ; scale . derivY . reshape ( scaleImage . width , scaleImage . height ) ; gradient . process ( scaleImage , scale . derivX , scale . derivY ) ; scale . imageToInput = pixelCurrentToInput ; scale . sigma = sigma ; usedScales . add ( scale ) ; } } while ( scaleSpace . computeNextOctave ( ) ) ; }
Sets the input image . Scale - space is computed and unrolled from this image
219
17
26,551
public ImageScale lookup ( double sigma ) { ImageScale best = null ; double bestValue = Double . MAX_VALUE ; for ( int i = 0 ; i < usedScales . size ( ) ; i ++ ) { ImageScale image = usedScales . get ( i ) ; double difference = Math . abs ( sigma - image . sigma ) ; if ( difference < bestValue ) { bestValue = difference ; best = image ; } } return best ; }
Looks up the image which is closest specified sigma
99
10
26,552
public void setModel ( BundleAdjustmentCamera model ) { this . model = model ; numIntrinsic = model . getIntrinsicCount ( ) ; if ( numIntrinsic > intrinsic . length ) { intrinsic = new double [ numIntrinsic ] ; } model . getIntrinsic ( intrinsic , 0 ) ; numericalPoint = createNumericalAlgorithm ( funcPoint ) ; numericalIntrinsic = createNumericalAlgorithm ( funcIntrinsic ) ; }
Specifies the camera model . The current state of its intrinsic parameters
109
13
26,553
@ Override public void associate ( FastQueue < D > src , FastQueue < D > dst ) { fitQuality . reset ( ) ; pairs . reset ( ) ; workBuffer . reset ( ) ; pairs . resize ( src . size ) ; fitQuality . resize ( src . size ) ; workBuffer . resize ( src . size * dst . size ) ; //CONCURRENT_BELOW BoofConcurrency.loopFor(0, src.size, i -> { for ( int i = 0 ; i < src . size ; i ++ ) { D a = src . data [ i ] ; double bestScore = maxFitError ; int bestIndex = - 1 ; int workIdx = i * dst . size ; for ( int j = 0 ; j < dst . size ; j ++ ) { D b = dst . data [ j ] ; double fit = score . score ( a , b ) ; workBuffer . set ( workIdx + j , fit ) ; if ( fit <= bestScore ) { bestIndex = j ; bestScore = fit ; } } pairs . set ( i , bestIndex ) ; fitQuality . set ( i , bestScore ) ; } //CONCURRENT_ABOVE }); if ( backwardsValidation ) { //CONCURRENT_BELOW BoofConcurrency.loopFor(0, src.size, i -> { for ( int i = 0 ; i < src . size ; i ++ ) { int match = pairs . data [ i ] ; if ( match == - 1 ) //CONCURRENT_BELOW return; continue ; double scoreToBeat = workBuffer . data [ i * dst . size + match ] ; for ( int j = 0 ; j < src . size ; j ++ , match += dst . size ) { if ( workBuffer . data [ match ] <= scoreToBeat && j != i ) { pairs . data [ i ] = - 1 ; fitQuality . data [ i ] = Double . MAX_VALUE ; break ; } } } //CONCURRENT_ABOVE }); } }
Associates the two sets objects against each other by minimizing fit score .
436
15
26,554
public boolean process ( T image , QrCode qr ) { this . qr = qr ; // this must be cleared before calling setMarker or else the distortion will be messed up qr . alignment . reset ( ) ; reader . setImage ( image ) ; reader . setMarker ( qr ) ; threshold = ( float ) qr . threshCorner ; initializePatterns ( qr ) ; // version 1 has no alignment patterns if ( qr . version <= 1 ) return true ; return localizePositionPatterns ( QrCode . VERSION_INFO [ qr . version ] . alignment ) ; }
Uses the previously detected position patterns to seed the search for the alignment patterns
133
15
26,555
void initializePatterns ( QrCode qr ) { int where [ ] = QrCode . VERSION_INFO [ qr . version ] . alignment ; qr . alignment . reset ( ) ; lookup . reset ( ) ; for ( int row = 0 ; row < where . length ; row ++ ) { for ( int col = 0 ; col < where . length ; col ++ ) { boolean skip = false ; if ( row == 0 && col == 0 ) skip = true ; else if ( row == 0 && col == where . length - 1 ) skip = true ; else if ( row == where . length - 1 && col == 0 ) skip = true ; if ( skip ) { lookup . add ( null ) ; } else { QrCode . Alignment a = qr . alignment . grow ( ) ; a . moduleX = where [ col ] ; a . moduleY = where [ row ] ; lookup . add ( a ) ; } } } }
Creates a list of alignment patterns to look for and their grid coordinates
203
14
26,556
boolean centerOnSquare ( QrCode . Alignment pattern , float guessY , float guessX ) { float step = 1 ; float bestMag = Float . MAX_VALUE ; float bestX = guessX ; float bestY = guessY ; for ( int i = 0 ; i < 10 ; i ++ ) { for ( int row = 0 ; row < 3 ; row ++ ) { float gridy = guessY - 1f + row ; for ( int col = 0 ; col < 3 ; col ++ ) { float gridx = guessX - 1f + col ; samples [ row * 3 + col ] = reader . read ( gridy , gridx ) ; } } float dx = ( samples [ 2 ] + samples [ 5 ] + samples [ 8 ] ) - ( samples [ 0 ] + samples [ 3 ] + samples [ 6 ] ) ; float dy = ( samples [ 6 ] + samples [ 7 ] + samples [ 8 ] ) - ( samples [ 0 ] + samples [ 1 ] + samples [ 2 ] ) ; float r = ( float ) Math . sqrt ( dx * dx + dy * dy ) ; if ( bestMag > r ) { // System.out.println("good step at "+i); bestMag = r ; bestX = guessX ; bestY = guessY ; } else { // System.out.println("bad step at "+i); step *= 0.75f ; } if ( r > 0 ) { guessX = bestX + step * dx / r ; guessY = bestY + step * dy / r ; } else { break ; } } pattern . moduleFound . x = bestX ; pattern . moduleFound . y = bestY ; reader . gridToImage ( ( float ) pattern . moduleFound . y , ( float ) pattern . moduleFound . x , pattern . pixel ) ; return true ; }
If the initial guess is within the inner white circle or black dot this will ensure that it is centered on the black dot
393
24
26,557
boolean localize ( QrCode . Alignment pattern , float guessY , float guessX ) { // sample along the middle. Try to not sample the outside edges which could confuse it for ( int i = 0 ; i < arrayY . length ; i ++ ) { float x = guessX - 1.5f + i * 3f / 12.0f ; float y = guessY - 1.5f + i * 3f / 12.0f ; arrayX [ i ] = reader . read ( guessY , x ) ; arrayY [ i ] = reader . read ( y , guessX ) ; } // TODO turn this into an exhaustive search of the array for best up and down point? int downX = greatestDown ( arrayX ) ; if ( downX == - 1 ) return false ; int upX = greatestUp ( arrayX , downX ) ; if ( upX == - 1 ) return false ; int downY = greatestDown ( arrayY ) ; if ( downY == - 1 ) return false ; int upY = greatestUp ( arrayY , downY ) ; if ( upY == - 1 ) return false ; pattern . moduleFound . x = guessX - 1.5f + ( downX + upX ) * 3f / 24.0f ; pattern . moduleFound . y = guessY - 1.5f + ( downY + upY ) * 3f / 24.0f ; reader . gridToImage ( ( float ) pattern . moduleFound . y , ( float ) pattern . moduleFound . x , pattern . pixel ) ; return true ; }
Localizizes the alignment pattern crudely by searching for the black box in the center by looking for its edges in the gray scale image
342
27
26,558
public static void positive ( TupleDesc_F64 input , TupleDesc_U8 output ) { double max = 0 ; for ( int i = 0 ; i < input . size ( ) ; i ++ ) { double v = input . value [ i ] ; if ( v > max ) max = v ; } if ( max == 0 ) max = 1.0 ; for ( int i = 0 ; i < input . size ( ) ; i ++ ) { output . value [ i ] = ( byte ) ( 255.0 * input . value [ i ] / max ) ; } }
Converts a floating point description with all positive values into the 8 - bit integer descriptor by dividing each element in the input by the element maximum value and multiplying by 255 .
125
34
26,559
public static void real ( TupleDesc_F64 input , TupleDesc_S8 output ) { double max = 0 ; for ( int i = 0 ; i < input . size ( ) ; i ++ ) { double v = Math . abs ( input . value [ i ] ) ; if ( v > max ) max = v ; } for ( int i = 0 ; i < input . size ( ) ; i ++ ) { output . value [ i ] = ( byte ) ( 127.0 * input . value [ i ] / max ) ; } }
Converts a floating point description with real values into the 8 - bit integer descriptor by dividing each element in the input by the element maximum absolute value and multiplying by 127 .
118
34
26,560
public static void convertNcc ( TupleDesc_F64 input , NccFeature output ) { if ( input . size ( ) != output . size ( ) ) throw new IllegalArgumentException ( "Feature lengths do not match." ) ; double mean = 0 ; for ( int i = 0 ; i < input . value . length ; i ++ ) { mean += input . value [ i ] ; } mean /= input . value . length ; double variance = 0 ; for ( int i = 0 ; i < input . value . length ; i ++ ) { double d = output . value [ i ] = input . value [ i ] - mean ; variance += d * d ; } variance /= output . size ( ) ; output . mean = mean ; output . sigma = Math . sqrt ( variance ) ; }
Converts a regular feature description into a NCC feature description
173
12
26,561
private static void convolve1D ( GrayU8 gray ) { ImageBorder < GrayU8 > border = FactoryImageBorder . wrap ( BorderType . EXTENDED , gray ) ; Kernel1D_S32 kernel = new Kernel1D_S32 ( 2 ) ; kernel . offset = 1 ; // specify the kernel's origin kernel . data [ 0 ] = 1 ; kernel . data [ 1 ] = - 1 ; GrayS16 output = new GrayS16 ( gray . width , gray . height ) ; GConvolveImageOps . horizontal ( kernel , gray , output , border ) ; panel . addImage ( VisualizeImageData . standard ( output , null ) , "1D Horizontal" ) ; GConvolveImageOps . vertical ( kernel , gray , output , border ) ; panel . addImage ( VisualizeImageData . standard ( output , null ) , "1D Vertical" ) ; }
Convolves a 1D kernel horizontally and vertically
193
10
26,562
private static void convolve2D ( GrayU8 gray ) { // By default 2D kernels will be centered around width/2 Kernel2D_S32 kernel = new Kernel2D_S32 ( 3 ) ; kernel . set ( 1 , 0 , 2 ) ; kernel . set ( 2 , 1 , 2 ) ; kernel . set ( 0 , 1 , - 2 ) ; kernel . set ( 1 , 2 , - 2 ) ; // Output needs to handle the increased domain after convolution. Can't be 8bit GrayS16 output = new GrayS16 ( gray . width , gray . height ) ; ImageBorder < GrayU8 > border = FactoryImageBorder . wrap ( BorderType . EXTENDED , gray ) ; GConvolveImageOps . convolve ( kernel , gray , output , border ) ; panel . addImage ( VisualizeImageData . standard ( output , null ) , "2D Kernel" ) ; }
Convolves a 2D kernel
196
7
26,563
private static void normalize2D ( GrayU8 gray ) { // Create a Gaussian kernel with radius of 3 Kernel2D_S32 kernel = FactoryKernelGaussian . gaussian2D ( GrayU8 . class , - 1 , 3 ) ; // Note that there is a more efficient way to compute this convolution since it is a separable kernel // just use BlurImageOps instead. // Since it's normalized it can be saved inside an 8bit image GrayU8 output = new GrayU8 ( gray . width , gray . height ) ; GConvolveImageOps . convolveNormalized ( kernel , gray , output ) ; panel . addImage ( VisualizeImageData . standard ( output , null ) , "2D Normalized Kernel" ) ; }
Convolves a 2D normalized kernel . This kernel is divided by its sum after computation .
164
19
26,564
public void process ( List < DMatrixRMaj > homographies ) { if ( assumeZeroSkew ) { if ( homographies . size ( ) < 2 ) throw new IllegalArgumentException ( "At least two homographies are required. Found " + homographies . size ( ) ) ; } else if ( homographies . size ( ) < 3 ) { throw new IllegalArgumentException ( "At least three homographies are required. Found " + homographies . size ( ) ) ; } if ( assumeZeroSkew ) { setupA_NoSkew ( homographies ) ; if ( ! solverNull . process ( A , 1 , b ) ) throw new RuntimeException ( "SVD failed" ) ; computeParam_ZeroSkew ( ) ; } else { setupA ( homographies ) ; if ( ! solverNull . process ( A , 1 , b ) ) throw new RuntimeException ( "SVD failed" ) ; computeParam ( ) ; } if ( MatrixFeatures_DDRM . hasUncountable ( K ) ) { throw new RuntimeException ( "Failed!" ) ; } }
Given a set of homographies computed from a sequence of images that observe the same plane it estimates the camera s calibration .
239
24
26,565
private void computeV ( DMatrixRMaj h1 , DMatrixRMaj h2 , DMatrixRMaj v ) { double h1x = h1 . get ( 0 , 0 ) ; double h1y = h1 . get ( 1 , 0 ) ; double h1z = h1 . get ( 2 , 0 ) ; double h2x = h2 . get ( 0 , 0 ) ; double h2y = h2 . get ( 1 , 0 ) ; double h2z = h2 . get ( 2 , 0 ) ; v . set ( 0 , 0 , h1x * h2x ) ; v . set ( 0 , 1 , h1x * h2y + h1y * h2x ) ; v . set ( 0 , 2 , h1y * h2y ) ; v . set ( 0 , 3 , h1z * h2x + h1x * h2z ) ; v . set ( 0 , 4 , h1z * h2y + h1y * h2z ) ; v . set ( 0 , 5 , h1z * h2z ) ; }
This computes the v_ij vector found in the paper .
246
13
26,566
private void computeParam ( ) { // reduce overflow/underflow CommonOps_DDRM . divide ( b , CommonOps_DDRM . elementMaxAbs ( b ) ) ; double B11 = b . get ( 0 , 0 ) ; double B12 = b . get ( 1 , 0 ) ; double B22 = b . get ( 2 , 0 ) ; double B13 = b . get ( 3 , 0 ) ; double B23 = b . get ( 4 , 0 ) ; double B33 = b . get ( 5 , 0 ) ; double temp0 = B12 * B13 - B11 * B23 ; double temp1 = B11 * B22 - B12 * B12 ; double v0 = temp0 / temp1 ; double lambda = B33 - ( B13 * B13 + v0 * temp0 ) / B11 ; // Using abs() inside is an adhoc modification to make it more stable // If there is any good theoretical reason for it, that's a pure accident. Seems // to work well in practice double a = Math . sqrt ( Math . abs ( lambda / B11 ) ) ; double b = Math . sqrt ( Math . abs ( lambda * B11 / temp1 ) ) ; double c = - B12 * b / B11 ; double u0 = c * v0 / a - B13 / B11 ; K . set ( 0 , 0 , a ) ; K . set ( 0 , 1 , c ) ; K . set ( 0 , 2 , u0 ) ; K . set ( 1 , 1 , b ) ; K . set ( 1 , 2 , v0 ) ; K . set ( 2 , 2 , 1 ) ; }
Compute the calibration parameters from the b matrix .
361
10
26,567
public static void hessianNaive ( GrayF32 integral , int skip , int size , GrayF32 intensity ) { final int w = intensity . width ; final int h = intensity . height ; // get convolution kernels for the second order derivatives IntegralKernel kerXX = DerivativeIntegralImage . kernelDerivXX ( size , null ) ; IntegralKernel kerYY = DerivativeIntegralImage . kernelDerivYY ( size , null ) ; IntegralKernel kerXY = DerivativeIntegralImage . kernelDerivXY ( size , null ) ; float norm = 1.0f / ( size * size ) ; for ( int y = 0 ; y < h ; y ++ ) { for ( int x = 0 ; x < w ; x ++ ) { int xx = x * skip ; int yy = y * skip ; computeHessian ( integral , intensity , kerXX , kerYY , kerXY , norm , y , yy , x , xx ) ; } } }
Brute force approach which is easy to validate through visual inspection .
216
13
26,568
@ Override public void openImageSet ( String ... files ) { synchronized ( lockProcessing ) { if ( processing ) { JOptionPane . showMessageDialog ( this , "Still processing" ) ; return ; } } // disable the menu until it finish processing the images setMenuBarEnabled ( false ) ; super . openImageSet ( files ) ; }
Prevent the user from tring to process more than one image at once
75
15
26,569
private BufferedImage scaleBuffered ( BufferedImage input ) { int m = Math . max ( input . getWidth ( ) , input . getHeight ( ) ) ; if ( m <= controls . maxImageSize ) return input ; else { double scale = controls . maxImageSize / ( double ) m ; int w = ( int ) ( scale * input . getWidth ( ) + 0.5 ) ; int h = ( int ) ( scale * input . getHeight ( ) + 0.5 ) ; // Use BoofCV to down sample since Graphics2D introduced too many aliasing artifacts BufferedImage output = new BufferedImage ( w , h , input . getType ( ) ) ; Planar < GrayU8 > a = new Planar <> ( GrayU8 . class , input . getWidth ( ) , input . getHeight ( ) , 3 ) ; Planar < GrayU8 > b = new Planar <> ( GrayU8 . class , w , h , 3 ) ; ConvertBufferedImage . convertFrom ( input , a , true ) ; AverageDownSampleOps . down ( a , b ) ; ConvertBufferedImage . convertTo ( b , output , true ) ; return output ; } }
Scale buffered image so that it meets the image size restrictions
260
12
26,570
private int [ ] selectBestPair ( SceneStructureMetric structure ) { Se3_F64 w_to_0 = structure . views [ 0 ] . worldToView ; Se3_F64 w_to_1 = structure . views [ 1 ] . worldToView ; Se3_F64 w_to_2 = structure . views [ 2 ] . worldToView ; Se3_F64 view0_to_1 = w_to_0 . invert ( null ) . concat ( w_to_1 , null ) ; Se3_F64 view0_to_2 = w_to_0 . invert ( null ) . concat ( w_to_2 , null ) ; Se3_F64 view1_to_2 = w_to_1 . invert ( null ) . concat ( w_to_2 , null ) ; Se3_F64 candidates [ ] = new Se3_F64 [ ] { view0_to_1 , view0_to_2 , view1_to_2 } ; int best = - 1 ; double bestScore = Double . MAX_VALUE ; for ( int i = 0 ; i < candidates . length ; i ++ ) { double s = score ( candidates [ i ] ) ; System . out . println ( "stereo score[" + i + "] = " + s ) ; if ( s < bestScore ) { bestScore = s ; best = i ; } } switch ( best ) { case 0 : return new int [ ] { 0 , 1 } ; case 1 : return new int [ ] { 0 , 2 } ; case 2 : return new int [ ] { 1 , 2 } ; } throw new RuntimeException ( "BUG!" ) ; }
Select two views which are the closest to an idea stereo pair . Little rotation and little translation along z - axis
375
22
26,571
private double score ( Se3_F64 se ) { // Rodrigues_F64 rod = new Rodrigues_F64(); // ConvertRotation3D_F64.matrixToRodrigues(se.R,rod); double x = Math . abs ( se . T . x ) ; double y = Math . abs ( se . T . y ) ; double z = Math . abs ( se . T . z ) + 1e-8 ; double r = Math . max ( x / ( y + z ) , y / ( x + z ) ) ; // System.out.println(se.T+" angle="+rod.theta); // return (Math.abs(rod.theta)+1e-3)/r; return 1.0 / r ; // ignoring rotation seems to work better <shrug> }
Give lower scores to transforms with no rotation and translations along x or y axis .
179
16
26,572
public void process ( List < Point2D_I32 > contour , GrowQueue_I32 vertexes , Polygon2D_F64 output ) { int numDecreasing = 0 ; for ( int i = vertexes . size - 1 , j = 0 ; j < vertexes . size ; i = j , j ++ ) { if ( vertexes . get ( i ) > vertexes . get ( j ) ) numDecreasing ++ ; } boolean decreasing = numDecreasing > 1 ; output . vertexes . resize ( vertexes . size ) ; lines . resize ( vertexes . size ) ; // fit lines to each size for ( int i = vertexes . size - 1 , j = 0 ; j < vertexes . size ; i = j , j ++ ) { int idx0 = vertexes . get ( i ) ; int idx1 = vertexes . get ( j ) ; if ( decreasing ) { int tmp = idx0 ; idx0 = idx1 ; idx1 = tmp ; } if ( idx0 > idx1 ) { // handle special case where it wraps around work . clear ( ) ; for ( int k = idx0 ; k < contour . size ( ) ; k ++ ) { work . add ( contour . get ( k ) ) ; } for ( int k = 0 ; k < idx1 ; k ++ ) { work . add ( contour . get ( k ) ) ; } FitLine_I32 . polar ( work , 0 , work . size ( ) , polar ) ; } else { FitLine_I32 . polar ( contour , idx0 , idx1 - idx0 , polar ) ; } UtilLine2D_F64 . convert ( polar , lines . get ( i ) ) ; } // find the corners by intersecting the side for ( int i = vertexes . size - 1 , j = 0 ; j < vertexes . size ; i = j , j ++ ) { LineGeneral2D_F64 lineA = lines . get ( i ) ; LineGeneral2D_F64 lineB = lines . get ( j ) ; Intersection2D_F64 . intersection ( lineA , lineB , output . get ( j ) ) ; } }
Refines the estimate using all the points in the contour
483
12
26,573
public boolean isDistorted ( ) { if ( radial != null && radial . length > 0 ) { for ( int i = 0 ; i < radial . length ; i ++ ) { if ( radial [ i ] != 0 ) return true ; } } return t1 != 0 || t2 != 0 ; }
If true then distortion parameters are specified .
64
8
26,574
public void process ( List < List < SquareNode > > clusters ) { valid . reset ( ) ; for ( int i = 0 ; i < clusters . size ( ) ; i ++ ) { List < SquareNode > graph = clusters . get ( i ) ; if ( graph . size ( ) < minimumElements ) continue ; switch ( checkNumberOfConnections ( graph ) ) { case 1 : orderIntoLine ( graph ) ; break ; case 2 : orderIntoGrid ( graph ) ; break ; // default: System.out.println("Failed number of connections. size = "+graph.size()); } } }
Converts the set of provided clusters into ordered grids .
131
11
26,575
int checkNumberOfConnections ( List < SquareNode > graph ) { int histogram [ ] = new int [ 5 ] ; for ( int i = 0 ; i < graph . size ( ) ; i ++ ) { histogram [ graph . get ( i ) . getNumberOfConnections ( ) ] ++ ; } if ( graph . size ( ) == 1 ) { if ( histogram [ 0 ] != 1 ) return 0 ; return 1 ; } else if ( histogram [ 1 ] == 2 ) { // line if ( histogram [ 0 ] != 0 ) return 0 ; if ( histogram [ 2 ] != graph . size ( ) - 2 ) return 0 ; if ( histogram [ 3 ] != 0 ) return 0 ; if ( histogram [ 4 ] != 0 ) return 0 ; return 1 ; } else { // grid if ( histogram [ 0 ] != 0 ) return 0 ; if ( histogram [ 1 ] != 0 ) return 0 ; if ( histogram [ 2 ] != 4 ) return 0 ; return 2 ; } }
Does a weak check on the number of edges in the graph . Since the structure isn t known it can t make harder checks
219
25
26,576
boolean addRowsToGrid ( List < SquareNode > column , List < SquareNode > ordered ) { for ( int i = 0 ; i < column . size ( ) ; i ++ ) { column . get ( i ) . graph = 0 ; } // now add the rows by traversing down the column int numFirsRow = 0 ; for ( int j = 0 ; j < column . size ( ) ; j ++ ) { SquareNode n = column . get ( j ) ; n . graph = SEARCHED ; ordered . add ( n ) ; SquareNode nextRow ; if ( j == 0 ) { if ( n . getNumberOfConnections ( ) != 2 ) { if ( verbose ) System . err . println ( "Unexpected number of connections. want 2 found " + n . getNumberOfConnections ( ) ) ; return true ; } nextRow = pickNot ( n , column . get ( j + 1 ) ) ; } else if ( j == column . size ( ) - 1 ) { if ( n . getNumberOfConnections ( ) != 2 ) { if ( verbose ) System . err . println ( "Unexpected number of connections. want 2 found " + n . getNumberOfConnections ( ) ) ; return true ; } nextRow = pickNot ( n , column . get ( j - 1 ) ) ; } else { if ( n . getNumberOfConnections ( ) != 3 ) { if ( verbose ) System . err . println ( "Unexpected number of connections. want 2 found " + n . getNumberOfConnections ( ) ) ; return true ; } nextRow = pickNot ( n , column . get ( j - 1 ) , column . get ( j + 1 ) ) ; } nextRow . graph = SEARCHED ; ordered . add ( nextRow ) ; int numberLine = addLineToGrid ( n , nextRow , ordered ) ; if ( j == 0 ) { numFirsRow = numberLine ; } else if ( numberLine != numFirsRow ) { if ( verbose ) System . err . println ( "Number of elements in rows do not match." ) ; return true ; } } return false ; }
Competes the graph by traversing down the first column and adding the rows one at a time
465
20
26,577
int addLineToGrid ( SquareNode a , SquareNode b , List < SquareNode > list ) { int total = 2 ; // double maxAngle = UtilAngle.radian(45); while ( true ) { // double slopeX0 = b.center.x - a.center.x; // double slopeY0 = b.center.y - a.center.y; // double angleAB = Math.atan2(slopeY0,slopeX0); // see which side the edge belongs to on b boolean matched = false ; int side ; for ( side = 0 ; side < 4 ; side ++ ) { if ( b . edges [ side ] != null && b . edges [ side ] . destination ( b ) == a ) { matched = true ; break ; } } if ( ! matched ) { throw new RuntimeException ( "BUG!" ) ; } // must be on the adjacent side side = ( side + 2 ) % 4 ; if ( b . edges [ side ] == null ) break ; SquareNode c = b . edges [ side ] . destination ( b ) ; if ( c . graph == SEARCHED ) break ; // double slopeX1 = c.center.x - b.center.x; // double slopeY1 = c.center.y - b.center.y; // // double angleBC = Math.atan2(slopeY1,slopeX1); // double acute = Math.abs(UtilAngle.minus(angleAB,angleBC)); // if( acute >= maxAngle ) // break; total ++ ; c . graph = SEARCHED ; list . add ( c ) ; a = b ; b = c ; } return total ; }
Add all the nodes into the list which lie along the line defined by a and b . a is assumed to be an end point . Care is taken to not cycle .
366
34
26,578
static SquareNode pickNot ( SquareNode target , SquareNode child ) { for ( int i = 0 ; i < 4 ; i ++ ) { SquareEdge e = target . edges [ i ] ; if ( e == null ) continue ; SquareNode c = e . destination ( target ) ; if ( c != child ) return c ; } throw new RuntimeException ( "There was no odd one out some how" ) ; }
There are only two edges on target . Pick the edge which does not go to the provided child
88
19
26,579
static SquareNode pickNot ( SquareNode target , SquareNode child0 , SquareNode child1 ) { for ( int i = 0 ; i < 4 ; i ++ ) { SquareEdge e = target . edges [ i ] ; if ( e == null ) continue ; SquareNode c = e . destination ( target ) ; if ( c != child0 && c != child1 ) return c ; } throw new RuntimeException ( "There was no odd one out some how" ) ; }
There are only three edges on target and two of them are known . Pick the one which isn t an inptu child
100
25
26,580
public static int countRegionPixels ( GrayS32 labeled , int which ) { int total = 0 ; for ( int y = 0 ; y < labeled . height ; y ++ ) { int index = labeled . startIndex + y * labeled . stride ; for ( int x = 0 ; x < labeled . width ; x ++ ) { if ( labeled . data [ index ++ ] == which ) { total ++ ; } } } return total ; }
Counts the number of instances of which inside the labeled image .
93
13
26,581
public static void countRegionPixels ( GrayS32 labeled , int totalRegions , int counts [ ] ) { Arrays . fill ( counts , 0 , totalRegions , 0 ) ; for ( int y = 0 ; y < labeled . height ; y ++ ) { int index = labeled . startIndex + y * labeled . stride ; for ( int x = 0 ; x < labeled . width ; x ++ ) { counts [ labeled . data [ index ++ ] ] ++ ; } } }
Counts the number of pixels in all regions . Regions must be have labels from 0 to totalRegions - 1 .
103
24
26,582
public static void regionPixelId_to_Compact ( GrayS32 graph , GrowQueue_I32 segmentId , GrayS32 output ) { InputSanityCheck . checkSameShape ( graph , output ) ; // Change the label of root nodes to be the new compacted labels for ( int i = 0 ; i < segmentId . size ; i ++ ) { graph . data [ segmentId . data [ i ] ] = i ; } // In the second pass assign all the children to the new compacted labels for ( int y = 0 ; y < output . height ; y ++ ) { int indexGraph = graph . startIndex + y * graph . stride ; int indexOut = output . startIndex + y * output . stride ; for ( int x = 0 ; x < output . width ; x ++ , indexGraph ++ , indexOut ++ ) { output . data [ indexOut ] = graph . data [ graph . data [ indexGraph ] ] ; } } // need to do some clean up since the above approach doesn't work for the roots for ( int i = 0 ; i < segmentId . size ; i ++ ) { int indexGraph = segmentId . data [ i ] - graph . startIndex ; int x = indexGraph % graph . stride ; int y = indexGraph / graph . stride ; output . data [ output . startIndex + y * output . stride + x ] = i ; } }
Compacts the region labels such that they are consecutive numbers starting from 0 . The ID of a root node must the index of a pixel in the graph image taking in account the change in coordinates for sub - images .
297
43
26,583
public static < II extends ImageGray < II > > OrientationIntegral < II > image_ii ( double objectRadiusToScale , int sampleRadius , double samplePeriod , int sampleWidth , double weightSigma , Class < II > integralImage ) { return ( OrientationIntegral < II > ) new ImplOrientationImageAverageIntegral ( objectRadiusToScale , sampleRadius , samplePeriod , sampleWidth , weightSigma , integralImage ) ; }
Estimates the orientation without calculating the image derivative .
102
10
26,584
public static < II extends ImageGray < II > > OrientationIntegral < II > sliding_ii ( ConfigSlidingIntegral config , Class < II > integralType ) { if ( config == null ) config = new ConfigSlidingIntegral ( ) ; config . checkValidity ( ) ; return ( OrientationIntegral < II > ) new ImplOrientationSlidingWindowIntegral ( config . objectRadiusToScale , config . samplePeriod , config . windowSize , config . radius , config . weightSigma , config . sampleWidth , integralType ) ; }
Estimates the orientation of a region by using a sliding window across the different potential angles .
122
18
26,585
public static < D extends ImageGray < D > > OrientationHistogramSift < D > sift ( ConfigSiftOrientation config , Class < D > derivType ) { if ( config == null ) config = new ConfigSiftOrientation ( ) ; config . checkValidity ( ) ; return new OrientationHistogramSift ( config . histogramSize , config . sigmaEnlarge , derivType ) ; }
Estimates multiple orientations as specified in SIFT paper .
91
12
26,586
public void setTemplate ( T template , T mask , int maxMatches ) { this . template = template ; this . mask = mask ; this . maxMatches = maxMatches ; }
Specifies the template to search for and the maximum number of matches to return .
40
16
26,587
public void setImage ( T image ) { match . setInputImage ( image ) ; this . imageWidth = image . width ; this . imageHeight = image . height ; }
Specifies the input image which the template is to be found inside .
37
14
26,588
public void process ( ) { // compute match intensities if ( mask == null ) match . process ( template ) ; else match . process ( template , mask ) ; GrayF32 intensity = match . getIntensity ( ) ; int offsetX = 0 ; int offsetY = 0 ; // adjust intensity image size depending on if there is a border or not if ( ! match . isBorderProcessed ( ) ) { int x0 = match . getBorderX0 ( ) ; int x1 = imageWidth - ( template . width - x0 ) ; int y0 = match . getBorderY0 ( ) ; int y1 = imageHeight - ( template . height - y0 ) ; intensity = intensity . subimage ( x0 , y0 , x1 , y1 , null ) ; } else { offsetX = match . getBorderX0 ( ) ; offsetY = match . getBorderY0 ( ) ; } // find local peaks in intensity image candidates . reset ( ) ; extractor . process ( intensity , null , null , null , candidates ) ; // select the best matches if ( scores . length < candidates . size ) { scores = new float [ candidates . size ] ; indexes = new int [ candidates . size ] ; } for ( int i = 0 ; i < candidates . size ; i ++ ) { Point2D_I16 p = candidates . get ( i ) ; scores [ i ] = - intensity . get ( p . x , p . y ) ; } int N = Math . min ( maxMatches , candidates . size ) ; QuickSelect . selectIndex ( scores , N , candidates . size , indexes ) ; // save the results results . reset ( ) ; for ( int i = 0 ; i < N ; i ++ ) { Point2D_I16 p = candidates . get ( indexes [ i ] ) ; Match m = results . grow ( ) ; m . score = - scores [ indexes [ i ] ] ; m . set ( p . x - offsetX , p . y - offsetY ) ; } }
Performs template matching .
431
5
26,589
public void refreshAlgorithm ( ) { Object cookie = algCookies . get ( algBox . getSelectedIndex ( ) ) ; String name = ( String ) algBox . getSelectedItem ( ) ; performSetAlgorithm ( name , cookie ) ; }
Tells it to switch again to the current algorithm . Useful if the input has changed and information needs to be rendered again .
58
25
26,590
public boolean process ( List < Point2D_I32 > contour ) { // Reset internal book keeping variables reset ( ) ; if ( loops ) { // Reject pathological case if ( contour . size ( ) < 3 ) return false ; if ( ! findInitialTriangle ( contour ) ) return false ; } else { // Reject pathological case if ( contour . size ( ) < 2 ) return false ; // two end points are the seeds. Plus they can't change addCorner ( 0 ) ; addCorner ( contour . size ( ) - 1 ) ; initializeScore ( contour , false ) ; } savePolyline ( ) ; sequentialSideFit ( contour , loops ) ; if ( fatalError ) return false ; int MIN_SIZE = loops ? 3 : 2 ; double bestScore = Double . MAX_VALUE ; int bestSize = - 1 ; for ( int i = 0 ; i < Math . min ( maxSides - ( MIN_SIZE - 1 ) , polylines . size ) ; i ++ ) { if ( polylines . get ( i ) . score < bestScore ) { bestPolyline = polylines . get ( i ) ; bestScore = bestPolyline . score ; bestSize = i + MIN_SIZE ; } } // There was no good match within the min/max size requirement if ( bestSize < minSides ) { return false ; } // make sure all the sides are within error tolerance for ( int i = 0 , j = bestSize - 1 ; i < bestSize ; j = i , i ++ ) { Point2D_I32 a = contour . get ( bestPolyline . splits . get ( i ) ) ; Point2D_I32 b = contour . get ( bestPolyline . splits . get ( j ) ) ; double length = a . distance ( b ) ; double thresholdSideError = this . maxSideError . compute ( length ) ; if ( bestPolyline . sideErrors . get ( i ) >= thresholdSideError * thresholdSideError ) { bestPolyline = null ; return false ; } } return true ; }
Process the contour and returns true if a polyline could be found .
446
15
26,591
boolean savePolyline ( ) { int N = loops ? 3 : 2 ; // if a polyline of this size has already been saved then over write it CandidatePolyline c ; if ( list . size ( ) <= polylines . size + N - 1 ) { c = polylines . get ( list . size ( ) - N ) ; // sanity check if ( c . splits . size != list . size ( ) ) throw new RuntimeException ( "Egads saved polylines aren't in the expected order" ) ; } else { c = polylines . grow ( ) ; c . reset ( ) ; c . score = Double . MAX_VALUE ; } double foundScore = computeScore ( list , cornerScorePenalty , loops ) ; // only save the results if it's an improvement if ( c . score > foundScore ) { c . score = foundScore ; c . splits . reset ( ) ; c . sideErrors . reset ( ) ; Element < Corner > e = list . getHead ( ) ; double maxSideError = 0 ; while ( e != null ) { maxSideError = Math . max ( maxSideError , e . object . sideError ) ; c . splits . add ( e . object . index ) ; c . sideErrors . add ( e . object . sideError ) ; e = e . next ; } c . maxSideError = maxSideError ; return true ; } else { return false ; } }
Saves the current polyline
305
6
26,592
static double computeScore ( LinkedList < Corner > list , double cornerPenalty , boolean loops ) { double sumSides = 0 ; Element < Corner > e = list . getHead ( ) ; Element < Corner > end = loops ? null : list . getTail ( ) ; while ( e != end ) { sumSides += e . object . sideError ; e = e . next ; } int numSides = loops ? list . size ( ) : list . size ( ) - 1 ; return sumSides / numSides + cornerPenalty * numSides ; }
Computes the score for a list
124
7
26,593
boolean findInitialTriangle ( List < Point2D_I32 > contour ) { // find the first estimate for a corner int cornerSeed = findCornerSeed ( contour ) ; // see if it can reject the contour immediately if ( convex ) { if ( ! isConvexUsingMaxDistantPoints ( contour , 0 , cornerSeed ) ) return false ; } // Select the second corner. splitter . selectSplitPoint ( contour , 0 , cornerSeed , resultsA ) ; splitter . selectSplitPoint ( contour , cornerSeed , 0 , resultsB ) ; if ( splitter . compareScore ( resultsA . score , resultsB . score ) >= 0 ) { addCorner ( resultsA . index ) ; addCorner ( cornerSeed ) ; } else { addCorner ( cornerSeed ) ; addCorner ( resultsB . index ) ; } // Select the third corner. Initial triangle will be complete now // the third corner will be the one which maximizes the distance from the first two int index0 = list . getHead ( ) . object . index ; int index1 = list . getHead ( ) . next . object . index ; int index2 = maximumDistance ( contour , index0 , index1 ) ; addCorner ( index2 ) ; // enforce CCW requirement ensureTriangleOrder ( contour ) ; return initializeScore ( contour , true ) ; }
Select an initial triangle . A good initial triangle is needed . By good it should minimize the error of the contour from each side
307
26
26,594
private boolean initializeScore ( List < Point2D_I32 > contour , boolean loops ) { // Score each side Element < Corner > e = list . getHead ( ) ; Element < Corner > end = loops ? null : list . getTail ( ) ; while ( e != end ) { if ( convex && ! isSideConvex ( contour , e ) ) return false ; Element < Corner > n = e . next ; double error ; if ( n == null ) { error = computeSideError ( contour , e . object . index , list . getHead ( ) . object . index ) ; } else { error = computeSideError ( contour , e . object . index , n . object . index ) ; } e . object . sideError = error ; e = n ; } // Compute what would happen if a side was split e = list . getHead ( ) ; while ( e != end ) { computePotentialSplitScore ( contour , e , list . size ( ) < minSides ) ; e = e . next ; } return true ; }
Computes the score and potential split for each side
231
10
26,595
void ensureTriangleOrder ( List < Point2D_I32 > contour ) { Element < Corner > e = list . getHead ( ) ; Corner a = e . object ; e = e . next ; Corner b = e . object ; e = e . next ; Corner c = e . object ; int distB = CircularIndex . distanceP ( a . index , b . index , contour . size ( ) ) ; int distC = CircularIndex . distanceP ( a . index , c . index , contour . size ( ) ) ; if ( distB > distC ) { list . reset ( ) ; list . pushTail ( a ) ; list . pushTail ( c ) ; list . pushTail ( b ) ; } }
Make sure the next corner after the head is the closest one to the head
163
15
26,596
boolean increaseNumberOfSidesByOne ( List < Point2D_I32 > contour , boolean loops ) { // System.out.println("increase number of sides by one. list = "+list.size()); Element < Corner > selected = selectCornerToSplit ( loops ) ; // No side can be split if ( selected == null ) return false ; // Update the corner who's side was just split selected . object . sideError = selected . object . splitError0 ; // split the selected side and add a new corner Corner c = corners . grow ( ) ; c . reset ( ) ; c . index = selected . object . splitLocation ; c . sideError = selected . object . splitError1 ; Element < Corner > cornerE = list . insertAfter ( selected , c ) ; // see if the new side could be convex if ( convex && ! isSideConvex ( contour , selected ) ) return false ; else { // compute the score for sides which just changed computePotentialSplitScore ( contour , cornerE , list . size ( ) < minSides ) ; computePotentialSplitScore ( contour , selected , list . size ( ) < minSides ) ; // Save the results // printCurrent(contour); savePolyline ( ) ; return true ; } }
Increase the number of sides in the polyline . This is done greedily selecting the side which would improve the score by the most of it was split .
278
31
26,597
boolean isSideConvex ( List < Point2D_I32 > contour , Element < Corner > e1 ) { // a conservative estimate for concavity. Assumes a triangle and that the farthest // point is equal to the distance between the two corners Element < Corner > e2 = next ( e1 ) ; int length = CircularIndex . distanceP ( e1 . object . index , e2 . object . index , contour . size ( ) ) ; Point2D_I32 p0 = contour . get ( e1 . object . index ) ; Point2D_I32 p1 = contour . get ( e2 . object . index ) ; double d = p0 . distance ( p1 ) ; if ( length >= d * convexTest ) { return false ; } return true ; }
Checks to see if the side could belong to a convex shape
177
14
26,598
Element < Corner > selectCornerToSplit ( boolean loops ) { Element < Corner > selected = null ; double bestChange = convex ? 0 : - Double . MAX_VALUE ; // Pick the side that if split would improve the overall score the most Element < Corner > e = list . getHead ( ) ; Element < Corner > end = loops ? null : list . getTail ( ) ; while ( e != end ) { Corner c = e . object ; if ( ! c . splitable ) { e = e . next ; continue ; } // compute how much better the score will improve because of the split double change = c . sideError * 2 - c . splitError0 - c . splitError1 ; // it was found that selecting for the biggest change tends to produce better results if ( change < 0 ) { change = - change ; } if ( change > bestChange ) { bestChange = change ; selected = e ; } e = e . next ; } return selected ; }
Selects the best side to split the polyline at .
207
12
26,599
Element < Corner > selectCornerToRemove ( List < Point2D_I32 > contour , ErrorValue sideError , boolean loops ) { if ( list . size ( ) <= 3 ) return null ; // Pick the side that if split would improve the overall score the most Element < Corner > target , end ; // if it loops any corner can be split. If it doesn't look the end points can't be removed if ( loops ) { target = list . getHead ( ) ; end = null ; } else { target = list . getHead ( ) . next ; end = list . getTail ( ) ; } Element < Corner > best = null ; double bestScore = - Double . MAX_VALUE ; while ( target != end ) { Element < Corner > p = previous ( target ) ; Element < Corner > n = next ( target ) ; // just contributions of the corners in question double before = ( p . object . sideError + target . object . sideError ) / 2.0 + cornerScorePenalty ; double after = computeSideError ( contour , p . object . index , n . object . index ) ; if ( before - after > bestScore ) { bestScore = before - after ; best = target ; sideError . value = after ; } target = target . next ; } return best ; }
Selects the best corner to remove . If no corner was found that can be removed then null is returned
278
21