idx int64 0 41.2k | question stringlengths 74 4.04k | target stringlengths 7 750 |
|---|---|---|
26,500 | Double truncate ( Number numberValue ) { double doubleValue = numberValue . doubleValue ( ) ; if ( truncateEnabled ) { final int exponent = Math . getExponent ( doubleValue ) ; if ( Double . isNaN ( doubleValue ) ) { doubleValue = 0.0 ; } else if ( exponent >= MAX_EXPONENT ) { doubleValue = ( doubleValue < 0.0 ) ? - MAX_VALUE : MAX_VALUE ; } else if ( exponent <= MIN_EXPONENT ) { doubleValue = 0.0 ; } } return doubleValue ; } | Adjust a double value so it can be successfully written to cloudwatch . This involves capping values with large exponents to an experimentally determined max value and converting values with large negative exponents to 0 . In addition NaN values will be converted to 0 . |
26,501 | public static Metric toValidValue ( Metric metric ) { MonitorConfig cfg = metric . getConfig ( ) ; MonitorConfig . Builder cfgBuilder = MonitorConfig . builder ( toValidCharset ( cfg . getName ( ) ) ) ; for ( Tag orig : cfg . getTags ( ) ) { final String key = orig . getKey ( ) ; if ( RELAXED_GROUP_KEYS . contains ( key ) ) { cfgBuilder . withTag ( key , toValidCharsetTable ( CHARS_ALLOWED_GROUPS , orig . getValue ( ) ) ) ; } else { cfgBuilder . withTag ( toValidCharset ( key ) , toValidCharset ( orig . getValue ( ) ) ) ; } } cfgBuilder . withPublishingPolicy ( cfg . getPublishingPolicy ( ) ) ; return new Metric ( cfgBuilder . build ( ) , metric . getTimestamp ( ) , metric . getValue ( ) ) ; } | Return a new metric where the name and all tags are using the valid character set . |
26,502 | public static List < Metric > toValidValues ( List < Metric > metrics ) { return metrics . stream ( ) . map ( ValidCharacters :: toValidValue ) . collect ( Collectors . toList ( ) ) ; } | Create a new list of metrics where all metrics are using the valid character set . |
26,503 | public static void tagToJson ( JsonGenerator gen , Tag tag ) throws IOException { final String key = tag . getKey ( ) ; if ( RELAXED_GROUP_KEYS . contains ( key ) ) { gen . writeStringField ( key , toValidCharsetTable ( CHARS_ALLOWED_GROUPS , tag . getValue ( ) ) ) ; } else { gen . writeStringField ( toValidCharset ( tag . getKey ( ) ) , toValidCharset ( tag . getValue ( ) ) ) ; } } | Serialize a tag to the given JsonGenerator . |
26,504 | public void record ( long measurement ) { lastUsed = clock . now ( ) ; if ( isExpired ( ) ) { LOGGER . info ( "Attempting to get the value for an expired monitor: {}." + "Will start computing stats again." , getConfig ( ) . getName ( ) ) ; startComputingStats ( executor , statsConfig . getFrequencyMillis ( ) ) ; } synchronized ( updateLock ) { cur . record ( measurement ) ; } count . increment ( ) ; totalMeasurement . increment ( measurement ) ; } | Record the measurement we want to perform statistics on . |
26,505 | public Long getValue ( int pollerIndex ) { final long n = getCount ( pollerIndex ) ; return n > 0 ? totalMeasurement . getValue ( pollerIndex ) . longValue ( ) / n : 0L ; } | Get the value of the measurement . |
26,506 | public List < V > values ( ) { final Collection < Entry < V > > values = map . values ( ) ; final List < V > res = values . stream ( ) . map ( e -> e . value ) . collect ( Collectors . toList ( ) ) ; return Collections . unmodifiableList ( res ) ; } | Get the list of all values that are members of this cache . Does not affect the access time used for eviction . |
26,507 | public void addPoller ( PollRunnable task , long delay , TimeUnit timeUnit ) { ScheduledExecutorService service = executor . get ( ) ; if ( service != null ) { service . scheduleWithFixedDelay ( task , 0 , delay , timeUnit ) ; } else { throw new IllegalStateException ( "you must start the scheduler before tasks can be submitted" ) ; } } | Add a tasks to execute at a fixed rate based on the provided delay . |
26,508 | public void start ( ) { int numThreads = Runtime . getRuntime ( ) . availableProcessors ( ) ; ThreadFactory factory = ThreadFactories . withName ( "ServoPollScheduler-%d" ) ; start ( Executors . newScheduledThreadPool ( numThreads , factory ) ) ; } | Start scheduling tasks with a default thread pool sized based on the number of available processors . |
26,509 | public void stop ( ) { ScheduledExecutorService service = executor . get ( ) ; if ( service != null && executor . compareAndSet ( service , null ) ) { service . shutdown ( ) ; } else { throw new IllegalStateException ( "scheduler must be started before you stop it" ) ; } } | Stop the poller shutting down the current executor service . |
26,510 | public static String join ( String separator , Iterator < ? > parts ) { Preconditions . checkNotNull ( separator , "separator" ) ; Preconditions . checkNotNull ( parts , "parts" ) ; StringBuilder builder = new StringBuilder ( ) ; if ( parts . hasNext ( ) ) { builder . append ( parts . next ( ) . toString ( ) ) ; while ( parts . hasNext ( ) ) { builder . append ( separator ) ; builder . append ( parts . next ( ) . toString ( ) ) ; } } return builder . toString ( ) ; } | Join the string representation of each part separated by the given separator string . |
26,511 | public static < T > T checkNotNull ( T obj , String name ) { if ( obj == null ) { String msg = String . format ( "parameter '%s' cannot be null" , name ) ; throw new NullPointerException ( msg ) ; } return obj ; } | Ensures the object reference is not null . |
26,512 | public void update ( long v ) { for ( int i = 0 ; i < Pollers . NUM_POLLERS ; ++ i ) { updateMin ( i , v ) ; } } | Update the min if the provided value is smaller than the current min . |
26,513 | public long getCurrentValue ( int nth ) { long v = min . getCurrent ( nth ) . get ( ) ; return ( v == Long . MAX_VALUE ) ? 0L : v ; } | Returns the current min value since the last reset . |
26,514 | public List < List < Metric > > getObservations ( ) { List < List < Metric > > builder = new ArrayList < > ( ) ; int pos = next ; for ( List < Metric > ignored : observations ) { if ( observations [ pos ] != null ) { builder . add ( observations [ pos ] ) ; } pos = ( pos + 1 ) % observations . length ; } return Collections . unmodifiableList ( builder ) ; } | Returns the current set of observations . |
26,515 | private MonitorConfig . Builder copy ( ) { return MonitorConfig . builder ( name ) . withTags ( tags ) . withPublishingPolicy ( policy ) ; } | Returns a copy of the current MonitorConfig . |
26,516 | public void update ( long v ) { spectatorGauge . set ( v ) ; for ( int i = 0 ; i < Pollers . NUM_POLLERS ; ++ i ) { updateMax ( i , v ) ; } } | Update the max if the provided value is larger than the current max . |
26,517 | public int sendAll ( Iterable < Observable < Integer > > batches , final int numMetrics , long timeoutMillis ) { final AtomicBoolean err = new AtomicBoolean ( false ) ; final AtomicInteger updated = new AtomicInteger ( 0 ) ; LOGGER . debug ( "Got {} ms to send {} metrics" , timeoutMillis , numMetrics ) ; try { final CountDownLatch completed = new CountDownLatch ( 1 ) ; final Subscription s = Observable . mergeDelayError ( Observable . from ( batches ) ) . timeout ( timeoutMillis , TimeUnit . MILLISECONDS ) . subscribeOn ( Schedulers . immediate ( ) ) . subscribe ( updated :: addAndGet , exc -> { logErr ( "onError caught" , exc , updated . get ( ) , numMetrics ) ; err . set ( true ) ; completed . countDown ( ) ; } , completed :: countDown ) ; try { completed . await ( timeoutMillis , TimeUnit . MILLISECONDS ) ; } catch ( InterruptedException interrupted ) { err . set ( true ) ; s . unsubscribe ( ) ; LOGGER . warn ( "Timed out sending metrics. {}/{} sent" , updated . get ( ) , numMetrics ) ; } } catch ( Exception e ) { err . set ( true ) ; logErr ( "Unexpected " , e , updated . get ( ) , numMetrics ) ; } if ( updated . get ( ) < numMetrics && ! err . get ( ) ) { LOGGER . warn ( "No error caught, but only {}/{} sent." , updated . get ( ) , numMetrics ) ; } return updated . get ( ) ; } | Attempt to send all the batches totalling numMetrics in the allowed time . |
26,518 | public Response get ( HttpClientRequest < ByteBuf > req , long timeout , TimeUnit timeUnit ) { final String uri = req . getUri ( ) ; final Response result = new Response ( ) ; try { final Func1 < HttpClientResponse < ByteBuf > , Observable < byte [ ] > > process = response -> { result . status = response . getStatus ( ) . code ( ) ; result . headers = response . getHeaders ( ) ; final Func2 < ByteArrayOutputStream , ByteBuf , ByteArrayOutputStream > accumulator = ( baos , bb ) -> { try { bb . readBytes ( baos , bb . readableBytes ( ) ) ; } catch ( IOException e ) { throw new RuntimeException ( e ) ; } return baos ; } ; return response . getContent ( ) . reduce ( new ByteArrayOutputStream ( ) , accumulator ) . map ( ByteArrayOutputStream :: toByteArray ) ; } ; result . body = rxHttp . submit ( req ) . flatMap ( process ) . subscribeOn ( Schedulers . io ( ) ) . toBlocking ( ) . toFuture ( ) . get ( timeout , timeUnit ) ; return result ; } catch ( Exception e ) { throw new RuntimeException ( "failed to get url: " + uri , e ) ; } } | Perform an HTTP get in the allowed time . |
26,519 | public static void increment ( String name , TagList list ) { final MonitorConfig config = new MonitorConfig . Builder ( name ) . withTags ( list ) . build ( ) ; increment ( config ) ; } | Increment the counter for a given name tagList . |
26,520 | public static void increment ( String name , TagList list , long delta ) { final MonitorConfig config = MonitorConfig . builder ( name ) . withTags ( list ) . build ( ) ; increment ( config , delta ) ; } | Increment the counter for a given name tagList by a given delta . |
26,521 | public Collection < Monitor < ? > > getRegisteredMonitors ( ) { if ( updatePending . getAndSet ( false ) ) { monitorList . set ( UnmodifiableList . copyOf ( monitors . values ( ) ) ) ; } return monitorList . get ( ) ; } | The set of registered Monitor objects . |
26,522 | public void set ( Long n ) { spectatorGauge . set ( n ) ; AtomicLong number = getNumber ( ) ; number . set ( n ) ; } | Set the current value . |
26,523 | public Long getCount ( int pollerIndex ) { long updates = 0 ; for ( Counter c : bucketCount ) { updates += c . getValue ( pollerIndex ) . longValue ( ) ; } updates += overflowCount . getValue ( pollerIndex ) . longValue ( ) ; return updates ; } | Get the total number of updates . |
26,524 | private TagList createTagList ( ObjectName name ) { Map < String , String > props = name . getKeyPropertyList ( ) ; SmallTagMap . Builder tagsBuilder = SmallTagMap . builder ( ) ; for ( Map . Entry < String , String > e : props . entrySet ( ) ) { String key = PROP_KEY_PREFIX + "." + e . getKey ( ) ; tagsBuilder . add ( Tags . newTag ( key , e . getValue ( ) ) ) ; } tagsBuilder . add ( Tags . newTag ( DOMAIN_KEY , name . getDomain ( ) ) ) ; tagsBuilder . add ( CLASS_TAG ) ; if ( defaultTags != null ) { defaultTags . forEach ( tagsBuilder :: add ) ; } return new BasicTagList ( tagsBuilder . result ( ) ) ; } | Creates a tag list from an object name . |
26,525 | private void addMetric ( List < Metric > metrics , String name , TagList tags , Object value ) { long now = System . currentTimeMillis ( ) ; if ( onlyNumericMetrics ) { value = asNumber ( value ) ; } if ( value != null ) { TagList newTags = counters . matches ( MonitorConfig . builder ( name ) . withTags ( tags ) . build ( ) ) ? getTagListWithAdditionalTag ( tags , DataSourceType . COUNTER ) : getTagListWithAdditionalTag ( tags , DataSourceType . GAUGE ) ; Metric m = new Metric ( name , newTags , now , value ) ; metrics . add ( m ) ; } } | Create a new metric object and add it to the list . |
26,526 | private static Number asNumber ( Object value ) { Number num = null ; if ( value == null ) { num = null ; } else if ( value instanceof Number ) { num = ( Number ) value ; } else if ( value instanceof Boolean ) { num = ( ( Boolean ) value ) ? 1 : 0 ; } return num ; } | Try to convert an object into a number . Boolean values will return 1 if true and 0 if false . If the value is null or an unknown data type null will be returned . |
26,527 | public static void set ( String name , double value ) { set ( MonitorConfig . builder ( name ) . build ( ) , value ) ; } | Increment a gauge specified by a name . |
26,528 | public static void set ( String name , TagList list , double value ) { final MonitorConfig config = MonitorConfig . builder ( name ) . withTags ( list ) . build ( ) ; set ( config , value ) ; } | Set the gauge for a given name tagList by a given value . |
26,529 | private static String join ( long [ ] a ) { assert ( a . length > 0 ) ; StringBuilder builder = new StringBuilder ( ) ; builder . append ( a [ 0 ] ) ; for ( int i = 1 ; i < a . length ; ++ i ) { builder . append ( ',' ) ; builder . append ( a [ i ] ) ; } return builder . toString ( ) ; } | For debugging . Simple toString for non - empty arrays |
26,530 | static long [ ] parse ( String pollers ) { String [ ] periods = pollers . split ( ",\\s*" ) ; long [ ] result = new long [ periods . length ] ; boolean errors = false ; Logger logger = LoggerFactory . getLogger ( Pollers . class ) ; for ( int i = 0 ; i < periods . length ; ++ i ) { String period = periods [ i ] ; try { result [ i ] = Long . parseLong ( period ) ; if ( result [ i ] <= 0 ) { logger . error ( "Invalid polling interval: {} must be positive." , period ) ; errors = true ; } } catch ( NumberFormatException e ) { logger . error ( "Cannot parse '{}' as a long: {}" , period , e . getMessage ( ) ) ; errors = true ; } } if ( errors || periods . length == 0 ) { logger . info ( "Using a default configuration for poller intervals: {}" , join ( DEFAULT_PERIODS ) ) ; return DEFAULT_PERIODS ; } else { return result ; } } | Parse the content of the system property that describes the polling intervals and in case of errors use the default of one poller running every minute . |
26,531 | private List < Container > filterByVolumeAndWeight ( List < Box > boxes , List < Container > containers , int count ) { long volume = 0 ; long minVolume = Long . MAX_VALUE ; long weight = 0 ; long minWeight = Long . MAX_VALUE ; for ( Box box : boxes ) { long boxVolume = box . getVolume ( ) ; volume += boxVolume ; if ( boxVolume < minVolume ) { minVolume = boxVolume ; } long boxWeight = box . getWeight ( ) ; weight += boxWeight ; if ( boxWeight < minWeight ) { minWeight = boxWeight ; } } long maxVolume = Long . MIN_VALUE ; long maxWeight = Long . MIN_VALUE ; for ( Container container : containers ) { long boxVolume = container . getVolume ( ) ; if ( boxVolume > maxVolume ) { maxVolume = boxVolume ; } long boxWeight = container . getWeight ( ) ; if ( boxWeight > maxWeight ) { maxWeight = boxWeight ; } } if ( maxVolume * count < volume || maxWeight * count < weight ) { return Collections . emptyList ( ) ; } List < Container > list = new ArrayList < > ( containers . size ( ) ) ; for ( Container container : containers ) { if ( container . getVolume ( ) < minVolume || container . getWeight ( ) < minWeight ) { continue ; } if ( container . getVolume ( ) + maxVolume * ( count - 1 ) < volume || container . getWeight ( ) + maxWeight * ( count - 1 ) < weight ) { continue ; } if ( count == 1 ) { if ( ! canHoldAll ( container , boxes ) ) { continue ; } } else { if ( ! canHoldAtLeastOne ( container , boxes ) ) { continue ; } } list . add ( container ) ; } return list ; } | Return a list of containers which can potentially hold the boxes . |
26,532 | public Box rotate3D ( ) { int height = this . height ; this . height = width ; this . width = depth ; this . depth = height ; return this ; } | Rotate box i . e . in 3D |
26,533 | boolean fitRotate2D ( Dimension dimension ) { if ( dimension . getHeight ( ) < height ) { return false ; } return fitRotate2D ( dimension . getWidth ( ) , dimension . getDepth ( ) ) ; } | Rotate box within a free space in 2D |
26,534 | protected boolean fit2D ( List < Box > containerProducts , Container holder , Box usedSpace , Space freeSpace , BooleanSupplier interrupt ) { if ( rotate3D ) { usedSpace . fitRotate3DSmallestFootprint ( freeSpace ) ; } holder . add ( new Placement ( freeSpace , usedSpace ) ) ; if ( containerProducts . isEmpty ( ) ) { usedSpace . fitRotate2D ( freeSpace ) ; return true ; } if ( interrupt . getAsBoolean ( ) ) { return false ; } Space [ ] spaces = getFreespaces ( freeSpace , usedSpace ) ; Placement nextPlacement = getBestBoxAndSpace ( containerProducts , spaces , holder . getFreeWeight ( ) ) ; if ( nextPlacement == null ) { usedSpace . fitRotate2D ( freeSpace ) ; } else { if ( nextPlacement . getSpace ( ) == spaces [ 2 ] || nextPlacement . getSpace ( ) == spaces [ 3 ] ) { usedSpace . rotate2D ( ) ; } removeIdentical ( containerProducts , nextPlacement . getBox ( ) ) ; Space remainder = nextPlacement . getSpace ( ) . getRemainder ( ) ; if ( remainder . nonEmpty ( ) ) { Box box = getBestBoxForSpace ( containerProducts , remainder , holder . getFreeWeight ( ) ) ; if ( box != null ) { removeIdentical ( containerProducts , box ) ; if ( ! fit2D ( containerProducts , holder , box , remainder , interrupt ) ) { return false ; } } } if ( holder . getFreeWeight ( ) >= nextPlacement . getBox ( ) . getWeight ( ) ) { if ( ! fit2D ( containerProducts , holder , nextPlacement . getBox ( ) , nextPlacement . getSpace ( ) , interrupt ) ) { return false ; } } } if ( freeSpace . getHeight ( ) > usedSpace . getHeight ( ) ) { Space above ; if ( nextPlacement == null ) { above = new Space ( freeSpace . getWidth ( ) , freeSpace . getDepth ( ) , freeSpace . getHeight ( ) - usedSpace . getHeight ( ) , freeSpace . getX ( ) , freeSpace . getY ( ) , freeSpace . getZ ( ) + usedSpace . getHeight ( ) ) ; } else { above = new Space ( usedSpace . getWidth ( ) , usedSpace . getDepth ( ) , freeSpace . getHeight ( ) - usedSpace . getHeight ( ) , freeSpace . getX ( ) , freeSpace . getY ( ) , freeSpace . getZ ( ) + usedSpace . getHeight ( ) ) ; } int currentIndex = getBestBox ( holder , above , containerProducts ) ; if ( currentIndex != - 1 ) { Box currentBox = containerProducts . get ( currentIndex ) ; containerProducts . remove ( currentIndex ) ; if ( ! fit2D ( containerProducts , holder , currentBox , above , interrupt ) ) { return false ; } } } return true ; } | Fit in two dimensions |
26,535 | protected int isBetter2D ( Box a , Box b ) { int compare = Long . compare ( a . getVolume ( ) , b . getVolume ( ) ) ; if ( compare != 0 ) { return compare ; } return Long . compare ( b . getFootprint ( ) , a . getFootprint ( ) ) ; } | Is box b better than a? |
26,536 | protected int isBetter3D ( Box a , Box b , Space space ) { int compare = Long . compare ( a . getVolume ( ) , b . getVolume ( ) ) ; if ( compare != 0 ) { return compare ; } a . fitRotate3DSmallestFootprint ( space ) ; b . fitRotate3DSmallestFootprint ( space ) ; return Long . compare ( b . getFootprint ( ) , a . getFootprint ( ) ) ; } | Is box b strictly better than a? |
26,537 | public void removePermutations ( List < Integer > removed ) { int [ ] permutations = new int [ this . permutations . length ] ; int index = 0 ; permutations : for ( int j : this . permutations ) { for ( int i = 0 ; i < removed . size ( ) ; i ++ ) { if ( removed . get ( i ) == j ) { removed . remove ( i ) ; continue permutations ; } } permutations [ index ] = j ; index ++ ; } int [ ] effectivePermutations = new int [ index ] ; System . arraycopy ( permutations , 0 , effectivePermutations , 0 , index ) ; this . rotations = new int [ permutations . length ] ; this . reset = new int [ permutations . length ] ; this . permutations = effectivePermutations ; Arrays . sort ( permutations ) ; } | Remove permutations if present . |
26,538 | public Dimension getFreeLevelSpace ( ) { int remainder = height - getStackHeight ( ) ; if ( remainder < 0 ) { throw new IllegalArgumentException ( "Remaining free space is negative at " + remainder + " for " + this ) ; } return new Dimension ( width , depth , remainder ) ; } | Get the free level space i . e . container height with height of levels subtracted . |
26,539 | public void process ( List < Point3D_F64 > worldPts , List < Point2D_F64 > observed , Se3_F64 solutionModel ) { if ( worldPts . size ( ) < 4 ) throw new IllegalArgumentException ( "Must provide at least 4 points" ) ; if ( worldPts . size ( ) != observed . size ( ) ) throw new IllegalArgumentException ( "Must have the same number of observations and world points" ) ; selectWorldControlPoints ( worldPts , controlWorldPts ) ; computeBarycentricCoordinates ( controlWorldPts , alphas , worldPts ) ; constructM ( observed , alphas , M ) ; extractNullPoints ( M ) ; if ( numControl == 4 ) { L_full . reshape ( 6 , 10 ) ; y . reshape ( 6 , 1 ) ; UtilLepetitEPnP . constraintMatrix6x10 ( L_full , y , controlWorldPts , nullPts ) ; estimateCase1 ( solutions . get ( 0 ) ) ; estimateCase2 ( solutions . get ( 1 ) ) ; estimateCase3 ( solutions . get ( 2 ) ) ; if ( worldPts . size ( ) == 4 ) estimateCase4 ( solutions . get ( 3 ) ) ; } else { L_full . reshape ( 3 , 6 ) ; y . reshape ( 3 , 1 ) ; UtilLepetitEPnP . constraintMatrix3x6 ( L_full , y , controlWorldPts , nullPts ) ; estimateCase1 ( solutions . get ( 0 ) ) ; estimateCase2 ( solutions . get ( 1 ) ) ; if ( worldPts . size ( ) == 3 ) estimateCase3_planar ( solutions . get ( 2 ) ) ; } computeResultFromBest ( solutionModel ) ; } | Compute camera motion given a set of features with observations and 3D locations |
26,540 | private void computeResultFromBest ( Se3_F64 solutionModel ) { double bestScore = Double . MAX_VALUE ; int bestSolution = - 1 ; for ( int i = 0 ; i < numControl ; i ++ ) { double score = score ( solutions . get ( i ) ) ; if ( score < bestScore ) { bestScore = score ; bestSolution = i ; } } double [ ] solution = solutions . get ( bestSolution ) ; if ( numIterations > 0 ) { gaussNewton ( solution ) ; } UtilLepetitEPnP . computeCameraControl ( solution , nullPts , solutionPts , numControl ) ; motionFit . process ( controlWorldPts . toList ( ) , solutionPts . toList ( ) ) ; solutionModel . set ( motionFit . getTransformSrcToDst ( ) ) ; } | Selects the best motion hypothesis based on the actual observations and optionally optimizes the solution . |
26,541 | private double score ( double betas [ ] ) { UtilLepetitEPnP . computeCameraControl ( betas , nullPts , solutionPts , numControl ) ; int index = 0 ; double score = 0 ; for ( int i = 0 ; i < numControl ; i ++ ) { Point3D_F64 si = solutionPts . get ( i ) ; Point3D_F64 wi = controlWorldPts . get ( i ) ; for ( int j = i + 1 ; j < numControl ; j ++ , index ++ ) { double ds = si . distance ( solutionPts . get ( j ) ) ; double dw = wi . distance ( controlWorldPts . get ( j ) ) ; score += ( ds - dw ) * ( ds - dw ) ; } } return score ; } | Score a solution based on distance between control points . Closer the camera control points are from the world control points the better the score . This is similar to how optimization score works and not the way recommended in the original paper . |
26,542 | public void selectWorldControlPoints ( List < Point3D_F64 > worldPts , FastQueue < Point3D_F64 > controlWorldPts ) { UtilPoint3D_F64 . mean ( worldPts , meanWorldPts ) ; double c11 = 0 , c12 = 0 , c13 = 0 , c22 = 0 , c23 = 0 , c33 = 0 ; final int N = worldPts . size ( ) ; for ( int i = 0 ; i < N ; i ++ ) { Point3D_F64 p = worldPts . get ( i ) ; double dx = p . x - meanWorldPts . x ; double dy = p . y - meanWorldPts . y ; double dz = p . z - meanWorldPts . z ; c11 += dx * dx ; c12 += dx * dy ; c13 += dx * dz ; c22 += dy * dy ; c23 += dy * dz ; c33 += dz * dz ; } c11 /= N ; c12 /= N ; c13 /= N ; c22 /= N ; c23 /= N ; c33 /= N ; DMatrixRMaj covar = new DMatrixRMaj ( 3 , 3 , true , c11 , c12 , c13 , c12 , c22 , c23 , c13 , c23 , c33 ) ; svd . decompose ( covar ) ; double [ ] singularValues = svd . getSingularValues ( ) ; DMatrixRMaj V = svd . getV ( null , false ) ; SingularOps_DDRM . descendingOrder ( null , false , singularValues , 3 , V , false ) ; if ( singularValues [ 0 ] < singularValues [ 2 ] * 1e13 ) { numControl = 4 ; } else { numControl = 3 ; } controlWorldPts . reset ( ) ; for ( int i = 0 ; i < numControl - 1 ; i ++ ) { double m = Math . sqrt ( singularValues [ 1 ] ) * magicNumber ; double vx = V . unsafe_get ( 0 , i ) * m ; double vy = V . unsafe_get ( 1 , i ) * m ; double vz = V . unsafe_get ( 2 , i ) * m ; controlWorldPts . grow ( ) . set ( meanWorldPts . x + vx , meanWorldPts . y + vy , meanWorldPts . z + vz ) ; } controlWorldPts . grow ( ) . set ( meanWorldPts . x , meanWorldPts . y , meanWorldPts . z ) ; } | Selects control points along the data s axis and the data s centroid . If the data is determined to be planar then only 3 control points are selected . |
26,543 | protected static void constructM ( List < Point2D_F64 > obsPts , DMatrixRMaj alphas , DMatrixRMaj M ) { int N = obsPts . size ( ) ; M . reshape ( 3 * alphas . numCols , 2 * N , false ) ; for ( int i = 0 ; i < N ; i ++ ) { Point2D_F64 p2 = obsPts . get ( i ) ; int row = i * 2 ; for ( int j = 0 ; j < alphas . numCols ; j ++ ) { int col = j * 3 ; double alpha = alphas . unsafe_get ( i , j ) ; M . unsafe_set ( col , row , alpha ) ; M . unsafe_set ( col + 1 , row , 0 ) ; M . unsafe_set ( col + 2 , row , - alpha * p2 . x ) ; M . unsafe_set ( col , row + 1 , 0 ) ; M . unsafe_set ( col + 1 , row + 1 , alpha ) ; M . unsafe_set ( col + 2 , row + 1 , - alpha * p2 . y ) ; } } } | Constructs the linear system which is to be solved . |
26,544 | 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 ) ; 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 ; } 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 . |
26,545 | 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 |
26,546 | 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 . |
26,547 | 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 |
26,548 | private void gaussNewton ( double betas [ ] ) { A_temp . reshape ( L_full . numRows , numControl ) ; v_temp . reshape ( L_full . numRows , 1 ) ; x . reshape ( numControl , 1 , false ) ; 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 . |
26,549 | public QrCodeEncoder addAutomatic ( String message ) { if ( containsKanji ( message ) ) { 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 . |
26,550 | 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 |
26,551 | 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 . |
26,552 | 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 |
26,553 | 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 |
26,554 | public QrCode fixate ( ) { autoSelectVersionAndError ( ) ; 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 ) { 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 |
26,555 | 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" ) ; 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 . |
26,556 | 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 ) ; } 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 |
26,557 | 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 |
26,558 | public boolean process ( DMatrixRMaj F21 , double x1 , double y1 , double x2 , double y2 , Point2D_F64 p1 , Point2D_F64 p2 ) { assignTinv ( T1 , x1 , y1 ) ; assignTinv ( T2 , x2 , y2 ) ; PerspectiveOps . multTranA ( T2 , F21 , T1 , Ft ) ; extract . process ( Ft , e1 , e2 ) ; normalizeEpipole ( e1 ) ; normalizeEpipole ( e2 ) ; assignR ( R1 , e1 ) ; assignR ( R2 , e2 ) ; 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 ; double t = solutionT ; l1 . set ( t * f1 , 1 , - t ) ; l2 . set ( - f2 * ( c * t + d ) , a * t + b , c * t + d ) ; closestPointToOrigin ( l1 , e1 ) ; closestPointToOrigin ( l2 , e2 ) ; originalCoordinates ( T1 , R1 , e1 ) ; originalCoordinates ( T2 , R2 , e2 ) ; 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 |
26,559 | 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 |
26,560 | 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 ) ; } } | Computes Laplacian on an U8 image but outputs derivative in a F32 image . Removes a step when processing images for feature detection |
26,561 | 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 . |
26,562 | 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 |
26,563 | protected void processCluster ( List < SquareNode > cluster ) { invalid = false ; 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 ; 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 ; List < List < SquareNode > > listRows = new ArrayList < > ( ) ; 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 ; SquareGrid grid = assembleGrid ( listRows ) ; if ( grid == null || ! checkEdgeCount ( grid ) ) { grids . removeTail ( ) ; } } | Converts the cluster into a grid data structure . If its not a grid then nothing happens |
26,564 | 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 ( ) ; for ( int i = 0 ; i < grid . columns * grid . rows ; i ++ ) { grid . nodes . add ( null ) ; } for ( int row = 0 ; row < listRows . size ( ) ; row ++ ) { List < SquareNode > list = listRows . get ( row ) ; int startCol = offset - row % 2 == 0 ? 0 : 1 ; 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 . |
26,565 | 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 |
26,566 | 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 ; 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 { 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 |
26,567 | 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 |
26,568 | 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 . |
26,569 | 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 . |
26,570 | 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 ) { 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 . |
26,571 | 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 . |
26,572 | public void process ( GrayF32 input ) { borderImg . setImage ( input ) ; gradient . process ( input , derivX , derivY ) ; interpX . setImage ( derivX ) ; interpY . setImage ( derivY ) ; cornerIntensity . process ( derivX , derivY , intensity ) ; intensityInterp . setImage ( intensity ) ; float featmax = ImageStatistics . max ( intensity ) ; PixelMath . multiply ( intensity , GRAY_LEVELS / featmax , intensity ) ; inputToBinary . process ( intensity , binary ) ; contourFinder . process ( binary ) ; corners . reset ( ) ; List < ContourPacked > packed = contourFinder . getContours ( ) ; for ( int i = 0 ; i < packed . size ( ) ; i ++ ) { contourFinder . loadContour ( i , contour ) ; ChessboardCorner c = corners . grow ( ) ; UtilPoint2D_I32 . mean ( contour . toList ( ) , c ) ; c . x += 0.5 ; c . y += 0.5 ; computeFeatures ( c . x , c . y , c ) ; if ( c . intensity < cornerIntensityThreshold ) { corners . removeTail ( ) ; } else if ( useMeanShift ) { meanShiftLocation ( c ) ; computeFeatures ( c . x , c . y , c ) ; } } } | Computes chessboard corners inside the image |
26,573 | public void meanShiftLocation ( ChessboardCorner c ) { float meanX = ( float ) c . x ; float meanY = ( float ) c . y ; 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 ) ; 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 . |
26,574 | 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 . |
26,575 | protected int selectResolution ( int widthTexture , int heightTexture , Size [ ] resolutions ) { timeOfLastUpdated = 0 ; 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 |
26,576 | 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 |
26,577 | 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 : { if ( image . getWidth ( ) == bitmapWork . getWidth ( ) && image . getHeight ( ) == bitmapWork . getHeight ( ) ) ConvertBitmap . boofToBitmap ( image , bitmapWork , bitmapTmp ) ; 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 . |
26,578 | protected void onDrawFrame ( SurfaceView view , Canvas canvas ) { 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 |
26,579 | 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 . |
26,580 | 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 . |
26,581 | 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 . |
26,582 | 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 ] ; 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 . |
26,583 | 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 ++ ) { 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 ; inten [ destIndex ] = this . intensity . compute ( totalXX , totalXY , totalYY ) ; destIndex += imgWidth ; } 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 |
26,584 | 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 . |
26,585 | 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 . |
26,586 | 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 . |
26,587 | 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 . |
26,588 | public boolean update ( Image input , RectangleRotate_F64 output ) { if ( trackLost ) return false ; trackFeatures ( input , region ) ; if ( pairs . size ( ) < config . numberOfSamples ) { System . out . println ( "Lack of sample pairs" ) ; trackLost = true ; return false ; } 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 ; } 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 ) ; swapImages ( ) ; return true ; } | Given the input image compute the new location of the target region and store the results in output . |
26,589 | 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 ] ) ; } 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 . 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 ; 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 ; } 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 . |
26,590 | 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 |
26,591 | 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 . |
26,592 | 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 |
26,593 | public boolean process ( EllipseRotated_F64 ellipse ) { 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 ; double ct = Math . cos ( theta ) ; double st = Math . sin ( theta ) ; 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 ; 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 ; double dx = edx * cphi - edy * sphi ; double dy = edx * sphi + edy * cphi ; 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 |
26,594 | 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 |
26,595 | 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 |
26,596 | 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 |
26,597 | 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 ) ; 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 ) ; } if ( backwardsValidation ) { for ( int i = 0 ; i < src . size ; i ++ ) { int match = pairs . data [ i ] ; if ( match == - 1 ) 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 ; } } } } } | Associates the two sets objects against each other by minimizing fit score . |
26,598 | public boolean process ( T image , QrCode qr ) { this . qr = qr ; qr . alignment . reset ( ) ; reader . setImage ( image ) ; reader . setMarker ( qr ) ; threshold = ( float ) qr . threshCorner ; initializePatterns ( qr ) ; 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 |
26,599 | 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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.