idx int64 0 165k | question stringlengths 73 4.15k | target stringlengths 5 918 | len_question int64 21 890 | len_target int64 3 255 |
|---|---|---|---|---|
27,700 | public Point2D_F64 transform ( Point3D_F64 worldPt ) { Point2D_F64 out = new Point2D_F64 ( ) ; if ( transform ( worldPt , out ) ) return out ; else return null ; } | Computes location of 3D point in world as observed in the camera . Point is returned if visible or null if not visible . | 57 | 26 |
27,701 | protected void splitPixels ( int indexStart , int length ) { // too short to split if ( length < minimumSideLengthPixel ) return ; // end points of the line int indexEnd = ( indexStart + length ) % N ; int splitOffset = selectSplitOffset ( indexStart , length ) ; if ( splitOffset >= 0 ) { // System.out.println(" splitting "); splitPixels ( indexStart , splitOffset ) ; int indexSplit = ( indexStart + splitOffset ) % N ; splits . add ( indexSplit ) ; splitPixels ( indexSplit , circularDistance ( indexSplit , indexEnd ) ) ; } } | Recursively splits pixels between indexStart to indexStart + length . A split happens if there is a pixel more than the desired distance away from the two end points . Results are placed into splits | 134 | 39 |
27,702 | protected boolean mergeSegments ( ) { // See if merging will cause a degenerate case if ( splits . size ( ) <= 3 ) return false ; boolean change = false ; work . reset ( ) ; for ( int i = 0 ; i < splits . size ; i ++ ) { int start = splits . data [ i ] ; int end = splits . data [ ( i + 2 ) % splits . size ] ; if ( selectSplitOffset ( start , circularDistance ( start , end ) ) < 0 ) { // merge the two lines by not adding it change = true ; } else { work . add ( splits . data [ ( i + 1 ) % splits . size ] ) ; } } // swap the two lists GrowQueue_I32 tmp = work ; work = splits ; splits = tmp ; return change ; } | Merges lines together if the common corner is close to a common line | 171 | 14 |
27,703 | protected boolean splitSegments ( ) { boolean change = false ; work . reset ( ) ; for ( int i = 0 ; i < splits . size - 1 ; i ++ ) { change |= checkSplit ( change , i , i + 1 ) ; } change |= checkSplit ( change , splits . size - 1 , 0 ) ; // swap the two lists GrowQueue_I32 tmp = work ; work = splits ; splits = tmp ; return change ; } | Splits a line in two if there is a point that is too far away | 97 | 16 |
27,704 | protected int circularDistance ( int start , int end ) { if ( end >= start ) return end - start ; else return N - start + end ; } | Distance the two points are apart in clockwise direction | 32 | 10 |
27,705 | public static void horizontal ( GrayF32 src , GrayF32 dst ) { if ( src . width < dst . width ) throw new IllegalArgumentException ( "src width must be >= dst width" ) ; if ( src . height != dst . height ) throw new IllegalArgumentException ( "src height must equal dst height" ) ; float scale = src . width / ( float ) dst . width ; //CONCURRENT_BELOW BoofConcurrency.loopFor(0, dst.height, y -> { for ( int y = 0 ; y < dst . height ; y ++ ) { int indexDst = dst . startIndex + y * dst . stride ; for ( int x = 0 ; x < dst . width - 1 ; x ++ , indexDst ++ ) { float srcX0 = x * scale ; float srcX1 = ( x + 1 ) * scale ; int isrcX0 = ( int ) srcX0 ; int isrcX1 = ( int ) srcX1 ; int index = src . getIndex ( isrcX0 , y ) ; // compute value of overlapped region float startWeight = ( 1.0f - ( srcX0 - isrcX0 ) ) ; float start = src . data [ index ++ ] ; float middle = 0 ; for ( int i = isrcX0 + 1 ; i < isrcX1 ; i ++ ) { middle += src . data [ index ++ ] ; } float endWeight = ( srcX1 % 1 ) ; float end = src . data [ index ] ; dst . data [ indexDst ] = ( start * startWeight + middle + end * endWeight ) / scale ; } // handle the last area as a special case int x = dst . width - 1 ; float srcX0 = x * scale ; int isrcX0 = ( int ) srcX0 ; int isrcX1 = src . width - 1 ; int index = src . getIndex ( isrcX0 , y ) ; // compute value of overlapped region float startWeight = ( 1.0f - ( srcX0 - isrcX0 ) ) ; float start = src . data [ index ++ ] ; float middle = 0 ; for ( int i = isrcX0 + 1 ; i < isrcX1 ; i ++ ) { middle += src . data [ index ++ ] ; } float end = isrcX1 != isrcX0 ? src . data [ index ] : 0 ; dst . data [ indexDst ] = ( start * startWeight + middle + end ) / scale ; } //CONCURRENT_ABOVE }); } | Down samples the image along the x - axis only . Image height s must be the same . | 560 | 19 |
27,706 | public static void vertical ( GrayF32 src , GrayF32 dst ) { if ( src . height < dst . height ) throw new IllegalArgumentException ( "src height must be >= dst height" ) ; if ( src . width != dst . width ) throw new IllegalArgumentException ( "src width must equal dst width" ) ; float scale = src . height / ( float ) dst . height ; //CONCURRENT_BELOW BoofConcurrency.loopFor(0, dst.width, x -> { for ( int x = 0 ; x < dst . width ; x ++ ) { int indexDst = dst . startIndex + x ; for ( int y = 0 ; y < dst . height - 1 ; y ++ ) { float srcY0 = y * scale ; float srcY1 = ( y + 1 ) * scale ; int isrcY0 = ( int ) srcY0 ; int isrcY1 = ( int ) srcY1 ; int index = src . getIndex ( x , isrcY0 ) ; // compute value of overlapped region float startWeight = ( 1.0f - ( srcY0 - isrcY0 ) ) ; float start = src . data [ index ] ; index += src . stride ; float middle = 0 ; for ( int i = isrcY0 + 1 ; i < isrcY1 ; i ++ ) { middle += src . data [ index ] ; index += src . stride ; } float endWeight = ( srcY1 % 1 ) ; float end = src . data [ index ] ; dst . data [ indexDst ] = ( float ) ( ( start * startWeight + middle + end * endWeight ) / scale ) ; indexDst += dst . stride ; } // handle the last area as a special case int y = dst . height - 1 ; float srcY0 = y * scale ; int isrcY0 = ( int ) srcY0 ; int isrcY1 = src . height - 1 ; int index = src . getIndex ( x , isrcY0 ) ; // compute value of overlapped region float startWeight = ( 1.0f - ( srcY0 - isrcY0 ) ) ; float start = src . data [ index ] ; index += src . stride ; float middle = 0 ; for ( int i = isrcY0 + 1 ; i < isrcY1 ; i ++ ) { middle += src . data [ index ] ; index += src . stride ; } float end = isrcY1 != isrcY0 ? src . data [ index ] : 0 ; dst . data [ indexDst ] = ( float ) ( ( start * startWeight + middle + end ) / scale ) ; } //CONCURRENT_ABOVE }); } | Down samples the image along the y - axis only . Image width s must be the same . | 589 | 19 |
27,707 | protected void drawFeatures ( float scale , int offsetX , int offsetY , FastQueue < Point2D_F64 > all , FastQueue < Point2D_F64 > inliers , Homography2D_F64 currToGlobal , Graphics2D g2 ) { Point2D_F64 distPt = new Point2D_F64 ( ) ; for ( int i = 0 ; i < all . size ; i ++ ) { HomographyPointOps_F64 . transform ( currToGlobal , all . get ( i ) , distPt ) ; distPt . x = offsetX + distPt . x * scale ; distPt . y = offsetY + distPt . y * scale ; VisualizeFeatures . drawPoint ( g2 , ( int ) distPt . x , ( int ) distPt . y , Color . RED ) ; } for ( int i = 0 ; i < inliers . size ; i ++ ) { HomographyPointOps_F64 . transform ( currToGlobal , inliers . get ( i ) , distPt ) ; distPt . x = offsetX + distPt . x * scale ; distPt . y = offsetY + distPt . y * scale ; VisualizeFeatures . drawPoint ( g2 , ( int ) distPt . x , ( int ) distPt . y , Color . BLUE ) ; } } | Draw features after applying a homography transformation . | 311 | 9 |
27,708 | public void update ( ImageGray image ) { if ( approximateHistogram ) { for ( int i = 0 ; i < bins . length ; i ++ ) bins [ i ] = 0 ; if ( image instanceof GrayF32 ) update ( ( GrayF32 ) image ) ; else if ( GrayI . class . isAssignableFrom ( image . getClass ( ) ) ) update ( ( GrayI ) image ) ; else throw new IllegalArgumentException ( "Image type not yet supported" ) ; } else { GImageStatistics . histogram ( image , 0 , bins ) ; } } | Update s the histogram . Must only be called in UI thread | 125 | 13 |
27,709 | public void addImage ( BufferedImage image , String name ) { addImage ( image , name , ScaleOptions . DOWN ) ; } | Displays a new image in the list . | 28 | 9 |
27,710 | public synchronized void addItem ( final JComponent panel , final String name ) { Dimension panelD = panel . getPreferredSize ( ) ; final boolean sizeChanged = bodyWidth != panelD . width || bodyHeight != panelD . height ; // make the preferred size large enough to hold all the images bodyWidth = ( int ) Math . max ( bodyWidth , panelD . getWidth ( ) ) ; bodyHeight = ( int ) Math . max ( bodyHeight , panelD . getHeight ( ) ) ; panels . add ( panel ) ; SwingUtilities . invokeLater ( new Runnable ( ) { public void run ( ) { listModel . addElement ( name ) ; if ( listModel . size ( ) == 1 ) { listPanel . setSelectedIndex ( 0 ) ; } // update the list's size Dimension d = listPanel . getMinimumSize ( ) ; listPanel . setPreferredSize ( new Dimension ( d . width + scroll . getVerticalScrollBar ( ) . getWidth ( ) , d . height ) ) ; // make sure it's preferred size is up to date if ( sizeChanged ) { Component old = ( ( BorderLayout ) bodyPanel . getLayout ( ) ) . getLayoutComponent ( BorderLayout . CENTER ) ; if ( old != null ) { old . setPreferredSize ( new Dimension ( bodyWidth , bodyHeight ) ) ; } } validate ( ) ; } } ) ; } | Displays a new JPanel in the list . | 301 | 10 |
27,711 | public static RectangleLength2D_F64 centerBoxInside ( int srcWidth , int srcHeight , PixelTransform < Point2D_F64 > transform , Point2D_F64 work ) { List < Point2D_F64 > points = computeBoundingPoints ( srcWidth , srcHeight , transform , work ) ; Point2D_F64 center = new Point2D_F64 ( ) ; UtilPoint2D_F64 . mean ( points , center ) ; double x0 , x1 , y0 , y1 ; double bx0 , bx1 , by0 , by1 ; x0 = x1 = y0 = y1 = 0 ; bx0 = bx1 = by0 = by1 = Double . MAX_VALUE ; for ( int i = 0 ; i < points . size ( ) ; i ++ ) { Point2D_F64 p = points . get ( i ) ; double dx = p . x - center . x ; double dy = p . y - center . y ; double adx = Math . abs ( dx ) ; double ady = Math . abs ( dy ) ; if ( adx < ady ) { if ( dy < 0 ) { if ( adx < by0 ) { by0 = adx ; y0 = dy ; } } else { if ( adx < by1 ) { by1 = adx ; y1 = dy ; } } } else { if ( dx < 0 ) { if ( ady < bx0 ) { bx0 = ady ; x0 = dx ; } } else { if ( ady < bx1 ) { bx1 = ady ; x1 = dx ; } } } } return new RectangleLength2D_F64 ( x0 + center . x , y0 + center . y , x1 - x0 , y1 - y0 ) ; } | Attempts to center the box inside . It will be approximately fitted too . | 407 | 14 |
27,712 | public static void roundInside ( RectangleLength2D_F64 bound ) { double x0 = Math . ceil ( bound . x0 ) ; double y0 = Math . ceil ( bound . y0 ) ; double x1 = Math . floor ( bound . x0 + bound . width ) ; double y1 = Math . floor ( bound . y0 + bound . height ) ; bound . x0 = x0 ; bound . y0 = y0 ; bound . width = x1 - x0 ; bound . height = y1 - y0 ; } | Adjust bound to ensure the entire image is contained inside otherwise there might be single pixel wide black regions | 120 | 19 |
27,713 | public boolean isInBounds ( int c_x , int c_y ) { return BoofMiscOps . checkInside ( image , c_x , c_y , radiusWidth , radiusHeight ) ; } | The entire region must be inside the image because any outside pixels will change the statistics | 46 | 16 |
27,714 | private GrowQueue_I32 findCommonTracks ( SeedInfo target ) { // if true then it is visible in all tracks boolean visibleAll [ ] = new boolean [ target . seed . totalFeatures ] ; Arrays . fill ( visibleAll , true ) ; // used to keep track of which features are visible in the current motion boolean visibleMotion [ ] = new boolean [ target . seed . totalFeatures ] ; // Only look at features in the motions that were used to compute the score for ( int idxMotion = 0 ; idxMotion < target . motions . size ; idxMotion ++ ) { PairwiseImageGraph2 . Motion m = target . seed . connections . get ( target . motions . get ( idxMotion ) ) ; boolean seedIsSrc = m . src == target . seed ; Arrays . fill ( visibleMotion , false ) ; for ( int i = 0 ; i < m . inliers . size ; i ++ ) { AssociatedIndex a = m . inliers . get ( i ) ; visibleMotion [ seedIsSrc ? a . src : a . dst ] = true ; } for ( int i = 0 ; i < target . seed . totalFeatures ; i ++ ) { visibleAll [ i ] &= visibleMotion [ i ] ; } } GrowQueue_I32 common = new GrowQueue_I32 ( target . seed . totalFeatures / 10 + 1 ) ; for ( int i = 0 ; i < target . seed . totalFeatures ; i ++ ) { if ( visibleAll [ i ] ) { common . add ( i ) ; } } return common ; } | Finds the indexes of tracks which are common to all views | 338 | 12 |
27,715 | private SeedInfo score ( View target ) { SeedInfo output = new SeedInfo ( ) ; output . seed = target ; scoresMotions . reset ( ) ; // score all edges for ( int i = 0 ; i < target . connections . size ; i ++ ) { PairwiseImageGraph2 . Motion m = target . connections . get ( i ) ; if ( ! m . is3D ) continue ; scoresMotions . grow ( ) . set ( score ( m ) , i ) ; } // only score the 3 best. This is to avoid biasing it for Collections . sort ( scoresMotions . toList ( ) ) ; for ( int i = Math . min ( 2 , scoresMotions . size ) ; i >= 0 ; i -- ) { output . motions . add ( scoresMotions . get ( i ) . index ) ; output . score += scoresMotions . get ( i ) . score ; } return output ; } | Score a view for how well it could be a seed based on the the 3 best 3D motions associated with it | 197 | 23 |
27,716 | public static double score ( PairwiseImageGraph2 . Motion m ) { // countF and countF will be <= totalFeatures // Prefer a scene more features from a fundamental matrix than a homography. // This can be sign that the scene has a rich 3D structure and is poorly represented by // a plane or rotational motion double score = Math . min ( 5 , m . countF / ( double ) ( m . countH + 1 ) ) ; // Also prefer more features from the original image to be matched score *= m . countF ; return score ; } | Scores the motion for its ability to capture 3D structure | 119 | 12 |
27,717 | public void process ( D derivX , D derivY , GrayU8 binaryEdges ) { InputSanityCheck . checkSameShape ( derivX , derivY , binaryEdges ) ; int w = derivX . width - regionSize + 1 ; int h = derivY . height - regionSize + 1 ; foundLines . reshape ( derivX . width / regionSize , derivX . height / regionSize ) ; foundLines . reset ( ) ; // avoid partial regions/other image edge conditions by being at least the region's radius away for ( int y = 0 ; y < h ; y += regionSize ) { int gridY = y / regionSize ; // index of the top left pixel in the region being considered // possible over optimization int index = binaryEdges . startIndex + y * binaryEdges . stride ; for ( int x = 0 ; x < w ; x += regionSize , index += regionSize ) { int gridX = x / regionSize ; // detects edgels inside the region detectEdgels ( index , x , y , derivX , derivY , binaryEdges ) ; // find lines inside the region using RANSAC findLinesInRegion ( foundLines . get ( gridX , gridY ) ) ; } } } | Detects line segments through the image inside of grids . | 270 | 11 |
27,718 | private void findLinesInRegion ( List < LineSegment2D_F32 > gridLines ) { List < Edgel > list = edgels . copyIntoList ( null ) ; int iterations = 0 ; // exit if not enough points or max iterations exceeded while ( iterations ++ < maxDetectLines ) { if ( ! robustMatcher . process ( list ) ) break ; // remove the found edges from the main list List < Edgel > matchSet = robustMatcher . getMatchSet ( ) ; // make sure the match set is large enough if ( matchSet . size ( ) < minInlierSize ) break ; for ( Edgel e : matchSet ) { list . remove ( e ) ; } gridLines . add ( convertToLineSegment ( matchSet , robustMatcher . getModelParameters ( ) ) ) ; } } | Searches for lines inside inside the region .. | 182 | 10 |
27,719 | private LineSegment2D_F32 convertToLineSegment ( List < Edgel > matchSet , LinePolar2D_F32 model ) { float minT = Float . MAX_VALUE ; float maxT = - Float . MAX_VALUE ; LineParametric2D_F32 line = UtilLine2D_F32 . convert ( model , ( LineParametric2D_F32 ) null ) ; Point2D_F32 p = new Point2D_F32 ( ) ; for ( Edgel e : matchSet ) { p . set ( e . x , e . y ) ; float t = ClosestPoint2D_F32 . closestPointT ( line , e ) ; if ( minT > t ) minT = t ; if ( maxT < t ) maxT = t ; } LineSegment2D_F32 segment = new LineSegment2D_F32 ( ) ; segment . a . x = line . p . x + line . slope . x * minT ; segment . a . y = line . p . y + line . slope . y * minT ; segment . b . x = line . p . x + line . slope . x * maxT ; segment . b . y = line . p . y + line . slope . y * maxT ; return segment ; } | Lines are found in polar form and this coverts them into line segments by finding the extreme points of points on the line . | 289 | 26 |
27,720 | public TldFernFeature lookupFern ( int value ) { TldFernFeature found = table [ value ] ; if ( found == null ) { found = createFern ( ) ; found . init ( value ) ; table [ value ] = found ; } return found ; } | Looks up the fern with the specified value . If non exist a new one is created and returned . | 60 | 21 |
27,721 | public double lookupPosterior ( int value ) { TldFernFeature found = table [ value ] ; if ( found == null ) { return 0 ; } return found . posterior ; } | Looks up the posterior probability of the specified fern . If a fern is found its posterior is returned otherwise - 1 is returned . | 40 | 27 |
27,722 | void handleAdd ( ) { BoofSwingUtil . checkGuiThread ( ) ; java . util . List < File > paths = browser . getSelectedFiles ( ) ; for ( int i = 0 ; i < paths . size ( ) ; i ++ ) { File f = paths . get ( i ) ; // if it's a directory add all the files in the directory if ( f . isDirectory ( ) ) { java . util . List < String > files = UtilIO . listAll ( f . getPath ( ) ) ; Collections . sort ( files ) ; for ( int j = 0 ; j < files . size ( ) ; j ++ ) { File p = new File ( files . get ( j ) ) ; // Note: Can't use mimetype to determine if it's an image or not since it isn't 100% reliable if ( p . isFile ( ) ) { selected . addPath ( p ) ; } } } else { selected . addPath ( f ) ; } } } | Add all selected files | 215 | 4 |
27,723 | void handleOK ( ) { String [ ] selected = this . selected . paths . toArray ( new String [ 0 ] ) ; listener . selectedImages ( selected ) ; } | OK button pressed | 36 | 3 |
27,724 | void showPreview ( String path ) { synchronized ( lockPreview ) { if ( path == null ) { pendingPreview = null ; } else if ( previewThread == null ) { pendingPreview = path ; previewThread = new PreviewThread ( ) ; previewThread . start ( ) ; } else { pendingPreview = path ; } } } | Start a new preview thread if one isn t already running . Carefully manipulate variables due to threading | 68 | 20 |
27,725 | public static List < Point2D_F64 > createLayout ( int numRows , int numCols , double squareWidth , double spaceWidth ) { List < Point2D_F64 > all = new ArrayList <> ( ) ; double width = ( numCols * squareWidth + ( numCols - 1 ) * spaceWidth ) ; double height = ( numRows * squareWidth + ( numRows - 1 ) * spaceWidth ) ; double startX = - width / 2 ; double startY = - height / 2 ; for ( int i = numRows - 1 ; i >= 0 ; i -- ) { // this will be on the top of the black in the row double y = startY + i * ( squareWidth + spaceWidth ) + squareWidth ; List < Point2D_F64 > top = new ArrayList <> ( ) ; List < Point2D_F64 > bottom = new ArrayList <> ( ) ; for ( int j = 0 ; j < numCols ; j ++ ) { double x = startX + j * ( squareWidth + spaceWidth ) ; top . add ( new Point2D_F64 ( x , y ) ) ; top . add ( new Point2D_F64 ( x + squareWidth , y ) ) ; bottom . add ( new Point2D_F64 ( x , y - squareWidth ) ) ; bottom . add ( new Point2D_F64 ( x + squareWidth , y - squareWidth ) ) ; } all . addAll ( top ) ; all . addAll ( bottom ) ; } return all ; } | Creates a target that is composed of squares . The squares are spaced out and each corner provides a calibration point . | 344 | 23 |
27,726 | public void process ( FastQueue < PositionPatternNode > pps , T gray ) { gridReader . setImage ( gray ) ; storageQR . reset ( ) ; successes . clear ( ) ; failures . clear ( ) ; for ( int i = 0 ; i < pps . size ; i ++ ) { PositionPatternNode ppn = pps . get ( i ) ; for ( int j = 3 , k = 0 ; k < 4 ; j = k , k ++ ) { if ( ppn . edges [ j ] != null && ppn . edges [ k ] != null ) { QrCode qr = storageQR . grow ( ) ; qr . reset ( ) ; setPositionPatterns ( ppn , j , k , qr ) ; computeBoundingBox ( qr ) ; // Decode the entire marker now if ( decode ( gray , qr ) ) { successes . add ( qr ) ; } else { failures . add ( qr ) ; } } } } } | Detects QR Codes inside image using position pattern graph | 213 | 10 |
27,727 | static void computeBoundingBox ( QrCode qr ) { qr . bounds . get ( 0 ) . set ( qr . ppCorner . get ( 0 ) ) ; qr . bounds . get ( 1 ) . set ( qr . ppRight . get ( 1 ) ) ; Intersection2D_F64 . intersection ( qr . ppRight . get ( 1 ) , qr . ppRight . get ( 2 ) , qr . ppDown . get ( 3 ) , qr . ppDown . get ( 2 ) , qr . bounds . get ( 2 ) ) ; qr . bounds . get ( 3 ) . set ( qr . ppDown . get ( 3 ) ) ; } | 3 or the 4 corners are from the position patterns . The 4th is extrapolated using the position pattern sides . | 153 | 23 |
27,728 | private boolean extractFormatInfo ( QrCode qr ) { for ( int i = 0 ; i < 2 ; i ++ ) { // probably a better way to do this would be to go with the region that has the smallest // hamming distance if ( i == 0 ) readFormatRegion0 ( qr ) ; else readFormatRegion1 ( qr ) ; int bitField = this . bits . read ( 0 , 15 , false ) ; bitField ^= QrCodePolynomialMath . FORMAT_MASK ; int message ; if ( QrCodePolynomialMath . checkFormatBits ( bitField ) ) { message = bitField >> 10 ; } else { message = QrCodePolynomialMath . correctFormatBits ( bitField ) ; } if ( message >= 0 ) { QrCodePolynomialMath . decodeFormatMessage ( message , qr ) ; return true ; } } return false ; } | Reads format info bits from the image and saves the results in qr | 198 | 15 |
27,729 | private boolean readFormatRegion0 ( QrCode qr ) { // set the coordinate system to the closest pp to reduce position errors gridReader . setSquare ( qr . ppCorner , ( float ) qr . threshCorner ) ; bits . resize ( 15 ) ; bits . zero ( ) ; for ( int i = 0 ; i < 6 ; i ++ ) { read ( i , i , 8 ) ; } read ( 6 , 7 , 8 ) ; read ( 7 , 8 , 8 ) ; read ( 8 , 8 , 7 ) ; for ( int i = 0 ; i < 6 ; i ++ ) { read ( 9 + i , 8 , 5 - i ) ; } return true ; } | Reads the format bits near the corner position pattern | 150 | 10 |
27,730 | private boolean readFormatRegion1 ( QrCode qr ) { // if( qr.ppRight.get(0).distance(988.8,268.3) < 30 ) // System.out.println("tjere"); // System.out.println(qr.ppRight.get(0)); // set the coordinate system to the closest pp to reduce position errors gridReader . setSquare ( qr . ppRight , ( float ) qr . threshRight ) ; bits . resize ( 15 ) ; bits . zero ( ) ; for ( int i = 0 ; i < 8 ; i ++ ) { read ( i , 8 , 6 - i ) ; } gridReader . setSquare ( qr . ppDown , ( float ) qr . threshDown ) ; for ( int i = 0 ; i < 6 ; i ++ ) { read ( i + 8 , i , 8 ) ; } return true ; } | Read the format bits on the right and bottom patterns | 199 | 10 |
27,731 | private boolean readRawData ( QrCode qr ) { QrCode . VersionInfo info = QrCode . VERSION_INFO [ qr . version ] ; qr . rawbits = new byte [ info . codewords ] ; // predeclare memory bits . resize ( info . codewords * 8 ) ; // read bits from memory List < Point2D_I32 > locationBits = QrCode . LOCATION_BITS [ qr . version ] ; // end at bits.size instead of locationBits.size because location might point to useless bits for ( int i = 0 ; i < bits . size ; i ++ ) { Point2D_I32 b = locationBits . get ( i ) ; readDataMatrix ( i , b . y , b . x , qr . mask ) ; } // System.out.println("Version "+qr.version); // System.out.println("bits8.size "+bits8.size+" locationBits "+locationBits.size()); // bits8.print(); // copy over the results System . arraycopy ( bits . data , 0 , qr . rawbits , 0 , qr . rawbits . length ) ; return true ; } | Read the raw data from input memory | 265 | 7 |
27,732 | private void read ( int bit , int row , int col ) { int value = gridReader . readBit ( row , col ) ; if ( value == - 1 ) { // The requested region is outside the image. A partial QR code can be read so let's just // assign it a value of zero and let error correction handle this value = 0 ; } bits . set ( bit , value ) ; } | Reads a bit from the image . | 84 | 8 |
27,733 | boolean extractVersionInfo ( QrCode qr ) { int version = estimateVersionBySize ( qr ) ; // For version 7 and beyond use the version which has been encoded into the qr code if ( version >= QrCode . VERSION_ENCODED_AT ) { readVersionRegion0 ( qr ) ; int version0 = decodeVersion ( ) ; readVersionRegion1 ( qr ) ; int version1 = decodeVersion ( ) ; if ( version0 < 1 && version1 < 1 ) { // both decodings failed version = - 1 ; } else if ( version0 < 1 ) { // one failed so use the good one version = version1 ; } else if ( version1 < 1 ) { version = version0 ; } else if ( version0 != version1 ) { version = - 1 ; } else { version = version0 ; } } else if ( version <= 0 ) { version = - 1 ; } qr . version = version ; return version >= 1 && version <= QrCode . MAX_VERSION ; } | Determine the QR code s version . For QR codes version < 7 it can be determined using the marker s size alone . Otherwise the version is read from the image itself | 222 | 35 |
27,734 | int decodeVersion ( ) { int bitField = this . bits . read ( 0 , 18 , false ) ; int message ; // see if there's any errors if ( QrCodePolynomialMath . checkVersionBits ( bitField ) ) { message = bitField >> 12 ; } else { message = QrCodePolynomialMath . correctVersionBits ( bitField ) ; } // sanity check results if ( message > QrCode . MAX_VERSION || message < QrCode . VERSION_ENCODED_AT ) return - 1 ; return message ; } | Decode version information from read in bits | 122 | 8 |
27,735 | int estimateVersionBySize ( QrCode qr ) { // Just need the homography for this corner square square gridReader . setMarkerUnknownVersion ( qr , 0 ) ; // Compute location of position patterns relative to corner PP gridReader . imageToGrid ( qr . ppRight . get ( 0 ) , grid ) ; // see if pp is miss aligned. Probably not a flat surface // or they don't belong to the same qr code if ( Math . abs ( grid . y / grid . x ) >= 0.3 ) return - 1 ; double versionX = ( ( grid . x + 7 ) - 17 ) / 4 ; gridReader . imageToGrid ( qr . ppDown . get ( 0 ) , grid ) ; if ( Math . abs ( grid . x / grid . y ) >= 0.3 ) return - 1 ; double versionY = ( ( grid . y + 7 ) - 17 ) / 4 ; // see if they are in agreement if ( Math . abs ( versionX - versionY ) / Math . max ( versionX , versionY ) > 0.4 ) return - 1 ; return ( int ) ( ( versionX + versionY ) / 2.0 + 0.5 ) ; } | Attempts to estimate the qr - code s version based on distance between position patterns . If it can t estimate it based on distance return - 1 | 261 | 29 |
27,736 | private boolean readVersionRegion0 ( QrCode qr ) { // set the coordinate system to the closest pp to reduce position errors gridReader . setSquare ( qr . ppRight , ( float ) qr . threshRight ) ; bits . resize ( 18 ) ; bits . zero ( ) ; for ( int i = 0 ; i < 18 ; i ++ ) { int row = i / 3 ; int col = i % 3 ; read ( i , row , col - 4 ) ; } // System.out.println(" decoder version region 0 = "+Integer.toBinaryString(bits.data[0])); return true ; } | Reads the version bits near the right position pattern | 136 | 10 |
27,737 | private boolean readVersionRegion1 ( QrCode qr ) { // set the coordinate system to the closest pp to reduce position errors gridReader . setSquare ( qr . ppDown , ( float ) qr . threshDown ) ; bits . resize ( 18 ) ; bits . zero ( ) ; for ( int i = 0 ; i < 18 ; i ++ ) { int row = i % 3 ; int col = i / 3 ; read ( i , row - 4 , col ) ; } // System.out.println(" decoder version region 1 = "+Integer.toBinaryString(bits.data[0])); return true ; } | Reads the version bits near the bottom position pattern | 136 | 10 |
27,738 | public static void hessianBorder ( 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 ) ; int radiusFeature = size / 2 ; final int borderOrig = radiusFeature + 1 + ( skip - ( radiusFeature + 1 ) % skip ) ; final int border = borderOrig / skip ; float norm = 1.0f / ( size * size ) ; BoofConcurrency . loopFor ( 0 , h , y -> { int yy = y * skip ; for ( int x = 0 ; x < border ; x ++ ) { int xx = x * skip ; computeHessian ( integral , intensity , kerXX , kerYY , kerXY , norm , y , yy , x , xx ) ; } for ( int x = w - border ; x < w ; x ++ ) { int xx = x * skip ; computeHessian ( integral , intensity , kerXX , kerYY , kerXY , norm , y , yy , x , xx ) ; } } ) ; BoofConcurrency . loopFor ( border , w - border , x -> { int xx = x * skip ; for ( int y = 0 ; y < border ; y ++ ) { int yy = y * skip ; computeHessian ( integral , intensity , kerXX , kerYY , kerXY , norm , y , yy , x , xx ) ; } for ( int y = h - border ; y < h ; y ++ ) { int yy = y * skip ; computeHessian ( integral , intensity , kerXX , kerYY , kerXY , norm , y , yy , x , xx ) ; } } ) ; } | Only computes the fast hessian along the border using a brute force approach | 449 | 16 |
27,739 | public static GrayU8 logicAnd ( GrayU8 inputA , GrayU8 inputB , GrayU8 output ) { InputSanityCheck . checkSameShape ( inputA , inputB ) ; output = InputSanityCheck . checkDeclare ( inputA , output ) ; if ( BoofConcurrency . USE_CONCURRENT ) { ImplBinaryImageOps_MT . logicAnd ( inputA , inputB , output ) ; } else { ImplBinaryImageOps . logicAnd ( inputA , inputB , output ) ; } return output ; } | For each pixel it applies the logical and operator between two images . | 119 | 13 |
27,740 | public static GrayU8 invert ( GrayU8 input , GrayU8 output ) { output = InputSanityCheck . checkDeclare ( input , output ) ; if ( BoofConcurrency . USE_CONCURRENT ) { ImplBinaryImageOps_MT . invert ( input , output ) ; } else { ImplBinaryImageOps . invert ( input , output ) ; } return output ; } | Inverts each pixel from true to false and vis - versa . | 87 | 13 |
27,741 | public static GrayU8 thin ( GrayU8 input , int maxIterations , GrayU8 output ) { output = InputSanityCheck . checkDeclare ( input , output ) ; output . setTo ( input ) ; BinaryThinning thinning = new BinaryThinning ( ) ; thinning . apply ( output , maxIterations ) ; return output ; } | Applies a morphological thinning operation to the image . Also known as skeletonization . | 76 | 18 |
27,742 | public static List < Contour > contourExternal ( GrayU8 input , ConnectRule rule ) { BinaryContourFinder alg = FactoryBinaryContourFinder . linearExternal ( ) ; alg . setConnectRule ( rule ) ; alg . process ( input ) ; return convertContours ( alg ) ; } | Finds the external contours only in the image | 70 | 10 |
27,743 | public static void relabel ( GrayS32 input , int labels [ ] ) { if ( BoofConcurrency . USE_CONCURRENT ) { ImplBinaryImageOps_MT . relabel ( input , labels ) ; } else { ImplBinaryImageOps . relabel ( input , labels ) ; } } | Used to change the labels in a labeled binary image . | 66 | 11 |
27,744 | public static GrayU8 labelToBinary ( GrayS32 labelImage , GrayU8 binaryImage ) { binaryImage = InputSanityCheck . checkDeclare ( labelImage , binaryImage , GrayU8 . class ) ; if ( BoofConcurrency . USE_CONCURRENT ) { ImplBinaryImageOps_MT . labelToBinary ( labelImage , binaryImage ) ; } else { ImplBinaryImageOps . labelToBinary ( labelImage , binaryImage ) ; } return binaryImage ; } | Converts a labeled image into a binary image by setting any non - zero value to one . | 109 | 19 |
27,745 | public static List < List < Point2D_I32 > > labelToClusters ( GrayS32 labelImage , int numLabels , FastQueue < Point2D_I32 > queue ) { List < List < Point2D_I32 >> ret = new ArrayList <> ( ) ; for ( int i = 0 ; i < numLabels + 1 ; i ++ ) { ret . add ( new ArrayList < Point2D_I32 > ( ) ) ; } if ( queue == null ) { queue = new FastQueue <> ( numLabels , Point2D_I32 . class , true ) ; } else queue . reset ( ) ; for ( int y = 0 ; y < labelImage . height ; y ++ ) { int start = labelImage . startIndex + y * labelImage . stride ; int end = start + labelImage . width ; for ( int index = start ; index < end ; index ++ ) { int v = labelImage . data [ index ] ; if ( v > 0 ) { Point2D_I32 p = queue . grow ( ) ; p . set ( index - start , y ) ; ret . get ( v ) . add ( p ) ; } } } // first list is a place holder and should be empty if ( ret . get ( 0 ) . size ( ) != 0 ) throw new RuntimeException ( "BUG!" ) ; ret . remove ( 0 ) ; return ret ; } | Scans through the labeled image and adds the coordinate of each pixel that has been labeled to a list specific to its label . | 306 | 25 |
27,746 | public static void clusterToBinary ( List < List < Point2D_I32 > > clusters , GrayU8 binary ) { ImageMiscOps . fill ( binary , 0 ) ; for ( List < Point2D_I32 > l : clusters ) { for ( Point2D_I32 p : l ) { binary . set ( p . x , p . y , 1 ) ; } } } | Sets each pixel in the list of clusters to one in the binary image . | 87 | 16 |
27,747 | public static int [ ] selectRandomColors ( int numBlobs , Random rand ) { int colors [ ] = new int [ numBlobs + 1 ] ; colors [ 0 ] = 0 ; // black int B = 100 ; for ( int i = 1 ; i < colors . length ; i ++ ) { int c ; while ( true ) { c = rand . nextInt ( 0xFFFFFF ) ; // make sure its not too dark and can't be distriquished from the background if ( ( c & 0xFF ) > B || ( ( c >> 8 ) & 0xFF ) > B || ( ( c >> 8 ) & 0xFF ) > B ) { break ; } } colors [ i ] = c ; } return colors ; } | Several blob rending functions take in an array of colors so that the random blobs can be drawn with the same color each time . This function selects a random color for each blob and returns it in an array . | 160 | 43 |
27,748 | public static void bufferDepthToU16 ( ByteBuffer input , GrayU16 output ) { int indexIn = 0 ; for ( int y = 0 ; y < output . height ; y ++ ) { int indexOut = output . startIndex + y * output . stride ; for ( int x = 0 ; x < output . width ; x ++ , indexOut ++ ) { output . data [ indexOut ] = ( short ) ( ( input . get ( indexIn ++ ) & 0xFF ) | ( ( input . get ( indexIn ++ ) & 0xFF ) << 8 ) ) ; } } } | Converts data in a ByteBuffer into a 16bit depth image | 128 | 13 |
27,749 | public static void bufferRgbToMsU8 ( byte [ ] input , Planar < GrayU8 > output ) { GrayU8 band0 = output . getBand ( 0 ) ; GrayU8 band1 = output . getBand ( 1 ) ; GrayU8 band2 = output . getBand ( 2 ) ; int indexIn = 0 ; for ( int y = 0 ; y < output . height ; y ++ ) { int indexOut = output . startIndex + y * output . stride ; for ( int x = 0 ; x < output . width ; x ++ , indexOut ++ ) { band0 . data [ indexOut ] = input [ indexIn ++ ] ; band1 . data [ indexOut ] = input [ indexIn ++ ] ; band2 . data [ indexOut ] = input [ indexIn ++ ] ; } } } | Converts byte array that contains RGB data into a 3 - channel Planar image | 178 | 16 |
27,750 | public void computeECC ( GrowQueue_I8 input , GrowQueue_I8 output ) { int N = generator . size - 1 ; input . extend ( input . size + N ) ; Arrays . fill ( input . data , input . size - N , input . size , ( byte ) 0 ) ; math . polyDivide ( input , generator , tmp0 , output ) ; input . size -= N ; } | Given the input message compute the error correction code for it | 89 | 11 |
27,751 | public boolean correct ( GrowQueue_I8 input , GrowQueue_I8 ecc ) { computeSyndromes ( input , ecc , syndromes ) ; findErrorLocatorPolynomialBM ( syndromes , errorLocatorPoly ) ; if ( ! findErrorLocations_BruteForce ( errorLocatorPoly , input . size + ecc . size , errorLocations ) ) return false ; correctErrors ( input , input . size + ecc . size , syndromes , errorLocatorPoly , errorLocations ) ; return true ; } | Decodes the message and performs any necessary error correction | 118 | 10 |
27,752 | void findErrorLocatorPolynomial ( int messageLength , GrowQueue_I32 errorLocations , GrowQueue_I8 errorLocator ) { tmp1 . resize ( 2 ) ; tmp1 . data [ 1 ] = 1 ; errorLocator . resize ( 1 ) ; errorLocator . data [ 0 ] = 1 ; for ( int i = 0 ; i < errorLocations . size ; i ++ ) { // Convert from positions in the message to coefficient degrees int where = messageLength - errorLocations . get ( i ) - 1 ; // tmp1 = [2**w,1] tmp1 . data [ 0 ] = ( byte ) math . power ( 2 , where ) ; // tmp1.data[1] = 1; tmp0 . setTo ( errorLocator ) ; math . polyMult ( tmp0 , tmp1 , errorLocator ) ; } } | Compute the error locator polynomial when given the error locations in the message . | 187 | 18 |
27,753 | public boolean findErrorLocations_BruteForce ( GrowQueue_I8 errorLocator , int messageLength , GrowQueue_I32 locations ) { locations . resize ( 0 ) ; for ( int i = 0 ; i < messageLength ; i ++ ) { if ( math . polyEval_S ( errorLocator , math . power ( 2 , i ) ) == 0 ) { locations . add ( messageLength - i - 1 ) ; } } // see if the expected number of errors were found return locations . size == errorLocator . size - 1 ; } | Creates a list of bytes that have errors in them | 120 | 11 |
27,754 | void correctErrors ( GrowQueue_I8 message , int length_msg_ecc , GrowQueue_I8 syndromes , GrowQueue_I8 errorLocator , GrowQueue_I32 errorLocations ) { GrowQueue_I8 err_eval = new GrowQueue_I8 ( ) ; // TODO avoid new findErrorEvaluator ( syndromes , errorLocator , err_eval ) ; // Compute error positions GrowQueue_I8 X = GrowQueue_I8 . zeros ( errorLocations . size ) ; // TODO avoid new for ( int i = 0 ; i < errorLocations . size ; i ++ ) { int coef_pos = ( length_msg_ecc - errorLocations . data [ i ] - 1 ) ; X . data [ i ] = ( byte ) math . power ( 2 , coef_pos ) ; // The commented out code below replicates exactly how the reference code works. This code above // seems to work just as well and passes all the unit tests // int coef_pos = math.max_value-(length_msg_ecc-errorLocations.data[i]-1); // X.data[i] = (byte)math.power_n(2,-coef_pos); } GrowQueue_I8 err_loc_prime_tmp = new GrowQueue_I8 ( X . size ) ; // storage for error magnitude polynomial for ( int i = 0 ; i < X . size ; i ++ ) { int Xi = X . data [ i ] & 0xFF ; int Xi_inv = math . inverse ( Xi ) ; // Compute the polynomial derivative err_loc_prime_tmp . size = 0 ; for ( int j = 0 ; j < X . size ; j ++ ) { if ( i == j ) continue ; err_loc_prime_tmp . data [ err_loc_prime_tmp . size ++ ] = ( byte ) GaliosFieldOps . subtract ( 1 , math . multiply ( Xi_inv , X . data [ j ] & 0xFF ) ) ; } // compute the product, which is the denominator of Forney algorithm (errata locator derivative) int err_loc_prime = 1 ; for ( int j = 0 ; j < err_loc_prime_tmp . size ; j ++ ) { err_loc_prime = math . multiply ( err_loc_prime , err_loc_prime_tmp . data [ j ] & 0xFF ) ; } int y = math . polyEval_S ( err_eval , Xi_inv ) ; y = math . multiply ( math . power ( Xi , 1 ) , y ) ; // Compute the magnitude int magnitude = math . divide ( y , err_loc_prime ) ; // only apply a correction if it's part of the message and not the ECC int loc = errorLocations . get ( i ) ; if ( loc < message . size ) message . data [ loc ] = ( byte ) ( ( message . data [ loc ] & 0xFF ) ^ magnitude ) ; } } | Use Forney algorithm to compute correction values . | 667 | 9 |
27,755 | void findErrorEvaluator ( GrowQueue_I8 syndromes , GrowQueue_I8 errorLocator , GrowQueue_I8 evaluator ) { math . polyMult_flipA ( syndromes , errorLocator , evaluator ) ; int N = errorLocator . size - 1 ; int offset = evaluator . size - N ; for ( int i = 0 ; i < N ; i ++ ) { evaluator . data [ i ] = evaluator . data [ i + offset ] ; } evaluator . data [ N ] = 0 ; evaluator . size = errorLocator . size ; // flip evaluator around // TODO remove this flip and do it in place for ( int i = 0 ; i < evaluator . size / 2 ; i ++ ) { int j = evaluator . size - i - 1 ; int tmp = evaluator . data [ i ] ; evaluator . data [ i ] = evaluator . data [ j ] ; evaluator . data [ j ] = ( byte ) tmp ; } } | Compute the error evaluator polynomial Omega . | 236 | 12 |
27,756 | public static < O extends ImageGray < O > > O [ ] declareOutput ( ImagePyramid < ? > pyramid , Class < O > outputType ) { O [ ] ret = ( O [ ] ) Array . newInstance ( outputType , pyramid . getNumLayers ( ) ) ; for ( int i = 0 ; i < ret . length ; i ++ ) { int w = pyramid . getWidth ( i ) ; int h = pyramid . getHeight ( i ) ; ret [ i ] = GeneralizedImageOps . createSingleBand ( outputType , w , h ) ; } return ret ; } | Creates an array of single band images for each layer in the provided pyramid . Each image will be the same size as the corresponding layer in the pyramid . | 127 | 31 |
27,757 | public static < O extends ImageGray < O > > void reshapeOutput ( ImagePyramid < ? > pyramid , O [ ] output ) { for ( int i = 0 ; i < output . length ; i ++ ) { int w = pyramid . getWidth ( i ) ; int h = pyramid . getHeight ( i ) ; output [ i ] . reshape ( w , h ) ; } } | Reshapes each image in the array to match the layers in the pyramid | 84 | 15 |
27,758 | public static void histogram ( GrayU8 image , int maxPixelValue , TupleDesc_F64 histogram ) { int numBins = histogram . size ( ) ; int divisor = maxPixelValue + 1 ; histogram . fill ( 0 ) ; for ( int y = 0 ; y < image . height ; y ++ ) { int index = image . startIndex + y * image . stride ; for ( int x = 0 ; x < image . width ; x ++ , index ++ ) { int value = image . data [ index ] & 0xFF ; int bin = numBins * value / divisor ; histogram . value [ bin ] ++ ; } } } | Computes a single - band normalized histogram from an integer image .. | 147 | 14 |
27,759 | public static < T > T convertGenericToSpecificType ( Class < ? > type ) { if ( type == GrayI8 . class ) return ( T ) GrayU8 . class ; if ( type == GrayI16 . class ) return ( T ) GrayS16 . class ; if ( type == InterleavedI8 . class ) return ( T ) InterleavedU8 . class ; if ( type == InterleavedI16 . class ) return ( T ) InterleavedS16 . class ; return ( T ) type ; } | If an image is to be created then the generic type can t be used a specific one needs to be . An arbitrary specific image type is returned here . | 114 | 31 |
27,760 | public static List < LineParametric2D_F32 > pruneSimilarLines ( List < LineParametric2D_F32 > lines , float intensity [ ] , float toleranceAngle , float toleranceDist , int imgWidth , int imgHeight ) { int indexSort [ ] = new int [ intensity . length ] ; QuickSort_F32 sort = new QuickSort_F32 ( ) ; sort . sort ( intensity , 0 , lines . size ( ) , indexSort ) ; float theta [ ] = new float [ lines . size ( ) ] ; List < LineSegment2D_F32 > segments = new ArrayList <> ( lines . size ( ) ) ; for ( int i = 0 ; i < lines . size ( ) ; i ++ ) { LineParametric2D_F32 l = lines . get ( i ) ; theta [ i ] = UtilAngle . atanSafe ( l . getSlopeY ( ) , l . getSlopeX ( ) ) ; segments . add ( convert ( l , imgWidth , imgHeight ) ) ; } for ( int i = segments . size ( ) - 1 ; i >= 0 ; i -- ) { LineSegment2D_F32 a = segments . get ( indexSort [ i ] ) ; if ( a == null ) continue ; for ( int j = i - 1 ; j >= 0 ; j -- ) { LineSegment2D_F32 b = segments . get ( indexSort [ j ] ) ; if ( b == null ) continue ; if ( UtilAngle . distHalf ( theta [ indexSort [ i ] ] , theta [ indexSort [ j ] ] ) > toleranceAngle ) continue ; Point2D_F32 p = Intersection2D_F32 . intersection ( a , b , null ) ; if ( p != null && p . x >= 0 && p . y >= 0 && p . x < imgWidth && p . y < imgHeight ) { segments . set ( indexSort [ j ] , null ) ; } else { float distA = Distance2D_F32 . distance ( a , b . a ) ; float distB = Distance2D_F32 . distance ( a , b . b ) ; if ( distA <= toleranceDist || distB < toleranceDist ) { segments . set ( indexSort [ j ] , null ) ; } } } } List < LineParametric2D_F32 > ret = new ArrayList <> ( ) ; for ( int i = 0 ; i < segments . size ( ) ; i ++ ) { if ( segments . get ( i ) != null ) { ret . add ( lines . get ( i ) ) ; } } return ret ; } | Prunes similar looking lines but keeps the lines with the most intensity . | 581 | 14 |
27,761 | public static LineSegment2D_F32 convert ( LineParametric2D_F32 l , int width , int height ) { double t0 = ( 0 - l . p . x ) / l . getSlopeX ( ) ; double t1 = ( 0 - l . p . y ) / l . getSlopeY ( ) ; double t2 = ( width - l . p . x ) / l . getSlopeX ( ) ; double t3 = ( height - l . p . y ) / l . getSlopeY ( ) ; Point2D_F32 a = computePoint ( l , t0 ) ; Point2D_F32 b = computePoint ( l , t1 ) ; Point2D_F32 c = computePoint ( l , t2 ) ; Point2D_F32 d = computePoint ( l , t3 ) ; List < Point2D_F32 > inside = new ArrayList <> ( ) ; checkAddInside ( width , height , a , inside ) ; checkAddInside ( width , height , b , inside ) ; checkAddInside ( width , height , c , inside ) ; checkAddInside ( width , height , d , inside ) ; if ( inside . size ( ) != 2 ) { return null ; // System.out.println("interesting"); } return new LineSegment2D_F32 ( inside . get ( 0 ) , inside . get ( 1 ) ) ; } | Find the point in which the line intersects the image border and create a line segment at those points | 311 | 20 |
27,762 | public static void applyMask ( GrayF32 disparity , GrayU8 mask , int radius ) { if ( disparity . isSubimage ( ) || mask . isSubimage ( ) ) throw new RuntimeException ( "Input is subimage. Currently not support but no reason why it can't be. Ask for it" ) ; int N = disparity . width * disparity . height ; for ( int i = 0 ; i < N ; i ++ ) { if ( mask . data [ i ] == 0 ) { disparity . data [ i ] = 255 ; } } // TODO make this more efficient and correct. Update unit test if ( radius > 0 ) { int r = radius ; for ( int y = r ; y < mask . height - r - 1 ; y ++ ) { int indexMsk = y * mask . stride + r ; for ( int x = r ; x < mask . width - r - 1 ; x ++ , indexMsk ++ ) { int deltaX = mask . data [ indexMsk ] - mask . data [ indexMsk + 1 ] ; int deltaY = mask . data [ indexMsk ] - mask . data [ indexMsk + mask . stride ] ; if ( deltaX != 0 || deltaY != 0 ) { // because of how the border is detected it has a bias when going from up to down if ( deltaX < 0 ) deltaX = 0 ; if ( deltaY < 0 ) deltaY = 0 ; for ( int i = - r ; i <= r ; i ++ ) { for ( int j = - r ; j <= r ; j ++ ) { disparity . set ( deltaX + x + j , deltaY + y + i , 255 ) ; } } } } } } } | Applies a mask which indicates which pixels had mappings to the unrectified image . Pixels which were outside of the original image will be set to 255 . The border is extended because the sharp edge in the rectified image can cause in incorrect match between image features . | 366 | 55 |
27,763 | public boolean fitAnchored ( int anchor0 , int anchor1 , GrowQueue_I32 corners , GrowQueue_I32 output ) { this . anchor0 = anchor0 ; this . anchor1 = anchor1 ; int numLines = anchor0 == anchor1 ? corners . size ( ) : CircularIndex . distanceP ( anchor0 , anchor1 , corners . size ) ; if ( numLines < 2 ) { throw new RuntimeException ( "The one line is anchored and can't be optimized" ) ; } lines . resize ( numLines ) ; if ( verbose ) System . out . println ( "ENTER FitLinesToContour" ) ; // Check pre-condition // checkDuplicateCorner(corners); workCorners . setTo ( corners ) ; for ( int iteration = 0 ; iteration < maxIterations ; iteration ++ ) { // fit the lines to the contour using only lines between each corner for each line if ( ! fitLinesUsingCorners ( numLines , workCorners ) ) { return false ; } // intersect each line and find the closest point on the contour as the new corner if ( ! linesIntoCorners ( numLines , workCorners ) ) { return false ; } // sanity check to see if corner order is still met if ( ! sanityCheckCornerOrder ( numLines , workCorners ) ) { return false ; // TODO detect and handle this condition better } // TODO check for convergence } if ( verbose ) System . out . println ( "EXIT FitLinesToContour. " + corners . size ( ) + " " + workCorners . size ( ) ) ; output . setTo ( workCorners ) ; return true ; } | Fits line segments along the contour with the first and last corner fixed at the original corners . The output will be a new set of corner indexes . Since the corner list is circular it is assumed that anchor1 comes after anchor0 . The same index can be specified for an anchor it will just go around the entire circle | 371 | 65 |
27,764 | boolean sanityCheckCornerOrder ( int numLines , GrowQueue_I32 corners ) { int contourAnchor0 = corners . get ( anchor0 ) ; int previous = 0 ; for ( int i = 1 ; i < numLines ; i ++ ) { int contourIndex = corners . get ( CircularIndex . addOffset ( anchor0 , i , corners . size ( ) ) ) ; int pixelsFromAnchor0 = CircularIndex . distanceP ( contourAnchor0 , contourIndex , contour . size ( ) ) ; if ( pixelsFromAnchor0 < previous ) { return false ; } else { previous = pixelsFromAnchor0 ; } } return true ; } | All the corners should be in increasing order from the first anchor . | 155 | 13 |
27,765 | boolean fitLinesUsingCorners ( int numLines , GrowQueue_I32 cornerIndexes ) { for ( int i = 1 ; i <= numLines ; i ++ ) { int index0 = cornerIndexes . get ( CircularIndex . addOffset ( anchor0 , i - 1 , cornerIndexes . size ) ) ; int index1 = cornerIndexes . get ( CircularIndex . addOffset ( anchor0 , i , cornerIndexes . size ) ) ; if ( index0 == index1 ) return false ; if ( ! fitLine ( index0 , index1 , lines . get ( i - 1 ) ) ) { // TODO do something more intelligent here. Just leave the corners as is? return false ; } LineGeneral2D_F64 l = lines . get ( i - 1 ) ; if ( Double . isNaN ( l . A ) || Double . isNaN ( l . B ) || Double . isNaN ( l . C ) ) { throw new RuntimeException ( "This should be impossible" ) ; } } return true ; } | Fits lines across the sequence of corners | 230 | 8 |
27,766 | boolean fitLine ( int contourIndex0 , int contourIndex1 , LineGeneral2D_F64 line ) { int numPixels = CircularIndex . distanceP ( contourIndex0 , contourIndex1 , contour . size ( ) ) ; // if its too small if ( numPixels < minimumLineLength ) return false ; Point2D_I32 c0 = contour . get ( contourIndex0 ) ; Point2D_I32 c1 = contour . get ( contourIndex1 ) ; double scale = c0 . distance ( c1 ) ; double centerX = ( c1 . x + c0 . x ) / 2.0 ; double centerY = ( c1 . y + c0 . y ) / 2.0 ; int numSamples = Math . min ( maxSamples , numPixels ) ; pointsFit . reset ( ) ; for ( int i = 0 ; i < numSamples ; i ++ ) { int index = i * ( numPixels - 1 ) / ( numSamples - 1 ) ; Point2D_I32 c = contour . get ( CircularIndex . addOffset ( contourIndex0 , index , contour . size ( ) ) ) ; Point2D_F64 p = pointsFit . grow ( ) ; p . x = ( c . x - centerX ) / scale ; p . y = ( c . y - centerY ) / scale ; } if ( null == FitLine_F64 . polar ( pointsFit . toList ( ) , linePolar ) ) { return false ; } UtilLine2D_F64 . convert ( linePolar , line ) ; // go from local coordinates into global line . C = scale * line . C - centerX * line . A - centerY * line . B ; return true ; } | Given a sequence of points on the contour find the best fit line . | 395 | 15 |
27,767 | int closestPoint ( Point2D_F64 target ) { double bestDistance = Double . MAX_VALUE ; int bestIndex = - 1 ; for ( int i = 0 ; i < contour . size ( ) ; i ++ ) { Point2D_I32 c = contour . get ( i ) ; double d = UtilPoint2D_F64 . distanceSq ( target . x , target . y , c . x , c . y ) ; if ( d < bestDistance ) { bestDistance = d ; bestIndex = i ; } } return bestIndex ; } | Returns the closest point on the contour to the provided point in space | 124 | 14 |
27,768 | public void setTransformFromLinesSquare ( QrCode qr ) { // clear old points storagePairs2D . reset ( ) ; storagePairs3D . reset ( ) ; // use 3 of the corners to set the coordinate system // set(0, 0, qr.ppCorner,0); <-- prone to damage. Significantly degrades results if used set ( 0 , 7 , qr . ppCorner , 1 ) ; set ( 7 , 7 , qr . ppCorner , 2 ) ; set ( 7 , 0 , qr . ppCorner , 3 ) ; // Use 4 lines to make it more robust errors in these corners // We just need to get the direction right for the lines. the exact grid to image doesn't matter setLine ( 0 , 7 , 0 , 14 , qr . ppCorner , 1 , qr . ppRight , 0 ) ; setLine ( 7 , 7 , 7 , 14 , qr . ppCorner , 2 , qr . ppRight , 3 ) ; setLine ( 7 , 7 , 14 , 7 , qr . ppCorner , 2 , qr . ppDown , 1 ) ; setLine ( 7 , 0 , 14 , 0 , qr . ppCorner , 3 , qr . ppDown , 0 ) ; DMatrixRMaj HH = new DMatrixRMaj ( 3 , 3 ) ; dlt . process ( storagePairs2D . toList ( ) , storagePairs3D . toList ( ) , null , HH ) ; H . set ( HH ) ; H . invert ( Hinv ) ; ConvertFloatType . convert ( Hinv , Hinv32 ) ; ConvertFloatType . convert ( H , H32 ) ; } | Used to estimate the image to grid coordinate system before the version is known . The top left square is used to fix the coordinate system . Then 4 lines between corners going to other QR codes is used to make it less suspectable to errors in the first 4 corners | 372 | 52 |
27,769 | public void removeOutsideCornerFeatures ( ) { if ( pairs2D . size ( ) != storagePairs2D . size ) throw new RuntimeException ( "This can only be called when all the features have been added" ) ; pairs2D . remove ( 11 ) ; pairs2D . remove ( 5 ) ; pairs2D . remove ( 0 ) ; } | Outside corners on position patterns are more likely to be damaged so remove them | 77 | 14 |
27,770 | public static < T extends ImageGray < T > > SearchLocalPeak < T > meanShiftUniform ( int maxIterations , float convergenceTol , Class < T > imageType ) { WeightPixel_F32 weights = new WeightPixelUniform_F32 ( ) ; MeanShiftPeak < T > alg = new MeanShiftPeak <> ( maxIterations , convergenceTol , weights , imageType ) ; return new MeanShiftPeak_to_SearchLocalPeak <> ( alg ) ; } | Mean - shift based search with a uniform kernel | 112 | 10 |
27,771 | public static < T extends ImageGray < T > > SearchLocalPeak < T > meanShiftGaussian ( int maxIterations , float convergenceTol , Class < T > imageType ) { WeightPixel_F32 weights = new WeightPixelGaussian_F32 ( ) ; MeanShiftPeak < T > alg = new MeanShiftPeak <> ( maxIterations , convergenceTol , weights , imageType ) ; return new MeanShiftPeak_to_SearchLocalPeak <> ( alg ) ; } | Mean - shift based search with a Gaussian kernel | 112 | 11 |
27,772 | public static void loopBlocks ( int start , int endExclusive , int minBlock , IntRangeConsumer consumer ) { final ForkJoinPool pool = BoofConcurrency . pool ; int numThreads = pool . getParallelism ( ) ; int range = endExclusive - start ; if ( range == 0 ) // nothing to do here! return ; if ( range < 0 ) throw new IllegalArgumentException ( "end must be more than start. " + start + " -> " + endExclusive ) ; int block = selectBlockSize ( range , minBlock , numThreads ) ; try { pool . submit ( new IntRangeTask ( start , endExclusive , block , consumer ) ) . get ( ) ; } catch ( InterruptedException | ExecutionException e ) { e . printStackTrace ( ) ; } } | Automatically breaks the problem up into blocks based on the number of threads available . It is assumed that there is some cost associated with processing a block and the number of blocks is minimized . | 175 | 37 |
27,773 | public static void loopBlocks ( int start , int endExclusive , IntRangeConsumer consumer ) { final ForkJoinPool pool = BoofConcurrency . pool ; int numThreads = pool . getParallelism ( ) ; int range = endExclusive - start ; if ( range == 0 ) // nothing to do here! return ; if ( range < 0 ) throw new IllegalArgumentException ( "end must be more than start. " + start + " -> " + endExclusive ) ; // Did some experimentation here. Gave it more threads than were needed or exactly what was needed // exactly seemed to do better in the test cases int blockSize = Math . max ( 1 , range / numThreads ) ; try { pool . submit ( new IntRangeTask ( start , endExclusive , blockSize , consumer ) ) . get ( ) ; } catch ( InterruptedException | ExecutionException e ) { throw new RuntimeException ( e ) ; } } | Splits the range of values up into blocks . It s assumed the cost to process a block is small so more can be created . | 200 | 27 |
27,774 | public static Number sum ( int start , int endExclusive , Class type , IntProducerNumber producer ) { try { return pool . submit ( new IntOperatorTask . Sum ( start , endExclusive , type , producer ) ) . get ( ) ; } catch ( InterruptedException | ExecutionException e ) { throw new RuntimeException ( e ) ; } } | Computes sums up the results using the specified primitive type | 76 | 11 |
27,775 | public synchronized T pop ( ) { if ( list . isEmpty ( ) ) { return factory . newInstance ( ) ; } else { return list . remove ( list . size ( ) - 1 ) ; } } | Returns an instance . If there are instances queued up internally one of those is returned . Otherwise a new instance is created . | 44 | 25 |
27,776 | private void printGrid ( PDPageContentStream pcs , float offsetX , float offsetY , int numRows , int numCols , float sizeBox ) throws IOException { float pageWidth = ( float ) paper . convertWidth ( units ) * UNIT_TO_POINTS ; float pageHeight = ( float ) paper . convertHeight ( units ) * UNIT_TO_POINTS ; // pcs.setLineCapStyle(1); pcs . setStrokingColor ( 0.75 ) ; for ( int i = 0 ; i <= numCols ; i ++ ) { float x = offsetX + i * sizeBox ; pcs . moveTo ( x , 0 ) ; pcs . lineTo ( x , pageHeight ) ; } for ( int i = 0 ; i <= numRows ; i ++ ) { float y = offsetY + i * sizeBox ; pcs . moveTo ( 0 , y ) ; pcs . lineTo ( pageWidth , y ) ; } pcs . closeAndStroke ( ) ; } | Draws the grid in light grey on the document | 228 | 10 |
27,777 | public void setInput ( I input ) { this . inputImage = input ; // reset the state flag so that everything need sto be computed if ( stale != null ) { for ( int i = 0 ; i < stale . length ; i ++ ) { boolean a [ ] = stale [ i ] ; for ( int j = 0 ; j < a . length ; j ++ ) { a [ j ] = true ; } } } } | Sets the new input image from which the image derivatives are computed from . | 90 | 15 |
27,778 | public void configure ( double descriptorRegionScale , double periodX , double periodY ) { this . radius = descriptorRegionScale * scaleToRadius ; this . periodX = ( int ) ( periodX + 0.5 ) ; this . periodY = ( int ) ( periodY + 0.5 ) ; this . featureWidth = ( int ) ( alg . getCanonicalWidth ( ) * descriptorRegionScale + 0.5 ) ; descriptions = new FastQueue < Desc > ( alg . getDescriptionType ( ) , true ) { @ Override protected Desc createInstance ( ) { return alg . createDescription ( ) ; } } ; } | Configures size of the descriptor and the frequency at which it s computed | 138 | 14 |
27,779 | public void setPoint ( int which , double x , double y , double z ) { points [ which ] . set ( x , y , z ) ; } | Specifies the location of a point in 3D space | 33 | 11 |
27,780 | public void connectPointToView ( int pointIndex , int viewIndex ) { SceneStructureMetric . Point p = points [ pointIndex ] ; for ( int i = 0 ; i < p . views . size ; i ++ ) { if ( p . views . data [ i ] == viewIndex ) throw new IllegalArgumentException ( "Tried to add the same view twice. viewIndex=" + viewIndex ) ; } p . views . add ( viewIndex ) ; } | Specifies that the point was observed in this view . | 101 | 11 |
27,781 | public void removePoints ( GrowQueue_I32 which ) { SceneStructureMetric . Point results [ ] = new SceneStructureMetric . Point [ points . length - which . size ] ; int indexWhich = 0 ; for ( int i = 0 ; i < points . length ; i ++ ) { if ( indexWhich < which . size && which . data [ indexWhich ] == i ) { indexWhich ++ ; } else { results [ i - indexWhich ] = points [ i ] ; } } points = results ; } | Removes the points specified in which from the list of points . which must be ordered from lowest to highest index . | 112 | 23 |
27,782 | public void select ( List < Se3_F64 > candidatesAtoB , List < AssociatedPair > observations , Se3_F64 model ) { // use positive depth constraint to select the best one Se3_F64 bestModel = null ; int bestCount = - 1 ; for ( int i = 0 ; i < candidatesAtoB . size ( ) ; i ++ ) { Se3_F64 s = candidatesAtoB . get ( i ) ; int count = 0 ; for ( AssociatedPair p : observations ) { if ( depthCheck . checkConstraint ( p . p1 , p . p2 , s ) ) { count ++ ; } } if ( count > bestCount ) { bestCount = count ; bestModel = s ; } } if ( bestModel == null ) throw new RuntimeException ( "BUG" ) ; model . set ( bestModel ) ; } | Selects the transform which describes a view where observations appear in front of the camera the most | 189 | 18 |
27,783 | public float get ( int x , int y ) { if ( ! isInBounds ( x , y ) ) throw new ImageAccessException ( "Requested pixel is out of bounds: ( " + x + " , " + y + " )" ) ; return unsafe_get ( x , y ) ; } | Returns the value of the specified pixel . | 66 | 8 |
27,784 | public void apply ( GrayU8 binary , int maxLoops ) { this . binary = binary ; inputBorder . setImage ( binary ) ; ones0 . reset ( ) ; zerosOut . reset ( ) ; findOnePixels ( ones0 ) ; for ( int loop = 0 ; ( loop < maxLoops || maxLoops == - 1 ) && ones0 . size > 0 ; loop ++ ) { boolean changed = false ; // do one cycle through all the masks for ( int i = 0 ; i < masks . length ; i ++ ) { zerosOut . reset ( ) ; ones1 . reset ( ) ; masks [ i ] . apply ( ones0 , ones1 , zerosOut ) ; changed |= ones0 . size != ones1 . size ; // mark all the pixels that need to be set to 0 as 0 for ( int j = 0 ; j < zerosOut . size ( ) ; j ++ ) { binary . data [ zerosOut . get ( j ) ] = 0 ; } // swap the lists GrowQueue_I32 tmp = ones0 ; ones0 = ones1 ; ones1 = tmp ; } if ( ! changed ) break ; } } | Applies the thinning algorithm . Runs for the specified number of loops or until no change is detected . | 250 | 21 |
27,785 | protected void findOnePixels ( GrowQueue_I32 ones ) { for ( int y = 0 ; y < binary . height ; y ++ ) { int index = binary . startIndex + y * binary . stride ; for ( int x = 0 ; x < binary . width ; x ++ , index ++ ) { if ( binary . data [ index ] != 0 ) { ones . add ( index ) ; } } } } | Scans through the image and record the array index of all marked pixels | 89 | 14 |
27,786 | public void pruneObservationsBehindCamera ( ) { Point3D_F64 X = new Point3D_F64 ( ) ; for ( int viewIndex = 0 ; viewIndex < observations . views . length ; viewIndex ++ ) { SceneObservations . View v = observations . views [ viewIndex ] ; SceneStructureMetric . View view = structure . views [ viewIndex ] ; for ( int pointIndex = 0 ; pointIndex < v . point . size ; pointIndex ++ ) { SceneStructureMetric . Point f = structure . points [ v . getPointId ( pointIndex ) ] ; // Get feature location in world f . get ( X ) ; if ( ! f . views . contains ( viewIndex ) ) throw new RuntimeException ( "BUG!" ) ; // World to View view . worldToView . transform ( X , X ) ; // Is the feature behind this view and can't be seen? if ( X . z <= 0 ) { v . set ( pointIndex , Float . NaN , Float . NaN ) ; } } } removeMarkedObservations ( ) ; } | Check to see if a point is behind the camera which is viewing it . If it is remove that observation since it can t possibly be observed . | 237 | 29 |
27,787 | public void prunePoints ( int neighbors , double distance ) { // Use a nearest neighbor search to find near by points Point3D_F64 worldX = new Point3D_F64 ( ) ; List < Point3D_F64 > cloud = new ArrayList <> ( ) ; for ( int i = 0 ; i < structure . points . length ; i ++ ) { SceneStructureMetric . Point structureP = structure . points [ i ] ; structureP . get ( worldX ) ; cloud . add ( worldX . copy ( ) ) ; } NearestNeighbor < Point3D_F64 > nn = FactoryNearestNeighbor . kdtree ( new KdTreePoint3D_F64 ( ) ) ; NearestNeighbor . Search < Point3D_F64 > search = nn . createSearch ( ) ; nn . setPoints ( cloud , false ) ; FastQueue < NnData < Point3D_F64 > > resultsNN = new FastQueue ( NnData . class , true ) ; // Create a look up table containing from old to new indexes for each point int oldToNew [ ] = new int [ structure . points . length ] ; Arrays . fill ( oldToNew , - 1 ) ; // crash is bug // List of point ID's which are to be removed. GrowQueue_I32 prunePointID = new GrowQueue_I32 ( ) ; // identify points which need to be pruned for ( int pointId = 0 ; pointId < structure . points . length ; pointId ++ ) { SceneStructureMetric . Point structureP = structure . points [ pointId ] ; structureP . get ( worldX ) ; // distance is squared search . findNearest ( cloud . get ( pointId ) , distance * distance , neighbors + 1 , resultsNN ) ; // Don't prune if it has enough neighbors. Remember that it will always find itself. if ( resultsNN . size ( ) > neighbors ) { oldToNew [ pointId ] = pointId - prunePointID . size ; continue ; } prunePointID . add ( pointId ) ; // Remove observations of this point for ( int viewIdx = 0 ; viewIdx < structureP . views . size ; viewIdx ++ ) { SceneObservations . View v = observations . getView ( structureP . views . data [ viewIdx ] ) ; int pointIdx = v . point . indexOf ( pointId ) ; if ( pointIdx < 0 ) throw new RuntimeException ( "Bad structure. Point not found in view's observation " + "which was in its structure" ) ; v . remove ( pointIdx ) ; } } pruneUpdatePointID ( oldToNew , prunePointID ) ; } | Prune a feature it has fewer than X neighbors within Y distance . Observations associated with this feature are also pruned . | 593 | 25 |
27,788 | public void pruneViews ( int count ) { List < SceneStructureMetric . View > remainingS = new ArrayList <> ( ) ; List < SceneObservations . View > remainingO = new ArrayList <> ( ) ; for ( int viewId = 0 ; viewId < structure . views . length ; viewId ++ ) { SceneObservations . View view = observations . views [ viewId ] ; // See if has enough observations to not prune if ( view . size ( ) > count ) { remainingS . add ( structure . views [ viewId ] ) ; remainingO . add ( view ) ; continue ; } // Go through list of points and remove this view from them for ( int pointIdx = 0 ; pointIdx < view . point . size ; pointIdx ++ ) { int pointId = view . getPointId ( pointIdx ) ; int viewIdx = structure . points [ pointId ] . views . indexOf ( viewId ) ; if ( viewIdx < 0 ) throw new RuntimeException ( "Bug in structure. view has point but point doesn't have view" ) ; structure . points [ pointId ] . views . remove ( viewIdx ) ; } } // Create new arrays with the views that were not pruned structure . views = new SceneStructureMetric . View [ remainingS . size ( ) ] ; observations . views = new SceneObservations . View [ remainingO . size ( ) ] ; for ( int i = 0 ; i < structure . views . length ; i ++ ) { structure . views [ i ] = remainingS . get ( i ) ; observations . views [ i ] = remainingO . get ( i ) ; } } | Removes views with less than count features visible . Observations of features in removed views are also removed . | 363 | 21 |
27,789 | public void pruneUnusedCameras ( ) { // Count how many views are used by each camera int histogram [ ] = new int [ structure . cameras . length ] ; for ( int i = 0 ; i < structure . views . length ; i ++ ) { histogram [ structure . views [ i ] . camera ] ++ ; } // See which cameras need to be removed and create a look up table from old to new camera IDs int oldToNew [ ] = new int [ structure . cameras . length ] ; List < SceneStructureMetric . Camera > remaining = new ArrayList <> ( ) ; for ( int i = 0 ; i < structure . cameras . length ; i ++ ) { if ( histogram [ i ] > 0 ) { oldToNew [ i ] = remaining . size ( ) ; remaining . add ( structure . cameras [ i ] ) ; } } // Create the new camera array without the unused cameras structure . cameras = new SceneStructureMetric . Camera [ remaining . size ( ) ] ; for ( int i = 0 ; i < remaining . size ( ) ; i ++ ) { structure . cameras [ i ] = remaining . get ( i ) ; } // Update the references to the cameras for ( int i = 0 ; i < structure . views . length ; i ++ ) { SceneStructureMetric . View v = structure . views [ i ] ; v . camera = oldToNew [ v . camera ] ; } } | Prunes cameras that are not referenced by any views . | 307 | 11 |
27,790 | public void setIntrinsic ( CameraPinholeBrown intrinsic ) { planeProjection . setIntrinsic ( intrinsic ) ; normToPixel = LensDistortionFactory . narrow ( intrinsic ) . distort_F64 ( false , true ) ; pixelToNorm = LensDistortionFactory . narrow ( intrinsic ) . undistort_F64 ( true , false ) ; // Find the change in angle caused by a pixel error in the image center. The same angle error will induce a // larger change in pixel values towards the outside of the image edge. For fish-eyes lenses this could // become significant. Not sure what a better way to handle it would be thresholdFarAngleError = Math . atan2 ( thresholdPixelError , intrinsic . fx ) ; } | Camera the camera s intrinsic parameters . Can be called at any time . | 160 | 14 |
27,791 | public void setExtrinsic ( Se3_F64 planeToCamera ) { this . planeToCamera = planeToCamera ; planeToCamera . invert ( cameraToPlane ) ; planeProjection . setPlaneToCamera ( planeToCamera , true ) ; } | Camera the camera s extrinsic parameters . Can be called at any time . | 59 | 16 |
27,792 | public void reset ( ) { tick = 0 ; first = true ; tracker . reset ( ) ; keyToWorld . reset ( ) ; currToKey . reset ( ) ; currToWorld . reset ( ) ; worldToCurrCam3D . reset ( ) ; } | Resets the algorithm into its initial state | 59 | 8 |
27,793 | private void addNewTracks ( ) { tracker . spawnTracks ( ) ; List < PointTrack > spawned = tracker . getNewTracks ( null ) ; // estimate 3D coordinate using stereo vision for ( PointTrack t : spawned ) { // System.out.println("track spawn "+t.x+" "+t.y); VoTrack p = t . getCookie ( ) ; if ( p == null ) { t . cookie = p = new VoTrack ( ) ; } // compute normalized image coordinate pixelToNorm . compute ( t . x , t . y , n ) ; // System.out.println(" pointing "+pointing.x+" "+pointing.y+" "+pointing.z); // See if the point ever intersects the ground plane or not if ( planeProjection . normalToPlane ( n . x , n . y , p . ground ) ) { // the line above computes the 2D plane position of the point p . onPlane = true ; } else { // Handle points at infinity which are off plane. // rotate observation pointing vector into plane reference frame pointing . set ( n . x , n . y , 1 ) ; GeometryMath_F64 . mult ( cameraToPlane . getR ( ) , pointing , pointing ) ; pointing . normalize ( ) ; // save value of y-axis in pointing vector double normXZ = Math . sqrt ( pointing . x * pointing . x + pointing . z * pointing . z ) ; p . pointingY = pointing . y / normXZ ; // save the angle as a vector p . ground . x = pointing . z ; p . ground . y = - pointing . x ; // normalize to make later calculations easier p . ground . x /= normXZ ; p . ground . y /= normXZ ; p . onPlane = false ; } p . lastInlier = tick ; } } | Requests that new tracks are spawned determines if they are on the plane or not and computes other required data structures . | 408 | 24 |
27,794 | private void sortTracksForEstimation ( ) { // reset data structures planeSamples . reset ( ) ; farAngles . reset ( ) ; tracksOnPlane . clear ( ) ; tracksFar . clear ( ) ; // list of active tracks List < PointTrack > active = tracker . getActiveTracks ( null ) ; for ( PointTrack t : active ) { VoTrack p = t . getCookie ( ) ; // compute normalized image coordinate pixelToNorm . compute ( t . x , t . y , n ) ; // rotate pointing vector into plane reference frame pointing . set ( n . x , n . y , 1 ) ; GeometryMath_F64 . mult ( cameraToPlane . getR ( ) , pointing , pointing ) ; pointing . normalize ( ) ; if ( p . onPlane ) { // see if it still intersects the plane if ( pointing . y > 0 ) { // create data structure for robust motion estimation PlanePtPixel ppp = planeSamples . grow ( ) ; ppp . normalizedCurr . set ( n ) ; ppp . planeKey . set ( p . ground ) ; tracksOnPlane . add ( t ) ; } } else { // if the point is not on the plane visually and (optionally) if it passes a strict y-axis rotation // test, consider using the point for estimating rotation. boolean allGood = pointing . y < 0 ; if ( strictFar ) { allGood = isRotationFromAxisY ( t , pointing ) ; } // is it still above the ground plane and only has motion consistent with rotation on ground plane axis if ( allGood ) { computeAngleOfRotation ( t , pointing ) ; tracksFar . add ( t ) ; } } } } | Splits the set of active tracks into on plane and infinity sets . For each set also perform specific sanity checks to make sure basic constraints are still being meet . If not then the track will not be considered for motion estimation . | 372 | 45 |
27,795 | protected boolean isRotationFromAxisY ( PointTrack t , Vector3D_F64 pointing ) { VoTrack p = t . getCookie ( ) ; // remove rotations not along x-z plane double normXZ = Math . sqrt ( pointing . x * pointing . x + pointing . z * pointing . z ) ; pointingAdj . set ( pointing . x / normXZ , p . pointingY , pointing . z / normXZ ) ; // Put pointing vector back into camera frame GeometryMath_F64 . multTran ( cameraToPlane . getR ( ) , pointingAdj , pointingAdj ) ; // compute normalized image coordinates n . x = pointingAdj . x / pointingAdj . z ; n . y = pointingAdj . y / pointingAdj . z ; // compute pixel of projected point normToPixel . compute ( n . x , n . y , pixel ) ; // compute error double error = pixel . distance2 ( t ) ; return error < thresholdPixelError * thresholdPixelError ; } | Checks for motion which can t be caused by rotations along the y - axis alone . This is done by adjusting the pointing vector in the plane reference frame such that it has the same y component as when the track was spawned and that the x - z components are normalized to one to ensure consistent units . That pointing vector is then projected back into the image and a pixel difference computed . | 224 | 78 |
27,796 | private void computeAngleOfRotation ( PointTrack t , Vector3D_F64 pointingPlane ) { VoTrack p = t . getCookie ( ) ; // Compute ground pointing vector groundCurr . x = pointingPlane . z ; groundCurr . y = - pointingPlane . x ; double norm = groundCurr . norm ( ) ; groundCurr . x /= norm ; groundCurr . y /= norm ; // dot product. vectors are normalized to 1 already double dot = groundCurr . x * p . ground . x + groundCurr . y * p . ground . y ; // floating point round off error some times knocks it above 1.0 if ( dot > 1.0 ) dot = 1.0 ; double angle = Math . acos ( dot ) ; // cross product to figure out direction if ( groundCurr . x * p . ground . y - groundCurr . y * p . ground . x > 0 ) angle = - angle ; farAngles . add ( angle ) ; } | Computes the angle of rotation between two pointing vectors on the ground plane and adds it to a list . | 222 | 21 |
27,797 | private void estimateFar ( ) { // do nothing if there are objects at infinity farInlierCount = 0 ; if ( farAngles . size == 0 ) return ; farAnglesCopy . reset ( ) ; farAnglesCopy . addAll ( farAngles ) ; // find angle which maximizes inlier set farAngle = maximizeCountInSpread ( farAnglesCopy . data , farAngles . size , 2 * thresholdFarAngleError ) ; // mark and count inliers for ( int i = 0 ; i < tracksFar . size ( ) ; i ++ ) { PointTrack t = tracksFar . get ( i ) ; VoTrack p = t . getCookie ( ) ; if ( UtilAngle . dist ( farAngles . get ( i ) , farAngle ) <= thresholdFarAngleError ) { p . lastInlier = tick ; farInlierCount ++ ; } } } | Estimates only rotation using points at infinity . A robust estimation algorithm is used which finds an angle which maximizes the inlier set like RANSAC does . Unlike RANSAC this will produce an optimal result . | 195 | 43 |
27,798 | private void fuseEstimates ( ) { // weighted average for angle double x = closeMotionKeyToCurr . c * closeInlierCount + Math . cos ( farAngle ) * farInlierCount ; double y = closeMotionKeyToCurr . s * closeInlierCount + Math . sin ( farAngle ) * farInlierCount ; // update the motion estimate closeMotionKeyToCurr . setYaw ( Math . atan2 ( y , x ) ) ; // save the results closeMotionKeyToCurr . invert ( currToKey ) ; } | Fuse the estimates for yaw from both sets of points using a weighted vector average and save the results into currToKey | 124 | 26 |
27,799 | public Se3_F64 getWorldToCurr3D ( ) { // compute transform in 2D space Se2_F64 currToWorld = getCurrToWorld2D ( ) ; // 2D to 3D coordinates currPlaneToWorld3D . getT ( ) . set ( - currToWorld . T . y , 0 , currToWorld . T . x ) ; DMatrixRMaj R = currPlaneToWorld3D . getR ( ) ; // set rotation around Y axis. // Transpose the 2D transform since the rotation are pointing in opposite directions R . unsafe_set ( 0 , 0 , currToWorld . c ) ; R . unsafe_set ( 0 , 2 , - currToWorld . s ) ; R . unsafe_set ( 1 , 1 , 1 ) ; R . unsafe_set ( 2 , 0 , currToWorld . s ) ; R . unsafe_set ( 2 , 2 , currToWorld . c ) ; currPlaneToWorld3D . invert ( worldToCurrPlane3D ) ; worldToCurrPlane3D . concat ( planeToCamera , worldToCurrCam3D ) ; return worldToCurrCam3D ; } | Converts 2D motion estimate into a 3D motion estimate | 274 | 12 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.