repo stringlengths 7 58 | path stringlengths 12 218 | func_name stringlengths 3 140 | original_string stringlengths 73 34.1k | language stringclasses 1
value | code stringlengths 73 34.1k | code_tokens list | docstring stringlengths 3 16k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 105 339 | partition stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|
Netflix/servo | servo-aws/src/main/java/com/netflix/servo/publish/cloudwatch/CloudWatchMetricObserver.java | CloudWatchMetricObserver.truncate | Double truncate(Number numberValue) {
// http://docs.amazonwebservices.com/AmazonCloudWatch/latest/APIReference/API_MetricDatum.html
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;
} | java | Double truncate(Number numberValue) {
// http://docs.amazonwebservices.com/AmazonCloudWatch/latest/APIReference/API_MetricDatum.html
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;
} | [
"Double",
"truncate",
"(",
"Number",
"numberValue",
")",
"{",
"// http://docs.amazonwebservices.com/AmazonCloudWatch/latest/APIReference/API_MetricDatum.html",
"double",
"doubleValue",
"=",
"numberValue",
".",
"doubleValue",
"(",
")",
";",
"if",
"(",
"truncateEnabled",
")",
... | 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. | [
"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",... | d67b5afce8c50bd9e9e31c288dbf4b78fb2ac815 | https://github.com/Netflix/servo/blob/d67b5afce8c50bd9e9e31c288dbf4b78fb2ac815/servo-aws/src/main/java/com/netflix/servo/publish/cloudwatch/CloudWatchMetricObserver.java#L247-L261 | train |
Netflix/servo | servo-atlas/src/main/java/com/netflix/servo/publish/atlas/ValidCharacters.java | ValidCharacters.toValidValue | 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());
} | java | 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());
} | [
"public",
"static",
"Metric",
"toValidValue",
"(",
"Metric",
"metric",
")",
"{",
"MonitorConfig",
"cfg",
"=",
"metric",
".",
"getConfig",
"(",
")",
";",
"MonitorConfig",
".",
"Builder",
"cfgBuilder",
"=",
"MonitorConfig",
".",
"builder",
"(",
"toValidCharset",
... | Return a new metric where the name and all tags are using the valid character
set. | [
"Return",
"a",
"new",
"metric",
"where",
"the",
"name",
"and",
"all",
"tags",
"are",
"using",
"the",
"valid",
"character",
"set",
"."
] | d67b5afce8c50bd9e9e31c288dbf4b78fb2ac815 | https://github.com/Netflix/servo/blob/d67b5afce8c50bd9e9e31c288dbf4b78fb2ac815/servo-atlas/src/main/java/com/netflix/servo/publish/atlas/ValidCharacters.java#L112-L125 | train |
Netflix/servo | servo-atlas/src/main/java/com/netflix/servo/publish/atlas/ValidCharacters.java | ValidCharacters.toValidValues | public static List<Metric> toValidValues(List<Metric> metrics) {
return metrics.stream().map(ValidCharacters::toValidValue).collect(Collectors.toList());
} | java | public static List<Metric> toValidValues(List<Metric> metrics) {
return metrics.stream().map(ValidCharacters::toValidValue).collect(Collectors.toList());
} | [
"public",
"static",
"List",
"<",
"Metric",
">",
"toValidValues",
"(",
"List",
"<",
"Metric",
">",
"metrics",
")",
"{",
"return",
"metrics",
".",
"stream",
"(",
")",
".",
"map",
"(",
"ValidCharacters",
"::",
"toValidValue",
")",
".",
"collect",
"(",
"Coll... | Create a new list of metrics where all metrics are using the valid character set. | [
"Create",
"a",
"new",
"list",
"of",
"metrics",
"where",
"all",
"metrics",
"are",
"using",
"the",
"valid",
"character",
"set",
"."
] | d67b5afce8c50bd9e9e31c288dbf4b78fb2ac815 | https://github.com/Netflix/servo/blob/d67b5afce8c50bd9e9e31c288dbf4b78fb2ac815/servo-atlas/src/main/java/com/netflix/servo/publish/atlas/ValidCharacters.java#L130-L132 | train |
Netflix/servo | servo-atlas/src/main/java/com/netflix/servo/publish/atlas/ValidCharacters.java | ValidCharacters.tagToJson | 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()));
}
} | java | 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()));
}
} | [
"public",
"static",
"void",
"tagToJson",
"(",
"JsonGenerator",
"gen",
",",
"Tag",
"tag",
")",
"throws",
"IOException",
"{",
"final",
"String",
"key",
"=",
"tag",
".",
"getKey",
"(",
")",
";",
"if",
"(",
"RELAXED_GROUP_KEYS",
".",
"contains",
"(",
"key",
... | Serialize a tag to the given JsonGenerator. | [
"Serialize",
"a",
"tag",
"to",
"the",
"given",
"JsonGenerator",
"."
] | d67b5afce8c50bd9e9e31c288dbf4b78fb2ac815 | https://github.com/Netflix/servo/blob/d67b5afce8c50bd9e9e31c288dbf4b78fb2ac815/servo-atlas/src/main/java/com/netflix/servo/publish/atlas/ValidCharacters.java#L137-L144 | train |
Netflix/servo | servo-core/src/main/java/com/netflix/servo/monitor/StatsMonitor.java | StatsMonitor.record | 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);
} | java | 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);
} | [
"public",
"void",
"record",
"(",
"long",
"measurement",
")",
"{",
"lastUsed",
"=",
"clock",
".",
"now",
"(",
")",
";",
"if",
"(",
"isExpired",
"(",
")",
")",
"{",
"LOGGER",
".",
"info",
"(",
"\"Attempting to get the value for an expired monitor: {}.\"",
"+",
... | Record the measurement we want to perform statistics on. | [
"Record",
"the",
"measurement",
"we",
"want",
"to",
"perform",
"statistics",
"on",
"."
] | d67b5afce8c50bd9e9e31c288dbf4b78fb2ac815 | https://github.com/Netflix/servo/blob/d67b5afce8c50bd9e9e31c288dbf4b78fb2ac815/servo-core/src/main/java/com/netflix/servo/monitor/StatsMonitor.java#L444-L458 | train |
Netflix/servo | servo-core/src/main/java/com/netflix/servo/monitor/StatsMonitor.java | StatsMonitor.getValue | @Override
public Long getValue(int pollerIndex) {
final long n = getCount(pollerIndex);
return n > 0 ? totalMeasurement.getValue(pollerIndex).longValue() / n : 0L;
} | java | @Override
public Long getValue(int pollerIndex) {
final long n = getCount(pollerIndex);
return n > 0 ? totalMeasurement.getValue(pollerIndex).longValue() / n : 0L;
} | [
"@",
"Override",
"public",
"Long",
"getValue",
"(",
"int",
"pollerIndex",
")",
"{",
"final",
"long",
"n",
"=",
"getCount",
"(",
"pollerIndex",
")",
";",
"return",
"n",
">",
"0",
"?",
"totalMeasurement",
".",
"getValue",
"(",
"pollerIndex",
")",
".",
"lon... | Get the value of the measurement. | [
"Get",
"the",
"value",
"of",
"the",
"measurement",
"."
] | d67b5afce8c50bd9e9e31c288dbf4b78fb2ac815 | https://github.com/Netflix/servo/blob/d67b5afce8c50bd9e9e31c288dbf4b78fb2ac815/servo-core/src/main/java/com/netflix/servo/monitor/StatsMonitor.java#L463-L467 | train |
Netflix/servo | servo-core/src/main/java/com/netflix/servo/util/ExpiringCache.java | ExpiringCache.values | public List<V> values() {
final Collection<Entry<V>> values = map.values();
// Note below that e.value avoids updating the access time
final List<V> res = values.stream().map(e -> e.value).collect(Collectors.toList());
return Collections.unmodifiableList(res);
} | java | public List<V> values() {
final Collection<Entry<V>> values = map.values();
// Note below that e.value avoids updating the access time
final List<V> res = values.stream().map(e -> e.value).collect(Collectors.toList());
return Collections.unmodifiableList(res);
} | [
"public",
"List",
"<",
"V",
">",
"values",
"(",
")",
"{",
"final",
"Collection",
"<",
"Entry",
"<",
"V",
">",
">",
"values",
"=",
"map",
".",
"values",
"(",
")",
";",
"// Note below that e.value avoids updating the access time",
"final",
"List",
"<",
"V",
... | Get the list of all values that are members of this cache. Does not
affect the access time used for eviction. | [
"Get",
"the",
"list",
"of",
"all",
"values",
"that",
"are",
"members",
"of",
"this",
"cache",
".",
"Does",
"not",
"affect",
"the",
"access",
"time",
"used",
"for",
"eviction",
"."
] | d67b5afce8c50bd9e9e31c288dbf4b78fb2ac815 | https://github.com/Netflix/servo/blob/d67b5afce8c50bd9e9e31c288dbf4b78fb2ac815/servo-core/src/main/java/com/netflix/servo/util/ExpiringCache.java#L159-L164 | train |
Netflix/servo | servo-core/src/main/java/com/netflix/servo/publish/PollScheduler.java | PollScheduler.addPoller | 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");
}
} | java | 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");
}
} | [
"public",
"void",
"addPoller",
"(",
"PollRunnable",
"task",
",",
"long",
"delay",
",",
"TimeUnit",
"timeUnit",
")",
"{",
"ScheduledExecutorService",
"service",
"=",
"executor",
".",
"get",
"(",
")",
";",
"if",
"(",
"service",
"!=",
"null",
")",
"{",
"servi... | Add a tasks to execute at a fixed rate based on the provided delay. | [
"Add",
"a",
"tasks",
"to",
"execute",
"at",
"a",
"fixed",
"rate",
"based",
"on",
"the",
"provided",
"delay",
"."
] | d67b5afce8c50bd9e9e31c288dbf4b78fb2ac815 | https://github.com/Netflix/servo/blob/d67b5afce8c50bd9e9e31c288dbf4b78fb2ac815/servo-core/src/main/java/com/netflix/servo/publish/PollScheduler.java#L51-L59 | train |
Netflix/servo | servo-core/src/main/java/com/netflix/servo/publish/PollScheduler.java | PollScheduler.start | public void start() {
int numThreads = Runtime.getRuntime().availableProcessors();
ThreadFactory factory = ThreadFactories.withName("ServoPollScheduler-%d");
start(Executors.newScheduledThreadPool(numThreads, factory));
} | java | public void start() {
int numThreads = Runtime.getRuntime().availableProcessors();
ThreadFactory factory = ThreadFactories.withName("ServoPollScheduler-%d");
start(Executors.newScheduledThreadPool(numThreads, factory));
} | [
"public",
"void",
"start",
"(",
")",
"{",
"int",
"numThreads",
"=",
"Runtime",
".",
"getRuntime",
"(",
")",
".",
"availableProcessors",
"(",
")",
";",
"ThreadFactory",
"factory",
"=",
"ThreadFactories",
".",
"withName",
"(",
"\"ServoPollScheduler-%d\"",
")",
"... | Start scheduling tasks with a default thread pool, sized based on the
number of available processors. | [
"Start",
"scheduling",
"tasks",
"with",
"a",
"default",
"thread",
"pool",
"sized",
"based",
"on",
"the",
"number",
"of",
"available",
"processors",
"."
] | d67b5afce8c50bd9e9e31c288dbf4b78fb2ac815 | https://github.com/Netflix/servo/blob/d67b5afce8c50bd9e9e31c288dbf4b78fb2ac815/servo-core/src/main/java/com/netflix/servo/publish/PollScheduler.java#L65-L69 | train |
Netflix/servo | servo-core/src/main/java/com/netflix/servo/publish/PollScheduler.java | PollScheduler.stop | 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");
}
} | java | 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");
}
} | [
"public",
"void",
"stop",
"(",
")",
"{",
"ScheduledExecutorService",
"service",
"=",
"executor",
".",
"get",
"(",
")",
";",
"if",
"(",
"service",
"!=",
"null",
"&&",
"executor",
".",
"compareAndSet",
"(",
"service",
",",
"null",
")",
")",
"{",
"service",... | Stop the poller, shutting down the current executor service. | [
"Stop",
"the",
"poller",
"shutting",
"down",
"the",
"current",
"executor",
"service",
"."
] | d67b5afce8c50bd9e9e31c288dbf4b78fb2ac815 | https://github.com/Netflix/servo/blob/d67b5afce8c50bd9e9e31c288dbf4b78fb2ac815/servo-core/src/main/java/com/netflix/servo/publish/PollScheduler.java#L83-L90 | train |
Netflix/servo | servo-core/src/main/java/com/netflix/servo/util/Strings.java | Strings.join | 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();
} | java | 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();
} | [
"public",
"static",
"String",
"join",
"(",
"String",
"separator",
",",
"Iterator",
"<",
"?",
">",
"parts",
")",
"{",
"Preconditions",
".",
"checkNotNull",
"(",
"separator",
",",
"\"separator\"",
")",
";",
"Preconditions",
".",
"checkNotNull",
"(",
"parts",
"... | Join the string representation of each part separated by the given separator string.
@param separator Separator string. For example ","
@param parts An iterator of the parts to join
@return The string formed by joining each part separated by the given separator. | [
"Join",
"the",
"string",
"representation",
"of",
"each",
"part",
"separated",
"by",
"the",
"given",
"separator",
"string",
"."
] | d67b5afce8c50bd9e9e31c288dbf4b78fb2ac815 | https://github.com/Netflix/servo/blob/d67b5afce8c50bd9e9e31c288dbf4b78fb2ac815/servo-core/src/main/java/com/netflix/servo/util/Strings.java#L41-L54 | train |
Netflix/servo | servo-core/src/main/java/com/netflix/servo/util/Preconditions.java | Preconditions.checkNotNull | 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;
} | java | 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;
} | [
"public",
"static",
"<",
"T",
">",
"T",
"checkNotNull",
"(",
"T",
"obj",
",",
"String",
"name",
")",
"{",
"if",
"(",
"obj",
"==",
"null",
")",
"{",
"String",
"msg",
"=",
"String",
".",
"format",
"(",
"\"parameter '%s' cannot be null\"",
",",
"name",
")... | Ensures the object reference is not null. | [
"Ensures",
"the",
"object",
"reference",
"is",
"not",
"null",
"."
] | d67b5afce8c50bd9e9e31c288dbf4b78fb2ac815 | https://github.com/Netflix/servo/blob/d67b5afce8c50bd9e9e31c288dbf4b78fb2ac815/servo-core/src/main/java/com/netflix/servo/util/Preconditions.java#L30-L36 | train |
Netflix/servo | servo-core/src/main/java/com/netflix/servo/monitor/MinGauge.java | MinGauge.update | public void update(long v) {
for (int i = 0; i < Pollers.NUM_POLLERS; ++i) {
updateMin(i, v);
}
} | java | public void update(long v) {
for (int i = 0; i < Pollers.NUM_POLLERS; ++i) {
updateMin(i, v);
}
} | [
"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. | [
"Update",
"the",
"min",
"if",
"the",
"provided",
"value",
"is",
"smaller",
"than",
"the",
"current",
"min",
"."
] | d67b5afce8c50bd9e9e31c288dbf4b78fb2ac815 | https://github.com/Netflix/servo/blob/d67b5afce8c50bd9e9e31c288dbf4b78fb2ac815/servo-core/src/main/java/com/netflix/servo/monitor/MinGauge.java#L62-L66 | train |
Netflix/servo | servo-core/src/main/java/com/netflix/servo/monitor/MinGauge.java | MinGauge.getCurrentValue | public long getCurrentValue(int nth) {
long v = min.getCurrent(nth).get();
return (v == Long.MAX_VALUE) ? 0L : v;
} | java | public long getCurrentValue(int nth) {
long v = min.getCurrent(nth).get();
return (v == Long.MAX_VALUE) ? 0L : v;
} | [
"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. | [
"Returns",
"the",
"current",
"min",
"value",
"since",
"the",
"last",
"reset",
"."
] | d67b5afce8c50bd9e9e31c288dbf4b78fb2ac815 | https://github.com/Netflix/servo/blob/d67b5afce8c50bd9e9e31c288dbf4b78fb2ac815/servo-core/src/main/java/com/netflix/servo/monitor/MinGauge.java#L80-L83 | train |
Netflix/servo | servo-core/src/main/java/com/netflix/servo/publish/MemoryMetricObserver.java | MemoryMetricObserver.getObservations | 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);
} | java | 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);
} | [
"public",
"List",
"<",
"List",
"<",
"Metric",
">",
">",
"getObservations",
"(",
")",
"{",
"List",
"<",
"List",
"<",
"Metric",
">>",
"builder",
"=",
"new",
"ArrayList",
"<>",
"(",
")",
";",
"int",
"pos",
"=",
"next",
";",
"for",
"(",
"List",
"<",
... | Returns the current set of observations. | [
"Returns",
"the",
"current",
"set",
"of",
"observations",
"."
] | d67b5afce8c50bd9e9e31c288dbf4b78fb2ac815 | https://github.com/Netflix/servo/blob/d67b5afce8c50bd9e9e31c288dbf4b78fb2ac815/servo-core/src/main/java/com/netflix/servo/publish/MemoryMetricObserver.java#L62-L72 | train |
Netflix/servo | servo-core/src/main/java/com/netflix/servo/monitor/MonitorConfig.java | MonitorConfig.copy | private MonitorConfig.Builder copy() {
return MonitorConfig.builder(name).withTags(tags).withPublishingPolicy(policy);
} | java | private MonitorConfig.Builder copy() {
return MonitorConfig.builder(name).withTags(tags).withPublishingPolicy(policy);
} | [
"private",
"MonitorConfig",
".",
"Builder",
"copy",
"(",
")",
"{",
"return",
"MonitorConfig",
".",
"builder",
"(",
"name",
")",
".",
"withTags",
"(",
"tags",
")",
".",
"withPublishingPolicy",
"(",
"policy",
")",
";",
"}"
] | Returns a copy of the current MonitorConfig. | [
"Returns",
"a",
"copy",
"of",
"the",
"current",
"MonitorConfig",
"."
] | d67b5afce8c50bd9e9e31c288dbf4b78fb2ac815 | https://github.com/Netflix/servo/blob/d67b5afce8c50bd9e9e31c288dbf4b78fb2ac815/servo-core/src/main/java/com/netflix/servo/monitor/MonitorConfig.java#L236-L238 | train |
Netflix/servo | servo-core/src/main/java/com/netflix/servo/monitor/MaxGauge.java | MaxGauge.update | public void update(long v) {
spectatorGauge.set(v);
for (int i = 0; i < Pollers.NUM_POLLERS; ++i) {
updateMax(i, v);
}
} | java | public void update(long v) {
spectatorGauge.set(v);
for (int i = 0; i < Pollers.NUM_POLLERS; ++i) {
updateMax(i, v);
}
} | [
"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. | [
"Update",
"the",
"max",
"if",
"the",
"provided",
"value",
"is",
"larger",
"than",
"the",
"current",
"max",
"."
] | d67b5afce8c50bd9e9e31c288dbf4b78fb2ac815 | https://github.com/Netflix/servo/blob/d67b5afce8c50bd9e9e31c288dbf4b78fb2ac815/servo-core/src/main/java/com/netflix/servo/monitor/MaxGauge.java#L71-L76 | train |
Netflix/servo | servo-atlas/src/main/java/com/netflix/servo/publish/atlas/HttpHelper.java | HttpHelper.sendAll | 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();
} | java | 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();
} | [
"public",
"int",
"sendAll",
"(",
"Iterable",
"<",
"Observable",
"<",
"Integer",
">",
">",
"batches",
",",
"final",
"int",
"numMetrics",
",",
"long",
"timeoutMillis",
")",
"{",
"final",
"AtomicBoolean",
"err",
"=",
"new",
"AtomicBoolean",
"(",
"false",
")",
... | Attempt to send all the batches totalling numMetrics in the allowed time.
@return The total number of metrics sent. | [
"Attempt",
"to",
"send",
"all",
"the",
"batches",
"totalling",
"numMetrics",
"in",
"the",
"allowed",
"time",
"."
] | d67b5afce8c50bd9e9e31c288dbf4b78fb2ac815 | https://github.com/Netflix/servo/blob/d67b5afce8c50bd9e9e31c288dbf4b78fb2ac815/servo-atlas/src/main/java/com/netflix/servo/publish/atlas/HttpHelper.java#L149-L180 | train |
Netflix/servo | servo-atlas/src/main/java/com/netflix/servo/publish/atlas/HttpHelper.java | HttpHelper.get | 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);
}
} | java | 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);
}
} | [
"public",
"Response",
"get",
"(",
"HttpClientRequest",
"<",
"ByteBuf",
">",
"req",
",",
"long",
"timeout",
",",
"TimeUnit",
"timeUnit",
")",
"{",
"final",
"String",
"uri",
"=",
"req",
".",
"getUri",
"(",
")",
";",
"final",
"Response",
"result",
"=",
"new... | Perform an HTTP get in the allowed time. | [
"Perform",
"an",
"HTTP",
"get",
"in",
"the",
"allowed",
"time",
"."
] | d67b5afce8c50bd9e9e31c288dbf4b78fb2ac815 | https://github.com/Netflix/servo/blob/d67b5afce8c50bd9e9e31c288dbf4b78fb2ac815/servo-atlas/src/main/java/com/netflix/servo/publish/atlas/HttpHelper.java#L185-L216 | train |
Netflix/servo | servo-core/src/main/java/com/netflix/servo/monitor/DynamicCounter.java | DynamicCounter.increment | public static void increment(String name, TagList list) {
final MonitorConfig config = new MonitorConfig.Builder(name).withTags(list).build();
increment(config);
} | java | public static void increment(String name, TagList list) {
final MonitorConfig config = new MonitorConfig.Builder(name).withTags(list).build();
increment(config);
} | [
"public",
"static",
"void",
"increment",
"(",
"String",
"name",
",",
"TagList",
"list",
")",
"{",
"final",
"MonitorConfig",
"config",
"=",
"new",
"MonitorConfig",
".",
"Builder",
"(",
"name",
")",
".",
"withTags",
"(",
"list",
")",
".",
"build",
"(",
")"... | Increment the counter for a given name, tagList. | [
"Increment",
"the",
"counter",
"for",
"a",
"given",
"name",
"tagList",
"."
] | d67b5afce8c50bd9e9e31c288dbf4b78fb2ac815 | https://github.com/Netflix/servo/blob/d67b5afce8c50bd9e9e31c288dbf4b78fb2ac815/servo-core/src/main/java/com/netflix/servo/monitor/DynamicCounter.java#L108-L111 | train |
Netflix/servo | servo-core/src/main/java/com/netflix/servo/monitor/DynamicCounter.java | DynamicCounter.increment | public static void increment(String name, TagList list, long delta) {
final MonitorConfig config = MonitorConfig.builder(name).withTags(list).build();
increment(config, delta);
} | java | public static void increment(String name, TagList list, long delta) {
final MonitorConfig config = MonitorConfig.builder(name).withTags(list).build();
increment(config, delta);
} | [
"public",
"static",
"void",
"increment",
"(",
"String",
"name",
",",
"TagList",
"list",
",",
"long",
"delta",
")",
"{",
"final",
"MonitorConfig",
"config",
"=",
"MonitorConfig",
".",
"builder",
"(",
"name",
")",
".",
"withTags",
"(",
"list",
")",
".",
"b... | Increment the counter for a given name, tagList by a given delta. | [
"Increment",
"the",
"counter",
"for",
"a",
"given",
"name",
"tagList",
"by",
"a",
"given",
"delta",
"."
] | d67b5afce8c50bd9e9e31c288dbf4b78fb2ac815 | https://github.com/Netflix/servo/blob/d67b5afce8c50bd9e9e31c288dbf4b78fb2ac815/servo-core/src/main/java/com/netflix/servo/monitor/DynamicCounter.java#L116-L119 | train |
Netflix/servo | servo-core/src/main/java/com/netflix/servo/jmx/JmxMonitorRegistry.java | JmxMonitorRegistry.getRegisteredMonitors | @Override
public Collection<Monitor<?>> getRegisteredMonitors() {
if (updatePending.getAndSet(false)) {
monitorList.set(UnmodifiableList.copyOf(monitors.values()));
}
return monitorList.get();
} | java | @Override
public Collection<Monitor<?>> getRegisteredMonitors() {
if (updatePending.getAndSet(false)) {
monitorList.set(UnmodifiableList.copyOf(monitors.values()));
}
return monitorList.get();
} | [
"@",
"Override",
"public",
"Collection",
"<",
"Monitor",
"<",
"?",
">",
">",
"getRegisteredMonitors",
"(",
")",
"{",
"if",
"(",
"updatePending",
".",
"getAndSet",
"(",
"false",
")",
")",
"{",
"monitorList",
".",
"set",
"(",
"UnmodifiableList",
".",
"copyOf... | The set of registered Monitor objects. | [
"The",
"set",
"of",
"registered",
"Monitor",
"objects",
"."
] | d67b5afce8c50bd9e9e31c288dbf4b78fb2ac815 | https://github.com/Netflix/servo/blob/d67b5afce8c50bd9e9e31c288dbf4b78fb2ac815/servo-core/src/main/java/com/netflix/servo/jmx/JmxMonitorRegistry.java#L95-L101 | train |
Netflix/servo | servo-core/src/main/java/com/netflix/servo/monitor/LongGauge.java | LongGauge.set | public void set(Long n) {
spectatorGauge.set(n);
AtomicLong number = getNumber();
number.set(n);
} | java | public void set(Long n) {
spectatorGauge.set(n);
AtomicLong number = getNumber();
number.set(n);
} | [
"public",
"void",
"set",
"(",
"Long",
"n",
")",
"{",
"spectatorGauge",
".",
"set",
"(",
"n",
")",
";",
"AtomicLong",
"number",
"=",
"getNumber",
"(",
")",
";",
"number",
".",
"set",
"(",
"n",
")",
";",
"}"
] | Set the current value. | [
"Set",
"the",
"current",
"value",
"."
] | d67b5afce8c50bd9e9e31c288dbf4b78fb2ac815 | https://github.com/Netflix/servo/blob/d67b5afce8c50bd9e9e31c288dbf4b78fb2ac815/servo-core/src/main/java/com/netflix/servo/monitor/LongGauge.java#L49-L53 | train |
Netflix/servo | servo-core/src/main/java/com/netflix/servo/monitor/BucketTimer.java | BucketTimer.getCount | public Long getCount(int pollerIndex) {
long updates = 0;
for (Counter c : bucketCount) {
updates += c.getValue(pollerIndex).longValue();
}
updates += overflowCount.getValue(pollerIndex).longValue();
return updates;
} | java | public Long getCount(int pollerIndex) {
long updates = 0;
for (Counter c : bucketCount) {
updates += c.getValue(pollerIndex).longValue();
}
updates += overflowCount.getValue(pollerIndex).longValue();
return updates;
} | [
"public",
"Long",
"getCount",
"(",
"int",
"pollerIndex",
")",
"{",
"long",
"updates",
"=",
"0",
";",
"for",
"(",
"Counter",
"c",
":",
"bucketCount",
")",
"{",
"updates",
"+=",
"c",
".",
"getValue",
"(",
"pollerIndex",
")",
".",
"longValue",
"(",
")",
... | Get the total number of updates. | [
"Get",
"the",
"total",
"number",
"of",
"updates",
"."
] | d67b5afce8c50bd9e9e31c288dbf4b78fb2ac815 | https://github.com/Netflix/servo/blob/d67b5afce8c50bd9e9e31c288dbf4b78fb2ac815/servo-core/src/main/java/com/netflix/servo/monitor/BucketTimer.java#L228-L236 | train |
Netflix/servo | servo-core/src/main/java/com/netflix/servo/publish/JmxMetricPoller.java | JmxMetricPoller.createTagList | 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());
} | java | 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());
} | [
"private",
"TagList",
"createTagList",
"(",
"ObjectName",
"name",
")",
"{",
"Map",
"<",
"String",
",",
"String",
">",
"props",
"=",
"name",
".",
"getKeyPropertyList",
"(",
")",
";",
"SmallTagMap",
".",
"Builder",
"tagsBuilder",
"=",
"SmallTagMap",
".",
"buil... | Creates a tag list from an object name. | [
"Creates",
"a",
"tag",
"list",
"from",
"an",
"object",
"name",
"."
] | d67b5afce8c50bd9e9e31c288dbf4b78fb2ac815 | https://github.com/Netflix/servo/blob/d67b5afce8c50bd9e9e31c288dbf4b78fb2ac815/servo-core/src/main/java/com/netflix/servo/publish/JmxMetricPoller.java#L124-L137 | train |
Netflix/servo | servo-core/src/main/java/com/netflix/servo/publish/JmxMetricPoller.java | JmxMetricPoller.addMetric | 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);
}
} | java | 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);
}
} | [
"private",
"void",
"addMetric",
"(",
"List",
"<",
"Metric",
">",
"metrics",
",",
"String",
"name",
",",
"TagList",
"tags",
",",
"Object",
"value",
")",
"{",
"long",
"now",
"=",
"System",
".",
"currentTimeMillis",
"(",
")",
";",
"if",
"(",
"onlyNumericMet... | Create a new metric object and add it to the list. | [
"Create",
"a",
"new",
"metric",
"object",
"and",
"add",
"it",
"to",
"the",
"list",
"."
] | d67b5afce8c50bd9e9e31c288dbf4b78fb2ac815 | https://github.com/Netflix/servo/blob/d67b5afce8c50bd9e9e31c288dbf4b78fb2ac815/servo-core/src/main/java/com/netflix/servo/publish/JmxMetricPoller.java#L146-L163 | train |
Netflix/servo | servo-core/src/main/java/com/netflix/servo/publish/JmxMetricPoller.java | JmxMetricPoller.asNumber | 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;
} | java | 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;
} | [
"private",
"static",
"Number",
"asNumber",
"(",
"Object",
"value",
")",
"{",
"Number",
"num",
"=",
"null",
";",
"if",
"(",
"value",
"==",
"null",
")",
"{",
"num",
"=",
"null",
";",
"}",
"else",
"if",
"(",
"value",
"instanceof",
"Number",
")",
"{",
... | 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. | [
"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",
"... | d67b5afce8c50bd9e9e31c288dbf4b78fb2ac815 | https://github.com/Netflix/servo/blob/d67b5afce8c50bd9e9e31c288dbf4b78fb2ac815/servo-core/src/main/java/com/netflix/servo/publish/JmxMetricPoller.java#L255-L265 | train |
Netflix/servo | servo-core/src/main/java/com/netflix/servo/monitor/DynamicGauge.java | DynamicGauge.set | public static void set(String name, double value) {
set(MonitorConfig.builder(name).build(), value);
} | java | public static void set(String name, double value) {
set(MonitorConfig.builder(name).build(), value);
} | [
"public",
"static",
"void",
"set",
"(",
"String",
"name",
",",
"double",
"value",
")",
"{",
"set",
"(",
"MonitorConfig",
".",
"builder",
"(",
"name",
")",
".",
"build",
"(",
")",
",",
"value",
")",
";",
"}"
] | Increment a gauge specified by a name. | [
"Increment",
"a",
"gauge",
"specified",
"by",
"a",
"name",
"."
] | d67b5afce8c50bd9e9e31c288dbf4b78fb2ac815 | https://github.com/Netflix/servo/blob/d67b5afce8c50bd9e9e31c288dbf4b78fb2ac815/servo-core/src/main/java/com/netflix/servo/monitor/DynamicGauge.java#L92-L94 | train |
Netflix/servo | servo-core/src/main/java/com/netflix/servo/monitor/DynamicGauge.java | DynamicGauge.set | public static void set(String name, TagList list, double value) {
final MonitorConfig config = MonitorConfig.builder(name).withTags(list).build();
set(config, value);
} | java | public static void set(String name, TagList list, double value) {
final MonitorConfig config = MonitorConfig.builder(name).withTags(list).build();
set(config, value);
} | [
"public",
"static",
"void",
"set",
"(",
"String",
"name",
",",
"TagList",
"list",
",",
"double",
"value",
")",
"{",
"final",
"MonitorConfig",
"config",
"=",
"MonitorConfig",
".",
"builder",
"(",
"name",
")",
".",
"withTags",
"(",
"list",
")",
".",
"build... | Set the gauge for a given name, tagList by a given value. | [
"Set",
"the",
"gauge",
"for",
"a",
"given",
"name",
"tagList",
"by",
"a",
"given",
"value",
"."
] | d67b5afce8c50bd9e9e31c288dbf4b78fb2ac815 | https://github.com/Netflix/servo/blob/d67b5afce8c50bd9e9e31c288dbf4b78fb2ac815/servo-core/src/main/java/com/netflix/servo/monitor/DynamicGauge.java#L99-L102 | train |
Netflix/servo | servo-core/src/main/java/com/netflix/servo/monitor/Pollers.java | Pollers.join | 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();
} | java | 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();
} | [
"private",
"static",
"String",
"join",
"(",
"long",
"[",
"]",
"a",
")",
"{",
"assert",
"(",
"a",
".",
"length",
">",
"0",
")",
";",
"StringBuilder",
"builder",
"=",
"new",
"StringBuilder",
"(",
")",
";",
"builder",
".",
"append",
"(",
"a",
"[",
"0"... | For debugging. Simple toString for non-empty arrays | [
"For",
"debugging",
".",
"Simple",
"toString",
"for",
"non",
"-",
"empty",
"arrays"
] | d67b5afce8c50bd9e9e31c288dbf4b78fb2ac815 | https://github.com/Netflix/servo/blob/d67b5afce8c50bd9e9e31c288dbf4b78fb2ac815/servo-core/src/main/java/com/netflix/servo/monitor/Pollers.java#L66-L75 | train |
Netflix/servo | servo-core/src/main/java/com/netflix/servo/monitor/Pollers.java | Pollers.parse | 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;
}
} | java | 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;
}
} | [
"static",
"long",
"[",
"]",
"parse",
"(",
"String",
"pollers",
")",
"{",
"String",
"[",
"]",
"periods",
"=",
"pollers",
".",
"split",
"(",
"\",\\\\s*\"",
")",
";",
"long",
"[",
"]",
"result",
"=",
"new",
"long",
"[",
"periods",
".",
"length",
"]",
... | 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. | [
"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",
"."
] | d67b5afce8c50bd9e9e31c288dbf4b78fb2ac815 | https://github.com/Netflix/servo/blob/d67b5afce8c50bd9e9e31c288dbf4b78fb2ac815/servo-core/src/main/java/com/netflix/servo/monitor/Pollers.java#L82-L109 | train |
skjolber/3d-bin-container-packing | src/main/java/com/github/skjolberg/packing/Packager.java | Packager.filterByVolumeAndWeight | 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) {
// volume
long boxVolume = box.getVolume();
volume += boxVolume;
if (boxVolume < minVolume) {
minVolume = boxVolume;
}
// weight
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) {
// volume
long boxVolume = container.getVolume();
if (boxVolume > maxVolume) {
maxVolume = boxVolume;
}
// weight
long boxWeight = container.getWeight();
if (boxWeight > maxWeight) {
maxWeight = boxWeight;
}
}
if (maxVolume * count < volume || maxWeight * count < weight) {
// no containers will work at current count
return Collections.emptyList();
}
List<Container> list = new ArrayList<>(containers.size());
for (Container container : containers) {
if (container.getVolume() < minVolume || container.getWeight() < minWeight) {
// this box cannot even fit a single box
continue;
}
if (container.getVolume() + maxVolume * (count - 1) < volume || container.getWeight() + maxWeight * (count - 1) < weight) {
// this box cannot be used even together with all biggest boxes
continue;
}
if (count == 1) {
if (!canHoldAll(container, boxes)) {
continue;
}
} else {
if (!canHoldAtLeastOne(container, boxes)) {
continue;
}
}
list.add(container);
}
return list;
} | java | 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) {
// volume
long boxVolume = box.getVolume();
volume += boxVolume;
if (boxVolume < minVolume) {
minVolume = boxVolume;
}
// weight
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) {
// volume
long boxVolume = container.getVolume();
if (boxVolume > maxVolume) {
maxVolume = boxVolume;
}
// weight
long boxWeight = container.getWeight();
if (boxWeight > maxWeight) {
maxWeight = boxWeight;
}
}
if (maxVolume * count < volume || maxWeight * count < weight) {
// no containers will work at current count
return Collections.emptyList();
}
List<Container> list = new ArrayList<>(containers.size());
for (Container container : containers) {
if (container.getVolume() < minVolume || container.getWeight() < minWeight) {
// this box cannot even fit a single box
continue;
}
if (container.getVolume() + maxVolume * (count - 1) < volume || container.getWeight() + maxWeight * (count - 1) < weight) {
// this box cannot be used even together with all biggest boxes
continue;
}
if (count == 1) {
if (!canHoldAll(container, boxes)) {
continue;
}
} else {
if (!canHoldAtLeastOne(container, boxes)) {
continue;
}
}
list.add(container);
}
return list;
} | [
"private",
"List",
"<",
"Container",
">",
"filterByVolumeAndWeight",
"(",
"List",
"<",
"Box",
">",
"boxes",
",",
"List",
"<",
"Container",
">",
"containers",
",",
"int",
"count",
")",
"{",
"long",
"volume",
"=",
"0",
";",
"long",
"minVolume",
"=",
"Long"... | Return a list of containers which can potentially hold the boxes.
@param boxes list of boxes
@param containers list of containers
@param count maximum number of possible containers
@return list of containers | [
"Return",
"a",
"list",
"of",
"containers",
"which",
"can",
"potentially",
"hold",
"the",
"boxes",
"."
] | 9609bc7515322b2de2cad0dfb3d2f72607e71aae | https://github.com/skjolber/3d-bin-container-packing/blob/9609bc7515322b2de2cad0dfb3d2f72607e71aae/src/main/java/com/github/skjolberg/packing/Packager.java#L325-L398 | train |
skjolber/3d-bin-container-packing | src/main/java/com/github/skjolberg/packing/Box.java | Box.rotate3D | public Box rotate3D() {
int height = this.height;
this.height = width;
this.width = depth;
this.depth = height;
return this;
} | java | public Box rotate3D() {
int height = this.height;
this.height = width;
this.width = depth;
this.depth = height;
return this;
} | [
"public",
"Box",
"rotate3D",
"(",
")",
"{",
"int",
"height",
"=",
"this",
".",
"height",
";",
"this",
".",
"height",
"=",
"width",
";",
"this",
".",
"width",
"=",
"depth",
";",
"this",
".",
"depth",
"=",
"height",
";",
"return",
"this",
";",
"}"
] | Rotate box, i.e. in 3D
@return this instance | [
"Rotate",
"box",
"i",
".",
"e",
".",
"in",
"3D"
] | 9609bc7515322b2de2cad0dfb3d2f72607e71aae | https://github.com/skjolber/3d-bin-container-packing/blob/9609bc7515322b2de2cad0dfb3d2f72607e71aae/src/main/java/com/github/skjolberg/packing/Box.java#L27-L35 | train |
skjolber/3d-bin-container-packing | src/main/java/com/github/skjolberg/packing/Box.java | Box.fitRotate2D | boolean fitRotate2D(Dimension dimension) {
if (dimension.getHeight() < height) {
return false;
}
return fitRotate2D(dimension.getWidth(), dimension.getDepth());
} | java | boolean fitRotate2D(Dimension dimension) {
if (dimension.getHeight() < height) {
return false;
}
return fitRotate2D(dimension.getWidth(), dimension.getDepth());
} | [
"boolean",
"fitRotate2D",
"(",
"Dimension",
"dimension",
")",
"{",
"if",
"(",
"dimension",
".",
"getHeight",
"(",
")",
"<",
"height",
")",
"{",
"return",
"false",
";",
"}",
"return",
"fitRotate2D",
"(",
"dimension",
".",
"getWidth",
"(",
")",
",",
"dimen... | Rotate box within a free space in 2D
@param dimension space to fit within
@return if this object fits within the input dimensions | [
"Rotate",
"box",
"within",
"a",
"free",
"space",
"in",
"2D"
] | 9609bc7515322b2de2cad0dfb3d2f72607e71aae | https://github.com/skjolber/3d-bin-container-packing/blob/9609bc7515322b2de2cad0dfb3d2f72607e71aae/src/main/java/com/github/skjolberg/packing/Box.java#L201-L206 | train |
skjolber/3d-bin-container-packing | src/main/java/com/github/skjolberg/packing/LargestAreaFitFirstPackager.java | LargestAreaFitFirstPackager.fit2D | protected boolean fit2D(List<Box> containerProducts, Container holder, Box usedSpace, Space freeSpace, BooleanSupplier interrupt) {
if(rotate3D) {
// minimize footprint
usedSpace.fitRotate3DSmallestFootprint(freeSpace);
}
// add used space box now, but possibly rotate later - this depends on the actual remaining free space selected further down
// there is up to possible 4 free spaces, 2 in which the used space box is rotated
holder.add(new Placement(freeSpace, usedSpace));
if(containerProducts.isEmpty()) {
// no additional boxes
// just make sure the used space fits in the free space
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) {
// no additional boxes along the level floor (x,y)
// just make sure the used space fits in the free space
usedSpace.fitRotate2D(freeSpace);
} else {
// check whether the selected free space requires the used space box to be rotated
if(nextPlacement.getSpace() == spaces[2] || nextPlacement.getSpace() == spaces[3]) {
// the desired space implies that we rotate the used space box
usedSpace.rotate2D();
}
// holder.validateCurrentLevel(); // uncomment for debugging
removeIdentical(containerProducts, nextPlacement.getBox());
// attempt to fit in the remaining (usually smaller) space first
// stack in the 'sibling' space - the space left over between the used box and the selected free space
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;
}
}
}
// double check that there is still free weight
// TODO possibly rewind if the value of the boxes in the remainder is lower than the one in next placement
if(holder.getFreeWeight() >= nextPlacement.getBox().getWeight()) {
if(!fit2D(containerProducts, holder, nextPlacement.getBox(), nextPlacement.getSpace(), interrupt)) {
return false;
}
}
}
// also use the space above the placed box, if any.
if(freeSpace.getHeight() > usedSpace.getHeight()) {
// so there is some free room; between the used space and the level height
// the level by level approach is somewhat crude, but at least some of the inefficiency
// can be avoided this way
Space above;
if(nextPlacement == null) {
// full width / depth
above = new Space(
freeSpace.getWidth(),
freeSpace.getDepth(),
freeSpace.getHeight() - usedSpace.getHeight(),
freeSpace.getX(),
freeSpace.getY(),
freeSpace.getZ() + usedSpace.getHeight()
);
} else {
// just directly above the used space
// TODO possible include the sibling space if no box was fitted there
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) {
// should be within weight already
Box currentBox = containerProducts.get(currentIndex);
containerProducts.remove(currentIndex);
if(!fit2D(containerProducts, holder, currentBox, above, interrupt)) {
return false;
}
}
}
return true;
} | java | protected boolean fit2D(List<Box> containerProducts, Container holder, Box usedSpace, Space freeSpace, BooleanSupplier interrupt) {
if(rotate3D) {
// minimize footprint
usedSpace.fitRotate3DSmallestFootprint(freeSpace);
}
// add used space box now, but possibly rotate later - this depends on the actual remaining free space selected further down
// there is up to possible 4 free spaces, 2 in which the used space box is rotated
holder.add(new Placement(freeSpace, usedSpace));
if(containerProducts.isEmpty()) {
// no additional boxes
// just make sure the used space fits in the free space
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) {
// no additional boxes along the level floor (x,y)
// just make sure the used space fits in the free space
usedSpace.fitRotate2D(freeSpace);
} else {
// check whether the selected free space requires the used space box to be rotated
if(nextPlacement.getSpace() == spaces[2] || nextPlacement.getSpace() == spaces[3]) {
// the desired space implies that we rotate the used space box
usedSpace.rotate2D();
}
// holder.validateCurrentLevel(); // uncomment for debugging
removeIdentical(containerProducts, nextPlacement.getBox());
// attempt to fit in the remaining (usually smaller) space first
// stack in the 'sibling' space - the space left over between the used box and the selected free space
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;
}
}
}
// double check that there is still free weight
// TODO possibly rewind if the value of the boxes in the remainder is lower than the one in next placement
if(holder.getFreeWeight() >= nextPlacement.getBox().getWeight()) {
if(!fit2D(containerProducts, holder, nextPlacement.getBox(), nextPlacement.getSpace(), interrupt)) {
return false;
}
}
}
// also use the space above the placed box, if any.
if(freeSpace.getHeight() > usedSpace.getHeight()) {
// so there is some free room; between the used space and the level height
// the level by level approach is somewhat crude, but at least some of the inefficiency
// can be avoided this way
Space above;
if(nextPlacement == null) {
// full width / depth
above = new Space(
freeSpace.getWidth(),
freeSpace.getDepth(),
freeSpace.getHeight() - usedSpace.getHeight(),
freeSpace.getX(),
freeSpace.getY(),
freeSpace.getZ() + usedSpace.getHeight()
);
} else {
// just directly above the used space
// TODO possible include the sibling space if no box was fitted there
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) {
// should be within weight already
Box currentBox = containerProducts.get(currentIndex);
containerProducts.remove(currentIndex);
if(!fit2D(containerProducts, holder, currentBox, above, interrupt)) {
return false;
}
}
}
return true;
} | [
"protected",
"boolean",
"fit2D",
"(",
"List",
"<",
"Box",
">",
"containerProducts",
",",
"Container",
"holder",
",",
"Box",
"usedSpace",
",",
"Space",
"freeSpace",
",",
"BooleanSupplier",
"interrupt",
")",
"{",
"if",
"(",
"rotate3D",
")",
"{",
"// minimize foo... | Fit in two dimensions
@param containerProducts products to fit
@param holder target container
@param usedSpace space to subtract
@param freeSpace available space
@param interrupt interrupt
@return false if interrupted | [
"Fit",
"in",
"two",
"dimensions"
] | 9609bc7515322b2de2cad0dfb3d2f72607e71aae | https://github.com/skjolber/3d-bin-container-packing/blob/9609bc7515322b2de2cad0dfb3d2f72607e71aae/src/main/java/com/github/skjolberg/packing/LargestAreaFitFirstPackager.java#L185-L294 | train |
skjolber/3d-bin-container-packing | src/main/java/com/github/skjolberg/packing/LargestAreaFitFirstPackager.java | LargestAreaFitFirstPackager.isBetter2D | 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()); // i.e. smaller i better
} | java | 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()); // i.e. smaller i better
} | [
"protected",
"int",
"isBetter2D",
"(",
"Box",
"a",
",",
"Box",
"b",
")",
"{",
"int",
"compare",
"=",
"Long",
".",
"compare",
"(",
"a",
".",
"getVolume",
"(",
")",
",",
"b",
".",
"getVolume",
"(",
")",
")",
";",
"if",
"(",
"compare",
"!=",
"0",
... | Is box b better than a?
@param a box
@param b box
@return -1 if b is better, 0 if equal, 1 if b is better | [
"Is",
"box",
"b",
"better",
"than",
"a?"
] | 9609bc7515322b2de2cad0dfb3d2f72607e71aae | https://github.com/skjolber/3d-bin-container-packing/blob/9609bc7515322b2de2cad0dfb3d2f72607e71aae/src/main/java/com/github/skjolberg/packing/LargestAreaFitFirstPackager.java#L432-L439 | train |
skjolber/3d-bin-container-packing | src/main/java/com/github/skjolberg/packing/LargestAreaFitFirstPackager.java | LargestAreaFitFirstPackager.isBetter3D | protected int isBetter3D(Box a, Box b, Space space) {
int compare = Long.compare(a.getVolume(), b.getVolume());
if(compare != 0) {
return compare;
}
// determine lowest fit
a.fitRotate3DSmallestFootprint(space);
b.fitRotate3DSmallestFootprint(space);
return Long.compare(b.getFootprint(), a.getFootprint()); // i.e. smaller i better
} | java | protected int isBetter3D(Box a, Box b, Space space) {
int compare = Long.compare(a.getVolume(), b.getVolume());
if(compare != 0) {
return compare;
}
// determine lowest fit
a.fitRotate3DSmallestFootprint(space);
b.fitRotate3DSmallestFootprint(space);
return Long.compare(b.getFootprint(), a.getFootprint()); // i.e. smaller i better
} | [
"protected",
"int",
"isBetter3D",
"(",
"Box",
"a",
",",
"Box",
"b",
",",
"Space",
"space",
")",
"{",
"int",
"compare",
"=",
"Long",
".",
"compare",
"(",
"a",
".",
"getVolume",
"(",
")",
",",
"b",
".",
"getVolume",
"(",
")",
")",
";",
"if",
"(",
... | Is box b strictly better than a?
@param a box
@param b box
@param space free space
@return -1 if b is better, 0 if equal, 1 if b is better | [
"Is",
"box",
"b",
"strictly",
"better",
"than",
"a?"
] | 9609bc7515322b2de2cad0dfb3d2f72607e71aae | https://github.com/skjolber/3d-bin-container-packing/blob/9609bc7515322b2de2cad0dfb3d2f72607e71aae/src/main/java/com/github/skjolberg/packing/LargestAreaFitFirstPackager.java#L450-L460 | train |
skjolber/3d-bin-container-packing | src/main/java/com/github/skjolberg/packing/impl/PermutationRotationIterator.java | PermutationRotationIterator.removePermutations | 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) {
// skip this
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); // ascending order to make the permutation logic work
} | java | 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) {
// skip this
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); // ascending order to make the permutation logic work
} | [
"public",
"void",
"removePermutations",
"(",
"List",
"<",
"Integer",
">",
"removed",
")",
"{",
"int",
"[",
"]",
"permutations",
"=",
"new",
"int",
"[",
"this",
".",
"permutations",
".",
"length",
"]",
";",
"int",
"index",
"=",
"0",
";",
"permutations",
... | Remove permutations, if present. | [
"Remove",
"permutations",
"if",
"present",
"."
] | 9609bc7515322b2de2cad0dfb3d2f72607e71aae | https://github.com/skjolber/3d-bin-container-packing/blob/9609bc7515322b2de2cad0dfb3d2f72607e71aae/src/main/java/com/github/skjolberg/packing/impl/PermutationRotationIterator.java#L161-L189 | train |
skjolber/3d-bin-container-packing | src/main/java/com/github/skjolberg/packing/Container.java | Container.getFreeLevelSpace | 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);
} | java | 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);
} | [
"public",
"Dimension",
"getFreeLevelSpace",
"(",
")",
"{",
"int",
"remainder",
"=",
"height",
"-",
"getStackHeight",
"(",
")",
";",
"if",
"(",
"remainder",
"<",
"0",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"Remaining free space is negative at ... | Get the free level space, i.e. container height with height of
levels subtracted.
@return free height and box dimension | [
"Get",
"the",
"free",
"level",
"space",
"i",
".",
"e",
".",
"container",
"height",
"with",
"height",
"of",
"levels",
"subtracted",
"."
] | 9609bc7515322b2de2cad0dfb3d2f72607e71aae | https://github.com/skjolber/3d-bin-container-packing/blob/9609bc7515322b2de2cad0dfb3d2f72607e71aae/src/main/java/com/github/skjolberg/packing/Container.java#L148-L154 | train |
lessthanoptimal/BoofCV | main/boofcv-geo/src/main/java/boofcv/alg/geo/pose/PnPLepetitEPnP.java | PnPLepetitEPnP.process | 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");
// select world control points using the points statistics
selectWorldControlPoints(worldPts, controlWorldPts);
// compute barycentric coordinates for the world control points
computeBarycentricCoordinates(controlWorldPts, alphas, worldPts );
// create the linear system whose null space will contain the camera control points
constructM(observed, alphas, M);
// the camera points are a linear combination of these null points
extractNullPoints(M);
// compute the full constraint matrix, the others are extracted from this
if( numControl == 4 ) {
L_full.reshape(6, 10);
y.reshape(6,1);
UtilLepetitEPnP.constraintMatrix6x10(L_full,y,controlWorldPts,nullPts);
// compute 4 solutions using the null points
estimateCase1(solutions.get(0));
estimateCase2(solutions.get(1));
estimateCase3(solutions.get(2));
// results are bad in general, so skip unless needed
// always considering this case seems to hurt runtime speed a little bit
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);
} | java | 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");
// select world control points using the points statistics
selectWorldControlPoints(worldPts, controlWorldPts);
// compute barycentric coordinates for the world control points
computeBarycentricCoordinates(controlWorldPts, alphas, worldPts );
// create the linear system whose null space will contain the camera control points
constructM(observed, alphas, M);
// the camera points are a linear combination of these null points
extractNullPoints(M);
// compute the full constraint matrix, the others are extracted from this
if( numControl == 4 ) {
L_full.reshape(6, 10);
y.reshape(6,1);
UtilLepetitEPnP.constraintMatrix6x10(L_full,y,controlWorldPts,nullPts);
// compute 4 solutions using the null points
estimateCase1(solutions.get(0));
estimateCase2(solutions.get(1));
estimateCase3(solutions.get(2));
// results are bad in general, so skip unless needed
// always considering this case seems to hurt runtime speed a little bit
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);
} | [
"public",
"void",
"process",
"(",
"List",
"<",
"Point3D_F64",
">",
"worldPts",
",",
"List",
"<",
"Point2D_F64",
">",
"observed",
",",
"Se3_F64",
"solutionModel",
")",
"{",
"if",
"(",
"worldPts",
".",
"size",
"(",
")",
"<",
"4",
")",
"throw",
"new",
"Il... | Compute camera motion given a set of features with observations and 3D locations
@param worldPts Known location of features in 3D world coordinates
@param observed Observed location of features in normalized camera coordinates
@param solutionModel Output: Storage for the found solution. | [
"Compute",
"camera",
"motion",
"given",
"a",
"set",
"of",
"features",
"with",
"observations",
"and",
"3D",
"locations"
] | f01c0243da0ec086285ee722183804d5923bc3ac | https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-geo/src/main/java/boofcv/alg/geo/pose/PnPLepetitEPnP.java#L210-L252 | train |
lessthanoptimal/BoofCV | main/boofcv-geo/src/main/java/boofcv/alg/geo/pose/PnPLepetitEPnP.java | PnPLepetitEPnP.computeResultFromBest | 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;
}
// System.out.println(i+" score "+score);
}
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());
} | java | 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;
}
// System.out.println(i+" score "+score);
}
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());
} | [
"private",
"void",
"computeResultFromBest",
"(",
"Se3_F64",
"solutionModel",
")",
"{",
"double",
"bestScore",
"=",
"Double",
".",
"MAX_VALUE",
";",
"int",
"bestSolution",
"=",
"-",
"1",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"numControl",
... | Selects the best motion hypothesis based on the actual observations and optionally
optimizes the solution. | [
"Selects",
"the",
"best",
"motion",
"hypothesis",
"based",
"on",
"the",
"actual",
"observations",
"and",
"optionally",
"optimizes",
"the",
"solution",
"."
] | f01c0243da0ec086285ee722183804d5923bc3ac | https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-geo/src/main/java/boofcv/alg/geo/pose/PnPLepetitEPnP.java#L258-L279 | train |
lessthanoptimal/BoofCV | main/boofcv-geo/src/main/java/boofcv/alg/geo/pose/PnPLepetitEPnP.java | PnPLepetitEPnP.score | 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;
} | java | 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;
} | [
"private",
"double",
"score",
"(",
"double",
"betas",
"[",
"]",
")",
"{",
"UtilLepetitEPnP",
".",
"computeCameraControl",
"(",
"betas",
",",
"nullPts",
",",
"solutionPts",
",",
"numControl",
")",
";",
"int",
"index",
"=",
"0",
";",
"double",
"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. | [
"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",... | f01c0243da0ec086285ee722183804d5923bc3ac | https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-geo/src/main/java/boofcv/alg/geo/pose/PnPLepetitEPnP.java#L287-L304 | train |
lessthanoptimal/BoofCV | main/boofcv-geo/src/main/java/boofcv/alg/geo/pose/PnPLepetitEPnP.java | PnPLepetitEPnP.selectWorldControlPoints | public void selectWorldControlPoints(List<Point3D_F64> worldPts, FastQueue<Point3D_F64> controlWorldPts) {
UtilPoint3D_F64.mean(worldPts,meanWorldPts);
// covariance matrix elements, summed up here for speed
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);
// find the data's orientation and check to see if it is planar
svd.decompose(covar);
double []singularValues = svd.getSingularValues();
DMatrixRMaj V = svd.getV(null,false);
SingularOps_DDRM.descendingOrder(null,false,singularValues,3,V,false);
// planar check
if( singularValues[0]<singularValues[2]*1e13 ) {
numControl = 4;
} else {
numControl = 3;
}
// put control points along the data's major axises
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);
}
// set a control point to be the centroid
controlWorldPts.grow().set(meanWorldPts.x, meanWorldPts.y, meanWorldPts.z);
} | java | public void selectWorldControlPoints(List<Point3D_F64> worldPts, FastQueue<Point3D_F64> controlWorldPts) {
UtilPoint3D_F64.mean(worldPts,meanWorldPts);
// covariance matrix elements, summed up here for speed
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);
// find the data's orientation and check to see if it is planar
svd.decompose(covar);
double []singularValues = svd.getSingularValues();
DMatrixRMaj V = svd.getV(null,false);
SingularOps_DDRM.descendingOrder(null,false,singularValues,3,V,false);
// planar check
if( singularValues[0]<singularValues[2]*1e13 ) {
numControl = 4;
} else {
numControl = 3;
}
// put control points along the data's major axises
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);
}
// set a control point to be the centroid
controlWorldPts.grow().set(meanWorldPts.x, meanWorldPts.y, meanWorldPts.z);
} | [
"public",
"void",
"selectWorldControlPoints",
"(",
"List",
"<",
"Point3D_F64",
">",
"worldPts",
",",
"FastQueue",
"<",
"Point3D_F64",
">",
"controlWorldPts",
")",
"{",
"UtilPoint3D_F64",
".",
"mean",
"(",
"worldPts",
",",
"meanWorldPts",
")",
";",
"// covariance m... | 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.
The data's axis is determined by computing the covariance matrix then performing SVD. The axis
is contained along the | [
"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",
"."
] | f01c0243da0ec086285ee722183804d5923bc3ac | https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-geo/src/main/java/boofcv/alg/geo/pose/PnPLepetitEPnP.java#L314-L364 | train |
lessthanoptimal/BoofCV | main/boofcv-geo/src/main/java/boofcv/alg/geo/pose/PnPLepetitEPnP.java | PnPLepetitEPnP.constructM | 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);
}
}
} | java | 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);
}
}
} | [
"protected",
"static",
"void",
"constructM",
"(",
"List",
"<",
"Point2D_F64",
">",
"obsPts",
",",
"DMatrixRMaj",
"alphas",
",",
"DMatrixRMaj",
"M",
")",
"{",
"int",
"N",
"=",
"obsPts",
".",
"size",
"(",
")",
";",
"M",
".",
"reshape",
"(",
"3",
"*",
"... | Constructs the linear system which is to be solved.
sum a_ij*x_j - a_ij*u_i*z_j = 0
sum a_ij*y_j - a_ij*v_i*z_j = 0
where (x,y,z) is the control point to be solved for.
(u,v) is the observed normalized point | [
"Constructs",
"the",
"linear",
"system",
"which",
"is",
"to",
"be",
"solved",
"."
] | f01c0243da0ec086285ee722183804d5923bc3ac | https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-geo/src/main/java/boofcv/alg/geo/pose/PnPLepetitEPnP.java#L429-L452 | train |
lessthanoptimal/BoofCV | main/boofcv-geo/src/main/java/boofcv/alg/geo/pose/PnPLepetitEPnP.java | PnPLepetitEPnP.matchScale | protected double matchScale( List<Point3D_F64> nullPts ,
FastQueue<Point3D_F64> controlWorldPts ) {
Point3D_F64 meanNull = UtilPoint3D_F64.mean(nullPts,numControl,null);
Point3D_F64 meanWorld = UtilPoint3D_F64.mean(controlWorldPts.toList(),numControl,null);
// compute the ratio of distance between world and null points from the centroid
double top = 0;
double bottom = 0;
for( int i = 0; i < numControl; i++ ) {
Point3D_F64 wi = controlWorldPts.get(i);
Point3D_F64 ni = nullPts.get(i);
double dwx = wi.x-meanWorld.x;
double dwy = wi.y-meanWorld.y;
double dwz = wi.z-meanWorld.z;
double dnx = ni.x-meanNull.x;
double dny = ni.y-meanNull.y;
double dnz = ni.z-meanNull.z;
double n2 = dnx*dnx + dny*dny + dnz*dnz;
double w2 = dwx*dwx + dwy*dwy + dwz*dwz;
top += w2;
bottom += n2;
}
// compute beta
return Math.sqrt(top/bottom);
} | java | protected double matchScale( List<Point3D_F64> nullPts ,
FastQueue<Point3D_F64> controlWorldPts ) {
Point3D_F64 meanNull = UtilPoint3D_F64.mean(nullPts,numControl,null);
Point3D_F64 meanWorld = UtilPoint3D_F64.mean(controlWorldPts.toList(),numControl,null);
// compute the ratio of distance between world and null points from the centroid
double top = 0;
double bottom = 0;
for( int i = 0; i < numControl; i++ ) {
Point3D_F64 wi = controlWorldPts.get(i);
Point3D_F64 ni = nullPts.get(i);
double dwx = wi.x-meanWorld.x;
double dwy = wi.y-meanWorld.y;
double dwz = wi.z-meanWorld.z;
double dnx = ni.x-meanNull.x;
double dny = ni.y-meanNull.y;
double dnz = ni.z-meanNull.z;
double n2 = dnx*dnx + dny*dny + dnz*dnz;
double w2 = dwx*dwx + dwy*dwy + dwz*dwz;
top += w2;
bottom += n2;
}
// compute beta
return Math.sqrt(top/bottom);
} | [
"protected",
"double",
"matchScale",
"(",
"List",
"<",
"Point3D_F64",
">",
"nullPts",
",",
"FastQueue",
"<",
"Point3D_F64",
">",
"controlWorldPts",
")",
"{",
"Point3D_F64",
"meanNull",
"=",
"UtilPoint3D_F64",
".",
"mean",
"(",
"nullPts",
",",
"numControl",
",",
... | Examines the distance each point is from the centroid to determine the scaling difference
between world control points and the null points. | [
"Examines",
"the",
"distance",
"each",
"point",
"is",
"from",
"the",
"centroid",
"to",
"determine",
"the",
"scaling",
"difference",
"between",
"world",
"control",
"points",
"and",
"the",
"null",
"points",
"."
] | f01c0243da0ec086285ee722183804d5923bc3ac | https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-geo/src/main/java/boofcv/alg/geo/pose/PnPLepetitEPnP.java#L483-L514 | train |
lessthanoptimal/BoofCV | main/boofcv-geo/src/main/java/boofcv/alg/geo/pose/PnPLepetitEPnP.java | PnPLepetitEPnP.adjustBetaSign | 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;
} | java | 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;
} | [
"private",
"double",
"adjustBetaSign",
"(",
"double",
"beta",
",",
"List",
"<",
"Point3D_F64",
">",
"nullPts",
")",
"{",
"if",
"(",
"beta",
"==",
"0",
")",
"return",
"0",
";",
"int",
"N",
"=",
"alphas",
".",
"numRows",
";",
"int",
"positiveCount",
"=",... | Use the positive depth constraint to determine the sign of beta | [
"Use",
"the",
"positive",
"depth",
"constraint",
"to",
"determine",
"the",
"sign",
"of",
"beta"
] | f01c0243da0ec086285ee722183804d5923bc3ac | https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-geo/src/main/java/boofcv/alg/geo/pose/PnPLepetitEPnP.java#L519-L542 | train |
lessthanoptimal/BoofCV | main/boofcv-geo/src/main/java/boofcv/alg/geo/pose/PnPLepetitEPnP.java | PnPLepetitEPnP.estimateCase1 | 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;
} | java | 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;
} | [
"protected",
"void",
"estimateCase1",
"(",
"double",
"betas",
"[",
"]",
")",
"{",
"betas",
"[",
"0",
"]",
"=",
"matchScale",
"(",
"nullPts",
"[",
"0",
"]",
",",
"controlWorldPts",
")",
";",
"betas",
"[",
"0",
"]",
"=",
"adjustBetaSign",
"(",
"betas",
... | Simple analytical solution. Just need to solve for the scale difference in one set
of potential control points. | [
"Simple",
"analytical",
"solution",
".",
"Just",
"need",
"to",
"solve",
"for",
"the",
"scale",
"difference",
"in",
"one",
"set",
"of",
"potential",
"control",
"points",
"."
] | f01c0243da0ec086285ee722183804d5923bc3ac | https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-geo/src/main/java/boofcv/alg/geo/pose/PnPLepetitEPnP.java#L574-L578 | train |
lessthanoptimal/BoofCV | main/boofcv-geo/src/main/java/boofcv/alg/geo/pose/PnPLepetitEPnP.java | PnPLepetitEPnP.estimateCase3_planar | protected void estimateCase3_planar( double betas[] ) {
relinearizeBeta.setNumberControl(3);
relinearizeBeta.process(L_full,y,betas);
refine(betas);
} | java | protected void estimateCase3_planar( double betas[] ) {
relinearizeBeta.setNumberControl(3);
relinearizeBeta.process(L_full,y,betas);
refine(betas);
} | [
"protected",
"void",
"estimateCase3_planar",
"(",
"double",
"betas",
"[",
"]",
")",
"{",
"relinearizeBeta",
".",
"setNumberControl",
"(",
"3",
")",
";",
"relinearizeBeta",
".",
"process",
"(",
"L_full",
",",
"y",
",",
"betas",
")",
";",
"refine",
"(",
"bet... | If the data is planar use relinearize to estimate betas | [
"If",
"the",
"data",
"is",
"planar",
"use",
"relinearize",
"to",
"estimate",
"betas"
] | f01c0243da0ec086285ee722183804d5923bc3ac | https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-geo/src/main/java/boofcv/alg/geo/pose/PnPLepetitEPnP.java#L629-L634 | train |
lessthanoptimal/BoofCV | main/boofcv-geo/src/main/java/boofcv/alg/geo/pose/PnPLepetitEPnP.java | PnPLepetitEPnP.gaussNewton | private void gaussNewton( double betas[] ) {
A_temp.reshape(L_full.numRows, numControl);
v_temp.reshape(L_full.numRows, 1);
x.reshape(numControl,1,false);
// don't check numControl inside in hope that the JVM can optimize the code better
if( numControl == 4 ) {
for( int i = 0; i < numIterations; i++ ) {
UtilLepetitEPnP.jacobian_Control4(L_full,betas, A_temp);
UtilLepetitEPnP.residuals_Control4(L_full,y,betas,v_temp.data);
if( !solver.setA(A_temp) )
return;
solver.solve(v_temp,x);
for( int j = 0; j < numControl; j++ ) {
betas[j] -= x.data[j];
}
}
} else {
for( int i = 0; i < numIterations; i++ ) {
UtilLepetitEPnP.jacobian_Control3(L_full,betas, A_temp);
UtilLepetitEPnP.residuals_Control3(L_full,y,betas,v_temp.data);
if( !solver.setA(A_temp) )
return;
solver.solve(v_temp,x);
for( int j = 0; j < numControl; j++ ) {
betas[j] -= x.data[j];
}
}
}
} | java | private void gaussNewton( double betas[] ) {
A_temp.reshape(L_full.numRows, numControl);
v_temp.reshape(L_full.numRows, 1);
x.reshape(numControl,1,false);
// don't check numControl inside in hope that the JVM can optimize the code better
if( numControl == 4 ) {
for( int i = 0; i < numIterations; i++ ) {
UtilLepetitEPnP.jacobian_Control4(L_full,betas, A_temp);
UtilLepetitEPnP.residuals_Control4(L_full,y,betas,v_temp.data);
if( !solver.setA(A_temp) )
return;
solver.solve(v_temp,x);
for( int j = 0; j < numControl; j++ ) {
betas[j] -= x.data[j];
}
}
} else {
for( int i = 0; i < numIterations; i++ ) {
UtilLepetitEPnP.jacobian_Control3(L_full,betas, A_temp);
UtilLepetitEPnP.residuals_Control3(L_full,y,betas,v_temp.data);
if( !solver.setA(A_temp) )
return;
solver.solve(v_temp,x);
for( int j = 0; j < numControl; j++ ) {
betas[j] -= x.data[j];
}
}
}
} | [
"private",
"void",
"gaussNewton",
"(",
"double",
"betas",
"[",
"]",
")",
"{",
"A_temp",
".",
"reshape",
"(",
"L_full",
".",
"numRows",
",",
"numControl",
")",
";",
"v_temp",
".",
"reshape",
"(",
"L_full",
".",
"numRows",
",",
"1",
")",
";",
"x",
".",... | Optimize beta values using Gauss Newton.
@param betas Beta values being optimized. | [
"Optimize",
"beta",
"values",
"using",
"Gauss",
"Newton",
"."
] | f01c0243da0ec086285ee722183804d5923bc3ac | https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-geo/src/main/java/boofcv/alg/geo/pose/PnPLepetitEPnP.java#L649-L685 | train |
lessthanoptimal/BoofCV | main/boofcv-recognition/src/main/java/boofcv/alg/fiducial/qrcode/QrCodeEncoder.java | QrCodeEncoder.addAutomatic | public QrCodeEncoder addAutomatic(String message) {
// very simple coding algorithm. Doesn't try to compress by using multiple formats
if(containsKanji(message)) {
// split into kanji and non-kanji segments
int start = 0;
boolean kanji = isKanji(message.charAt(0));
for (int i = 0; i < message.length(); i++) {
if( isKanji(message.charAt(i))) {
if( !kanji ) {
addAutomatic(message.substring(start,i));
start = i;
kanji = true;
}
} else {
if( kanji ) {
addKanji(message.substring(start,i));
start = i;
kanji = false;
}
}
}
if( kanji ) {
addKanji(message.substring(start,message.length()));
} else {
addAutomatic(message.substring(start,message.length()));
}
return this;
} else if( containsByte(message)) {
return addBytes(message);
} else if( containsAlphaNumeric(message)) {
return addAlphanumeric(message);
} else {
return addNumeric(message);
}
} | java | public QrCodeEncoder addAutomatic(String message) {
// very simple coding algorithm. Doesn't try to compress by using multiple formats
if(containsKanji(message)) {
// split into kanji and non-kanji segments
int start = 0;
boolean kanji = isKanji(message.charAt(0));
for (int i = 0; i < message.length(); i++) {
if( isKanji(message.charAt(i))) {
if( !kanji ) {
addAutomatic(message.substring(start,i));
start = i;
kanji = true;
}
} else {
if( kanji ) {
addKanji(message.substring(start,i));
start = i;
kanji = false;
}
}
}
if( kanji ) {
addKanji(message.substring(start,message.length()));
} else {
addAutomatic(message.substring(start,message.length()));
}
return this;
} else if( containsByte(message)) {
return addBytes(message);
} else if( containsAlphaNumeric(message)) {
return addAlphanumeric(message);
} else {
return addNumeric(message);
}
} | [
"public",
"QrCodeEncoder",
"addAutomatic",
"(",
"String",
"message",
")",
"{",
"// very simple coding algorithm. Doesn't try to compress by using multiple formats",
"if",
"(",
"containsKanji",
"(",
"message",
")",
")",
"{",
"// split into kanji and non-kanji segments",
"int",
"... | Select the encoding based on the letters in the message. A very simple algorithm is used internally. | [
"Select",
"the",
"encoding",
"based",
"on",
"the",
"letters",
"in",
"the",
"message",
".",
"A",
"very",
"simple",
"algorithm",
"is",
"used",
"internally",
"."
] | f01c0243da0ec086285ee722183804d5923bc3ac | https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-recognition/src/main/java/boofcv/alg/fiducial/qrcode/QrCodeEncoder.java#L121-L155 | train |
lessthanoptimal/BoofCV | main/boofcv-recognition/src/main/java/boofcv/alg/fiducial/qrcode/QrCodeEncoder.java | QrCodeEncoder.addAlphanumeric | 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;
} | java | 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;
} | [
"public",
"QrCodeEncoder",
"addAlphanumeric",
"(",
"String",
"alphaNumeric",
")",
"{",
"byte",
"values",
"[",
"]",
"=",
"alphanumericToValues",
"(",
"alphaNumeric",
")",
";",
"MessageSegment",
"segment",
"=",
"new",
"MessageSegment",
"(",
")",
";",
"segment",
".... | Creates a QR-Code which encodes data in the alphanumeric format
@param alphaNumeric String containing only alphanumeric values.
@return The QR-Code | [
"Creates",
"a",
"QR",
"-",
"Code",
"which",
"encodes",
"data",
"in",
"the",
"alphanumeric",
"format"
] | f01c0243da0ec086285ee722183804d5923bc3ac | https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-recognition/src/main/java/boofcv/alg/fiducial/qrcode/QrCodeEncoder.java#L274-L292 | train |
lessthanoptimal/BoofCV | main/boofcv-recognition/src/main/java/boofcv/alg/fiducial/qrcode/QrCodeEncoder.java | QrCodeEncoder.addBytes | 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;
} | java | 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;
} | [
"public",
"QrCodeEncoder",
"addBytes",
"(",
"byte",
"[",
"]",
"data",
")",
"{",
"StringBuilder",
"builder",
"=",
"new",
"StringBuilder",
"(",
"data",
".",
"length",
")",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"data",
".",
"length",
";"... | Creates a QR-Code which encodes data in the byte format.
@param data Data to be encoded
@return The QR-Code | [
"Creates",
"a",
"QR",
"-",
"Code",
"which",
"encodes",
"data",
"in",
"the",
"byte",
"format",
"."
] | f01c0243da0ec086285ee722183804d5923bc3ac | https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-recognition/src/main/java/boofcv/alg/fiducial/qrcode/QrCodeEncoder.java#L347-L365 | train |
lessthanoptimal/BoofCV | main/boofcv-recognition/src/main/java/boofcv/alg/fiducial/qrcode/QrCodeEncoder.java | QrCodeEncoder.addKanji | 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;
} | java | 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;
} | [
"public",
"QrCodeEncoder",
"addKanji",
"(",
"String",
"message",
")",
"{",
"byte",
"[",
"]",
"bytes",
";",
"try",
"{",
"bytes",
"=",
"message",
".",
"getBytes",
"(",
"\"Shift_JIS\"",
")",
";",
"}",
"catch",
"(",
"UnsupportedEncodingException",
"ex",
")",
"... | Creates a QR-Code which encodes Kanji characters
@param message Data to be encoded
@return The QR-Code | [
"Creates",
"a",
"QR",
"-",
"Code",
"which",
"encodes",
"Kanji",
"characters"
] | f01c0243da0ec086285ee722183804d5923bc3ac | https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-recognition/src/main/java/boofcv/alg/fiducial/qrcode/QrCodeEncoder.java#L390-L410 | train |
lessthanoptimal/BoofCV | main/boofcv-recognition/src/main/java/boofcv/alg/fiducial/qrcode/QrCodeEncoder.java | QrCodeEncoder.getLengthBits | 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;
} | java | 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;
} | [
"private",
"static",
"int",
"getLengthBits",
"(",
"int",
"version",
",",
"int",
"bitsA",
",",
"int",
"bitsB",
",",
"int",
"bitsC",
")",
"{",
"int",
"lengthBits",
";",
"if",
"(",
"version",
"<",
"10",
")",
"lengthBits",
"=",
"bitsA",
";",
"else",
"if",
... | Returns the length of the message length variable in bits. Dependent on version | [
"Returns",
"the",
"length",
"of",
"the",
"message",
"length",
"variable",
"in",
"bits",
".",
"Dependent",
"on",
"version"
] | f01c0243da0ec086285ee722183804d5923bc3ac | https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-recognition/src/main/java/boofcv/alg/fiducial/qrcode/QrCodeEncoder.java#L459-L469 | train |
lessthanoptimal/BoofCV | main/boofcv-recognition/src/main/java/boofcv/alg/fiducial/qrcode/QrCodeEncoder.java | QrCodeEncoder.fixate | public QrCode fixate() {
autoSelectVersionAndError();
// sanity check of code
int expectedBitSize = bitsAtVersion(qr.version);
qr.message = "";
for( MessageSegment m : segments ) {
qr.message += m.message;
switch( m.mode ) {
case NUMERIC:encodeNumeric(m.data,m.length);break;
case ALPHANUMERIC:encodeAlphanumeric(m.data,m.length);break;
case BYTE:encodeBytes(m.data,m.length);break;
case KANJI:encodeKanji(m.data,m.length);break;
default:
throw new RuntimeException("Unknown");
}
}
if( packed.size != expectedBitSize )
throw new RuntimeException("Bad size code. "+packed.size+" vs "+expectedBitSize);
int maxBits = QrCode.VERSION_INFO[qr.version].codewords * 8;
if (packed.size > maxBits) {
throw new IllegalArgumentException("The message is longer than the max possible size");
}
if (packed.size + 4 <= maxBits) {
// add the terminator to the bit stream
packed.append(0b0000, 4, false);
}
bitsToMessage(packed);
if (autoMask) {
qr.mask = selectMask(qr);
}
return qr;
} | java | public QrCode fixate() {
autoSelectVersionAndError();
// sanity check of code
int expectedBitSize = bitsAtVersion(qr.version);
qr.message = "";
for( MessageSegment m : segments ) {
qr.message += m.message;
switch( m.mode ) {
case NUMERIC:encodeNumeric(m.data,m.length);break;
case ALPHANUMERIC:encodeAlphanumeric(m.data,m.length);break;
case BYTE:encodeBytes(m.data,m.length);break;
case KANJI:encodeKanji(m.data,m.length);break;
default:
throw new RuntimeException("Unknown");
}
}
if( packed.size != expectedBitSize )
throw new RuntimeException("Bad size code. "+packed.size+" vs "+expectedBitSize);
int maxBits = QrCode.VERSION_INFO[qr.version].codewords * 8;
if (packed.size > maxBits) {
throw new IllegalArgumentException("The message is longer than the max possible size");
}
if (packed.size + 4 <= maxBits) {
// add the terminator to the bit stream
packed.append(0b0000, 4, false);
}
bitsToMessage(packed);
if (autoMask) {
qr.mask = selectMask(qr);
}
return qr;
} | [
"public",
"QrCode",
"fixate",
"(",
")",
"{",
"autoSelectVersionAndError",
"(",
")",
";",
"// sanity check of code",
"int",
"expectedBitSize",
"=",
"bitsAtVersion",
"(",
"qr",
".",
"version",
")",
";",
"qr",
".",
"message",
"=",
"\"\"",
";",
"for",
"(",
"Mess... | Call this function after you are done adding to the QR code
@return The generated QR Code | [
"Call",
"this",
"function",
"after",
"you",
"are",
"done",
"adding",
"to",
"the",
"QR",
"code"
] | f01c0243da0ec086285ee722183804d5923bc3ac | https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-recognition/src/main/java/boofcv/alg/fiducial/qrcode/QrCodeEncoder.java#L481-L521 | train |
lessthanoptimal/BoofCV | main/boofcv-recognition/src/main/java/boofcv/alg/fiducial/qrcode/QrCodeEncoder.java | QrCodeEncoder.selectMask | static QrCodeMaskPattern selectMask( QrCode qr ) {
int N = qr.getNumberOfModules();
int totalBytes = QrCode.VERSION_INFO[qr.version].codewords;
List<Point2D_I32> locations = QrCode.LOCATION_BITS[qr.version];
QrCodeMaskPattern bestMask = null;
double bestScore = Double.MAX_VALUE;
PackedBits8 bits = new PackedBits8();
bits.size = totalBytes * 8;
bits.data = qr.rawbits;
if (bits.size > locations.size())
throw new RuntimeException("BUG in code");
// Bit value of 0 = white. 1 = black
QrCodeCodeWordLocations matrix = new QrCodeCodeWordLocations(qr.version);
for (QrCodeMaskPattern mask : QrCodeMaskPattern.values()) {
double score = scoreMask(N, locations, bits, matrix, mask);
if (score < bestScore) {
bestScore = score;
bestMask = mask;
}
}
return bestMask;
} | java | static QrCodeMaskPattern selectMask( QrCode qr ) {
int N = qr.getNumberOfModules();
int totalBytes = QrCode.VERSION_INFO[qr.version].codewords;
List<Point2D_I32> locations = QrCode.LOCATION_BITS[qr.version];
QrCodeMaskPattern bestMask = null;
double bestScore = Double.MAX_VALUE;
PackedBits8 bits = new PackedBits8();
bits.size = totalBytes * 8;
bits.data = qr.rawbits;
if (bits.size > locations.size())
throw new RuntimeException("BUG in code");
// Bit value of 0 = white. 1 = black
QrCodeCodeWordLocations matrix = new QrCodeCodeWordLocations(qr.version);
for (QrCodeMaskPattern mask : QrCodeMaskPattern.values()) {
double score = scoreMask(N, locations, bits, matrix, mask);
if (score < bestScore) {
bestScore = score;
bestMask = mask;
}
}
return bestMask;
} | [
"static",
"QrCodeMaskPattern",
"selectMask",
"(",
"QrCode",
"qr",
")",
"{",
"int",
"N",
"=",
"qr",
".",
"getNumberOfModules",
"(",
")",
";",
"int",
"totalBytes",
"=",
"QrCode",
".",
"VERSION_INFO",
"[",
"qr",
".",
"version",
"]",
".",
"codewords",
";",
"... | 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. | [
"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",
... | f01c0243da0ec086285ee722183804d5923bc3ac | https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-recognition/src/main/java/boofcv/alg/fiducial/qrcode/QrCodeEncoder.java#L528-L553 | train |
lessthanoptimal/BoofCV | main/boofcv-recognition/src/main/java/boofcv/alg/fiducial/qrcode/QrCodeEncoder.java | QrCodeEncoder.detectAdjacentAndPositionPatterns | static void detectAdjacentAndPositionPatterns(int N, QrCodeCodeWordLocations matrix, FoundFeatures features) {
for (int foo = 0; foo < 2; foo++) {
for (int row = 0; row < N; row++) {
int index = row * N;
for (int col = 1; col < N; col++, index++) {
if (matrix.data[index] == matrix.data[index + 1])
features.adjacent++;
}
index = row * N;
for (int col = 6; col < N; col++, index++) {
if (matrix.data[index] && !matrix.data[index + 1] &&
matrix.data[index + 2] && matrix.data[index + 3] && matrix.data[index + 4] &&
!matrix.data[index + 5] && matrix.data[index + 6])
features.position++;
}
}
CommonOps_BDRM.transposeSquare(matrix);
}
// subtract out false positives by the mask applied to position patterns, timing, mode
features.adjacent -= 8*9 + 2*9*8 + (N-18)*2;
} | java | static void detectAdjacentAndPositionPatterns(int N, QrCodeCodeWordLocations matrix, FoundFeatures features) {
for (int foo = 0; foo < 2; foo++) {
for (int row = 0; row < N; row++) {
int index = row * N;
for (int col = 1; col < N; col++, index++) {
if (matrix.data[index] == matrix.data[index + 1])
features.adjacent++;
}
index = row * N;
for (int col = 6; col < N; col++, index++) {
if (matrix.data[index] && !matrix.data[index + 1] &&
matrix.data[index + 2] && matrix.data[index + 3] && matrix.data[index + 4] &&
!matrix.data[index + 5] && matrix.data[index + 6])
features.position++;
}
}
CommonOps_BDRM.transposeSquare(matrix);
}
// subtract out false positives by the mask applied to position patterns, timing, mode
features.adjacent -= 8*9 + 2*9*8 + (N-18)*2;
} | [
"static",
"void",
"detectAdjacentAndPositionPatterns",
"(",
"int",
"N",
",",
"QrCodeCodeWordLocations",
"matrix",
",",
"FoundFeatures",
"features",
")",
"{",
"for",
"(",
"int",
"foo",
"=",
"0",
";",
"foo",
"<",
"2",
";",
"foo",
"++",
")",
"{",
"for",
"(",
... | 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 | [
"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"
] | f01c0243da0ec086285ee722183804d5923bc3ac | https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-recognition/src/main/java/boofcv/alg/fiducial/qrcode/QrCodeEncoder.java#L606-L628 | train |
lessthanoptimal/BoofCV | main/boofcv-recognition/src/main/java/boofcv/alg/fiducial/qrcode/QrCodeEncoder.java | QrCodeEncoder.bitsAtVersion | private int bitsAtVersion( int version ) {
int total = 0;
for (int i = 0; i < segments.size(); i++) {
total += segments.get(i).sizeInBits(version);
}
return total;
} | java | private int bitsAtVersion( int version ) {
int total = 0;
for (int i = 0; i < segments.size(); i++) {
total += segments.get(i).sizeInBits(version);
}
return total;
} | [
"private",
"int",
"bitsAtVersion",
"(",
"int",
"version",
")",
"{",
"int",
"total",
"=",
"0",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"segments",
".",
"size",
"(",
")",
";",
"i",
"++",
")",
"{",
"total",
"+=",
"segments",
".",
"ge... | Computes how many bits it takes to encode the message at this version number
@param version
@return | [
"Computes",
"how",
"many",
"bits",
"it",
"takes",
"to",
"encode",
"the",
"message",
"at",
"this",
"version",
"number"
] | f01c0243da0ec086285ee722183804d5923bc3ac | https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-recognition/src/main/java/boofcv/alg/fiducial/qrcode/QrCodeEncoder.java#L690-L696 | train |
lessthanoptimal/BoofCV | main/boofcv-geo/src/main/java/boofcv/alg/geo/f/EpipolarMinimizeGeometricError.java | EpipolarMinimizeGeometricError.process | public boolean process(DMatrixRMaj F21 ,
double x1 , double y1, double x2, double y2,
Point2D_F64 p1 , Point2D_F64 p2 )
{
// translations used to move points to the origin
assignTinv(T1,x1,y1);
assignTinv(T2,x2,y2);
// take F to the new coordinate system
// F1 = T2'*F*T1
PerspectiveOps.multTranA(T2,F21,T1,Ft);
extract.process(Ft,e1,e2);
// normalize so that e[x]*e[x] + e[y]*e[y] == 1
normalizeEpipole(e1);
normalizeEpipole(e2);
assignR(R1,e1);
assignR(R2,e2);
// Ft = R2*Ft*R1'
PerspectiveOps.multTranC(R2,Ft,R1,Ft);
double f1 = e1.z;
double f2 = e2.z;
double a = Ft.get(1,1);
double b = Ft.get(1,2);
double c = Ft.get(2,1);
double d = Ft.get(2,2);
if( !solvePolynomial(f1,f2,a,b,c,d))
return false;
if( !selectBestSolution(rootFinder.getRoots(),f1,f2,a,b,c,d))
return false;
// find the closeset point on the two lines below to the origin
double t = solutionT;
l1.set(t*f1,1,-t);
l2.set(-f2*(c*t+d),a*t+b,c*t+d);
closestPointToOrigin(l1,e1); // recycle epipole storage
closestPointToOrigin(l2,e2);
// original coordinates
originalCoordinates(T1,R1,e1);
originalCoordinates(T2,R2,e2);
// back to 2D coordinates
p1.set(e1.x/e1.z, e1.y/e1.z);
p2.set(e2.x/e2.z, e2.y/e2.z);
return true;
} | java | public boolean process(DMatrixRMaj F21 ,
double x1 , double y1, double x2, double y2,
Point2D_F64 p1 , Point2D_F64 p2 )
{
// translations used to move points to the origin
assignTinv(T1,x1,y1);
assignTinv(T2,x2,y2);
// take F to the new coordinate system
// F1 = T2'*F*T1
PerspectiveOps.multTranA(T2,F21,T1,Ft);
extract.process(Ft,e1,e2);
// normalize so that e[x]*e[x] + e[y]*e[y] == 1
normalizeEpipole(e1);
normalizeEpipole(e2);
assignR(R1,e1);
assignR(R2,e2);
// Ft = R2*Ft*R1'
PerspectiveOps.multTranC(R2,Ft,R1,Ft);
double f1 = e1.z;
double f2 = e2.z;
double a = Ft.get(1,1);
double b = Ft.get(1,2);
double c = Ft.get(2,1);
double d = Ft.get(2,2);
if( !solvePolynomial(f1,f2,a,b,c,d))
return false;
if( !selectBestSolution(rootFinder.getRoots(),f1,f2,a,b,c,d))
return false;
// find the closeset point on the two lines below to the origin
double t = solutionT;
l1.set(t*f1,1,-t);
l2.set(-f2*(c*t+d),a*t+b,c*t+d);
closestPointToOrigin(l1,e1); // recycle epipole storage
closestPointToOrigin(l2,e2);
// original coordinates
originalCoordinates(T1,R1,e1);
originalCoordinates(T2,R2,e2);
// back to 2D coordinates
p1.set(e1.x/e1.z, e1.y/e1.z);
p2.set(e2.x/e2.z, e2.y/e2.z);
return true;
} | [
"public",
"boolean",
"process",
"(",
"DMatrixRMaj",
"F21",
",",
"double",
"x1",
",",
"double",
"y1",
",",
"double",
"x2",
",",
"double",
"y2",
",",
"Point2D_F64",
"p1",
",",
"Point2D_F64",
"p2",
")",
"{",
"// translations used to move points to the origin",
"ass... | Minimizes the geometric error
@param F21 (Input) Fundamental matrix x2 * F21 * x1 == 0
@param x1 (Input) Point 1 x-coordinate. Pixels
@param y1 (Input) Point 1 y-coordinate. Pixels
@param x2 (Input) Point 2 x-coordinate. Pixels
@param y2 (Input) Point 2 y-coordinate. Pixels
@param p1 (Output) Point 1. Pixels
@param p2 (Output) Point 2. Pixels
@return true if a solution was found or false if it failed | [
"Minimizes",
"the",
"geometric",
"error"
] | f01c0243da0ec086285ee722183804d5923bc3ac | https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-geo/src/main/java/boofcv/alg/geo/f/EpipolarMinimizeGeometricError.java#L87-L140 | train |
lessthanoptimal/BoofCV | main/boofcv-feature/src/main/java/boofcv/alg/shapes/polygon/UtilShapePolygon.java | UtilShapePolygon.convert | 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;
} | java | 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;
} | [
"public",
"static",
"boolean",
"convert",
"(",
"LineGeneral2D_F64",
"[",
"]",
"lines",
",",
"Polygon2D_F64",
"poly",
")",
"{",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"poly",
".",
"size",
"(",
")",
";",
"i",
"++",
")",
"{",
"int",
"j",
"... | Finds the intersections between the four lines and converts it into a quadrilateral
@param lines Assumes lines are ordered | [
"Finds",
"the",
"intersections",
"between",
"the",
"four",
"lines",
"and",
"converts",
"it",
"into",
"a",
"quadrilateral"
] | f01c0243da0ec086285ee722183804d5923bc3ac | https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-feature/src/main/java/boofcv/alg/shapes/polygon/UtilShapePolygon.java#L37-L46 | train |
lessthanoptimal/BoofCV | main/boofcv-ip/src/main/java/boofcv/alg/filter/derivative/DerivativeLaplacian.java | DerivativeLaplacian.process | public static void process(GrayU8 orig, GrayF32 deriv) {
deriv.reshape(orig.width,orig.height);
if( BoofConcurrency.USE_CONCURRENT ) {
DerivativeLaplacian_Inner_MT.process(orig,deriv);
} else {
DerivativeLaplacian_Inner.process(orig,deriv);
}
// if( border != null ) {
// border.setImage(orig);
// ConvolveJustBorder_General_SB.convolve(kernel_I32, border,deriv);
// }
} | java | public static void process(GrayU8 orig, GrayF32 deriv) {
deriv.reshape(orig.width,orig.height);
if( BoofConcurrency.USE_CONCURRENT ) {
DerivativeLaplacian_Inner_MT.process(orig,deriv);
} else {
DerivativeLaplacian_Inner.process(orig,deriv);
}
// if( border != null ) {
// border.setImage(orig);
// ConvolveJustBorder_General_SB.convolve(kernel_I32, border,deriv);
// }
} | [
"public",
"static",
"void",
"process",
"(",
"GrayU8",
"orig",
",",
"GrayF32",
"deriv",
")",
"{",
"deriv",
".",
"reshape",
"(",
"orig",
".",
"width",
",",
"orig",
".",
"height",
")",
";",
"if",
"(",
"BoofConcurrency",
".",
"USE_CONCURRENT",
")",
"{",
"D... | Computes Laplacian on an U8 image but outputs derivative in a F32 image. Removes a step when processing
images for feature detection | [
"Computes",
"Laplacian",
"on",
"an",
"U8",
"image",
"but",
"outputs",
"derivative",
"in",
"a",
"F32",
"image",
".",
"Removes",
"a",
"step",
"when",
"processing",
"images",
"for",
"feature",
"detection"
] | f01c0243da0ec086285ee722183804d5923bc3ac | https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-ip/src/main/java/boofcv/alg/filter/derivative/DerivativeLaplacian.java#L93-L106 | train |
lessthanoptimal/BoofCV | main/boofcv-recognition/src/main/java/boofcv/alg/fiducial/calib/squares/SquareCrossClustersIntoGrids.java | SquareCrossClustersIntoGrids.process | 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));
}
} | java | 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));
}
} | [
"public",
"void",
"process",
"(",
"List",
"<",
"List",
"<",
"SquareNode",
">",
">",
"clusters",
")",
"{",
"grids",
".",
"reset",
"(",
")",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"clusters",
".",
"size",
"(",
")",
";",
"i",
"++",
... | Converts all the found clusters into grids, if they are valid.
@param clusters List of clusters | [
"Converts",
"all",
"the",
"found",
"clusters",
"into",
"grids",
"if",
"they",
"are",
"valid",
"."
] | f01c0243da0ec086285ee722183804d5923bc3ac | https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-recognition/src/main/java/boofcv/alg/fiducial/calib/squares/SquareCrossClustersIntoGrids.java#L51-L57 | train |
lessthanoptimal/BoofCV | main/boofcv-recognition/src/main/java/boofcv/alg/fiducial/calib/squares/SquareCrossClustersIntoGrids.java | SquareCrossClustersIntoGrids.checkPreconditions | 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;
} | java | 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;
} | [
"protected",
"boolean",
"checkPreconditions",
"(",
"List",
"<",
"SquareNode",
">",
"cluster",
")",
"{",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"cluster",
".",
"size",
"(",
")",
";",
"i",
"++",
")",
"{",
"SquareNode",
"n",
"=",
"cluster",
... | Checks basic preconditions.
1) No node may be linked two more than once | [
"Checks",
"basic",
"preconditions",
".",
"1",
")",
"No",
"node",
"may",
"be",
"linked",
"two",
"more",
"than",
"once"
] | f01c0243da0ec086285ee722183804d5923bc3ac | https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-recognition/src/main/java/boofcv/alg/fiducial/calib/squares/SquareCrossClustersIntoGrids.java#L63-L81 | train |
lessthanoptimal/BoofCV | main/boofcv-recognition/src/main/java/boofcv/alg/fiducial/calib/squares/SquareCrossClustersIntoGrids.java | SquareCrossClustersIntoGrids.processCluster | protected void processCluster( List<SquareNode> cluster ) {
invalid = false;
// handle a special case
if( cluster.size() == 1 ) {
SquareNode n = cluster.get(0);
if( n.getNumberOfConnections() == 0 ) {
SquareGrid grid = grids.grow();
grid.reset();
grid.columns = grid.rows = 1;
grid.nodes.add(n);
return;
}
}
for (int i = 0; i < cluster.size(); i++) {
cluster.get(i).graph = SquareNode.RESET_GRAPH;
}
SquareNode seed = findSeedNode(cluster);
if( seed == null )
return;
// find the first row
List<SquareNode> firstRow;
if( seed.getNumberOfConnections() == 1 ) {
firstRow = firstRow1(seed);
} else if( seed.getNumberOfConnections() == 2 ) {
firstRow = firstRow2(seed);
} else {
throw new RuntimeException("BUG");
}
if( invalid || firstRow == null )
return;
// Add the next rows to the list, one after another
List<List<SquareNode>> listRows = new ArrayList<>();// TODO remove memory declaration here
listRows.add(firstRow);
while(true ) {
List<SquareNode> previous = listRows.get(listRows.size()-1);
if( !addNextRow(previous.get(0),listRows)) {
break;
}
}
if( invalid || listRows.size() < 2)
return;
// re-organize into a grid data structure
SquareGrid grid = assembleGrid(listRows);
// check the grids connectivity
if( grid == null || !checkEdgeCount(grid) ) {
grids.removeTail();
}
} | java | protected void processCluster( List<SquareNode> cluster ) {
invalid = false;
// handle a special case
if( cluster.size() == 1 ) {
SquareNode n = cluster.get(0);
if( n.getNumberOfConnections() == 0 ) {
SquareGrid grid = grids.grow();
grid.reset();
grid.columns = grid.rows = 1;
grid.nodes.add(n);
return;
}
}
for (int i = 0; i < cluster.size(); i++) {
cluster.get(i).graph = SquareNode.RESET_GRAPH;
}
SquareNode seed = findSeedNode(cluster);
if( seed == null )
return;
// find the first row
List<SquareNode> firstRow;
if( seed.getNumberOfConnections() == 1 ) {
firstRow = firstRow1(seed);
} else if( seed.getNumberOfConnections() == 2 ) {
firstRow = firstRow2(seed);
} else {
throw new RuntimeException("BUG");
}
if( invalid || firstRow == null )
return;
// Add the next rows to the list, one after another
List<List<SquareNode>> listRows = new ArrayList<>();// TODO remove memory declaration here
listRows.add(firstRow);
while(true ) {
List<SquareNode> previous = listRows.get(listRows.size()-1);
if( !addNextRow(previous.get(0),listRows)) {
break;
}
}
if( invalid || listRows.size() < 2)
return;
// re-organize into a grid data structure
SquareGrid grid = assembleGrid(listRows);
// check the grids connectivity
if( grid == null || !checkEdgeCount(grid) ) {
grids.removeTail();
}
} | [
"protected",
"void",
"processCluster",
"(",
"List",
"<",
"SquareNode",
">",
"cluster",
")",
"{",
"invalid",
"=",
"false",
";",
"// handle a special case",
"if",
"(",
"cluster",
".",
"size",
"(",
")",
"==",
"1",
")",
"{",
"SquareNode",
"n",
"=",
"cluster",
... | Converts the cluster into a grid data structure. If its not a grid then
nothing happens | [
"Converts",
"the",
"cluster",
"into",
"a",
"grid",
"data",
"structure",
".",
"If",
"its",
"not",
"a",
"grid",
"then",
"nothing",
"happens"
] | f01c0243da0ec086285ee722183804d5923bc3ac | https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-recognition/src/main/java/boofcv/alg/fiducial/calib/squares/SquareCrossClustersIntoGrids.java#L87-L142 | train |
lessthanoptimal/BoofCV | main/boofcv-recognition/src/main/java/boofcv/alg/fiducial/calib/squares/SquareCrossClustersIntoGrids.java | SquareCrossClustersIntoGrids.assembleGrid | private SquareGrid assembleGrid( List<List<SquareNode>> listRows) {
SquareGrid grid = grids.grow();
grid.reset();
List<SquareNode> row0 = listRows.get(0);
List<SquareNode> row1 = listRows.get(1);
int offset = row0.get(0).getNumberOfConnections() == 1 ? 0 : 1;
grid.columns = row0.size() + row1.size();
grid.rows = listRows.size();
// initialize grid to null
for (int i = 0; i < grid.columns * grid.rows; i++) {
grid.nodes.add(null);
}
// fill in the grid
for (int row = 0; row < listRows.size(); row++) {
List<SquareNode> list = listRows.get(row);
int startCol = offset - row%2 == 0 ? 0 : 1;
// make sure there is the expected number of elements in the row
int adjustedLength = grid.columns-startCol;
if( (adjustedLength)-adjustedLength/2 != list.size() ) {
return null;
}
int listIndex = 0;
for (int col = startCol; col < grid.columns; col += 2) {
grid.set(row,col,list.get(listIndex++));
}
}
return grid;
} | java | private SquareGrid assembleGrid( List<List<SquareNode>> listRows) {
SquareGrid grid = grids.grow();
grid.reset();
List<SquareNode> row0 = listRows.get(0);
List<SquareNode> row1 = listRows.get(1);
int offset = row0.get(0).getNumberOfConnections() == 1 ? 0 : 1;
grid.columns = row0.size() + row1.size();
grid.rows = listRows.size();
// initialize grid to null
for (int i = 0; i < grid.columns * grid.rows; i++) {
grid.nodes.add(null);
}
// fill in the grid
for (int row = 0; row < listRows.size(); row++) {
List<SquareNode> list = listRows.get(row);
int startCol = offset - row%2 == 0 ? 0 : 1;
// make sure there is the expected number of elements in the row
int adjustedLength = grid.columns-startCol;
if( (adjustedLength)-adjustedLength/2 != list.size() ) {
return null;
}
int listIndex = 0;
for (int col = startCol; col < grid.columns; col += 2) {
grid.set(row,col,list.get(listIndex++));
}
}
return grid;
} | [
"private",
"SquareGrid",
"assembleGrid",
"(",
"List",
"<",
"List",
"<",
"SquareNode",
">",
">",
"listRows",
")",
"{",
"SquareGrid",
"grid",
"=",
"grids",
".",
"grow",
"(",
")",
";",
"grid",
".",
"reset",
"(",
")",
";",
"List",
"<",
"SquareNode",
">",
... | Converts the list of rows into a grid. Since it is a chessboard pattern some of the grid
elements will be null. | [
"Converts",
"the",
"list",
"of",
"rows",
"into",
"a",
"grid",
".",
"Since",
"it",
"is",
"a",
"chessboard",
"pattern",
"some",
"of",
"the",
"grid",
"elements",
"will",
"be",
"null",
"."
] | f01c0243da0ec086285ee722183804d5923bc3ac | https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-recognition/src/main/java/boofcv/alg/fiducial/calib/squares/SquareCrossClustersIntoGrids.java#L148-L180 | train |
lessthanoptimal/BoofCV | main/boofcv-recognition/src/main/java/boofcv/alg/fiducial/calib/squares/SquareCrossClustersIntoGrids.java | SquareCrossClustersIntoGrids.checkEdgeCount | 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;
} | java | 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;
} | [
"private",
"boolean",
"checkEdgeCount",
"(",
"SquareGrid",
"grid",
")",
"{",
"int",
"left",
"=",
"0",
",",
"right",
"=",
"grid",
".",
"columns",
"-",
"1",
";",
"int",
"top",
"=",
"0",
",",
"bottom",
"=",
"grid",
".",
"rows",
"-",
"1",
";",
"for",
... | Looks at the edge count in each node and sees if it has the expected number | [
"Looks",
"at",
"the",
"edge",
"count",
"in",
"each",
"node",
"and",
"sees",
"if",
"it",
"has",
"the",
"expected",
"number"
] | f01c0243da0ec086285ee722183804d5923bc3ac | https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-recognition/src/main/java/boofcv/alg/fiducial/calib/squares/SquareCrossClustersIntoGrids.java#L185-L220 | train |
lessthanoptimal/BoofCV | main/boofcv-recognition/src/main/java/boofcv/alg/fiducial/calib/squares/SquareCrossClustersIntoGrids.java | SquareCrossClustersIntoGrids.firstRow1 | List<SquareNode> firstRow1( SquareNode seed ) {
for (int i = 0; i < seed.square.size(); i++) {
if( isOpenEdge(seed,i) ) {
List<SquareNode> list = new ArrayList<>();
seed.graph = 0;
// Doesn't know which direction it can traverse along. See figure that out
// by looking at the node its linked to
int corner = seed.edges[i].destinationSide(seed);
SquareNode dst = seed.edges[i].destination(seed);
int l = addOffset(corner,-1,dst.square.size());
int u = addOffset(corner, 1,dst.square.size());
if( dst.edges[u] != null ) {
list.add(seed);
if( !addToRow(seed,i,-1,true,list) ) return null;
} else if( dst.edges[l] != null ){
List<SquareNode> tmp = new ArrayList<>();
if( !addToRow(seed,i, 1,true,tmp) ) return null;
flipAdd(tmp, list);
list.add(seed);
} else {
// there is only a single node below it
list.add(seed);
}
return list;
}
}
throw new RuntimeException("BUG");
} | java | List<SquareNode> firstRow1( SquareNode seed ) {
for (int i = 0; i < seed.square.size(); i++) {
if( isOpenEdge(seed,i) ) {
List<SquareNode> list = new ArrayList<>();
seed.graph = 0;
// Doesn't know which direction it can traverse along. See figure that out
// by looking at the node its linked to
int corner = seed.edges[i].destinationSide(seed);
SquareNode dst = seed.edges[i].destination(seed);
int l = addOffset(corner,-1,dst.square.size());
int u = addOffset(corner, 1,dst.square.size());
if( dst.edges[u] != null ) {
list.add(seed);
if( !addToRow(seed,i,-1,true,list) ) return null;
} else if( dst.edges[l] != null ){
List<SquareNode> tmp = new ArrayList<>();
if( !addToRow(seed,i, 1,true,tmp) ) return null;
flipAdd(tmp, list);
list.add(seed);
} else {
// there is only a single node below it
list.add(seed);
}
return list;
}
}
throw new RuntimeException("BUG");
} | [
"List",
"<",
"SquareNode",
">",
"firstRow1",
"(",
"SquareNode",
"seed",
")",
"{",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"seed",
".",
"square",
".",
"size",
"(",
")",
";",
"i",
"++",
")",
"{",
"if",
"(",
"isOpenEdge",
"(",
"seed",
","... | Adds the first row to the list of rows when the seed element has only one edge | [
"Adds",
"the",
"first",
"row",
"to",
"the",
"list",
"of",
"rows",
"when",
"the",
"seed",
"element",
"has",
"only",
"one",
"edge"
] | f01c0243da0ec086285ee722183804d5923bc3ac | https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-recognition/src/main/java/boofcv/alg/fiducial/calib/squares/SquareCrossClustersIntoGrids.java#L225-L255 | train |
lessthanoptimal/BoofCV | main/boofcv-recognition/src/main/java/boofcv/alg/fiducial/calib/squares/SquareCrossClustersIntoGrids.java | SquareCrossClustersIntoGrids.firstRow2 | 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;
} | java | 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;
} | [
"List",
"<",
"SquareNode",
">",
"firstRow2",
"(",
"SquareNode",
"seed",
")",
"{",
"int",
"indexLower",
"=",
"lowerEdgeIndex",
"(",
"seed",
")",
";",
"int",
"indexUpper",
"=",
"addOffset",
"(",
"indexLower",
",",
"1",
",",
"seed",
".",
"square",
".",
"siz... | Adds the first row to the list of rows when the seed element has two edges | [
"Adds",
"the",
"first",
"row",
"to",
"the",
"list",
"of",
"rows",
"when",
"the",
"seed",
"element",
"has",
"two",
"edges"
] | f01c0243da0ec086285ee722183804d5923bc3ac | https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-recognition/src/main/java/boofcv/alg/fiducial/calib/squares/SquareCrossClustersIntoGrids.java#L260-L274 | train |
lessthanoptimal/BoofCV | main/boofcv-recognition/src/main/java/boofcv/alg/fiducial/calib/squares/SquareCrossClustersIntoGrids.java | SquareCrossClustersIntoGrids.lowerEdgeIndex | 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!");
} | java | 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!");
} | [
"static",
"int",
"lowerEdgeIndex",
"(",
"SquareNode",
"node",
")",
"{",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"node",
".",
"square",
".",
"size",
"(",
")",
";",
"i",
"++",
")",
"{",
"if",
"(",
"isOpenEdge",
"(",
"node",
",",
"i",
")"... | Returns the open corner index which is first. Assuming that there are two adjacent corners. | [
"Returns",
"the",
"open",
"corner",
"index",
"which",
"is",
"first",
".",
"Assuming",
"that",
"there",
"are",
"two",
"adjacent",
"corners",
"."
] | f01c0243da0ec086285ee722183804d5923bc3ac | https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-recognition/src/main/java/boofcv/alg/fiducial/calib/squares/SquareCrossClustersIntoGrids.java#L340-L358 | train |
lessthanoptimal/BoofCV | main/boofcv-recognition/src/main/java/boofcv/alg/fiducial/calib/squares/SquareCrossClustersIntoGrids.java | SquareCrossClustersIntoGrids.isOpenEdge | 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;
} | java | 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;
} | [
"static",
"boolean",
"isOpenEdge",
"(",
"SquareNode",
"node",
",",
"int",
"index",
")",
"{",
"if",
"(",
"node",
".",
"edges",
"[",
"index",
"]",
"==",
"null",
")",
"return",
"false",
";",
"int",
"marker",
"=",
"node",
".",
"edges",
"[",
"index",
"]",... | 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. | [
"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",
"."
] | f01c0243da0ec086285ee722183804d5923bc3ac | https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-recognition/src/main/java/boofcv/alg/fiducial/calib/squares/SquareCrossClustersIntoGrids.java#L373-L378 | train |
lessthanoptimal/BoofCV | main/boofcv-recognition/src/main/java/boofcv/alg/fiducial/calib/squares/SquareCrossClustersIntoGrids.java | SquareCrossClustersIntoGrids.addToRow | boolean addToRow( SquareNode n , int corner , int sign , boolean skip ,
List<SquareNode> row ) {
SquareEdge e;
while( (e = n.edges[corner]) != null ) {
if( e.a == n ) {
n = e.b;
corner = e.sideB;
} else {
n = e.a;
corner = e.sideA;
}
if( !skip ) {
if( n.graph != SquareNode.RESET_GRAPH) {
// This should never happen in a valid grid. It can happen if two nodes link to each other multiple
// times. Other situations as well
invalid = true;
return false;
}
n.graph = 0;
row.add(n);
}
skip = !skip;
sign *= -1;
corner = addOffset(corner,sign,n.square.size());
}
return true;
} | java | boolean addToRow( SquareNode n , int corner , int sign , boolean skip ,
List<SquareNode> row ) {
SquareEdge e;
while( (e = n.edges[corner]) != null ) {
if( e.a == n ) {
n = e.b;
corner = e.sideB;
} else {
n = e.a;
corner = e.sideA;
}
if( !skip ) {
if( n.graph != SquareNode.RESET_GRAPH) {
// This should never happen in a valid grid. It can happen if two nodes link to each other multiple
// times. Other situations as well
invalid = true;
return false;
}
n.graph = 0;
row.add(n);
}
skip = !skip;
sign *= -1;
corner = addOffset(corner,sign,n.square.size());
}
return true;
} | [
"boolean",
"addToRow",
"(",
"SquareNode",
"n",
",",
"int",
"corner",
",",
"int",
"sign",
",",
"boolean",
"skip",
",",
"List",
"<",
"SquareNode",
">",
"row",
")",
"{",
"SquareEdge",
"e",
";",
"while",
"(",
"(",
"e",
"=",
"n",
".",
"edges",
"[",
"cor... | 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.
@param n Initial node
@param corner Which corner points to the next node
@param sign Determines the direction it will traverse. -1 or 1
@param skip true = start adding nodes at second, false = start first.
@param row List that the nodes are placed into | [
"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",
"."
] | f01c0243da0ec086285ee722183804d5923bc3ac | https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-recognition/src/main/java/boofcv/alg/fiducial/calib/squares/SquareCrossClustersIntoGrids.java#L399-L425 | train |
lessthanoptimal/BoofCV | main/boofcv-recognition/src/main/java/boofcv/alg/fiducial/calib/squares/SquareCrossClustersIntoGrids.java | SquareCrossClustersIntoGrids.findSeedNode | 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;
} | java | 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;
} | [
"static",
"SquareNode",
"findSeedNode",
"(",
"List",
"<",
"SquareNode",
">",
"cluster",
")",
"{",
"SquareNode",
"seed",
"=",
"null",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"cluster",
".",
"size",
"(",
")",
";",
"i",
"++",
")",
"{",
... | Finds a seed with 1 or 2 edges. | [
"Finds",
"a",
"seed",
"with",
"1",
"or",
"2",
"edges",
"."
] | f01c0243da0ec086285ee722183804d5923bc3ac | https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-recognition/src/main/java/boofcv/alg/fiducial/calib/squares/SquareCrossClustersIntoGrids.java#L430-L442 | train |
lessthanoptimal/BoofCV | main/boofcv-feature/src/main/java/boofcv/alg/feature/detect/chess/DetectChessboardCorners.java | DetectChessboardCorners.process | public void process( GrayF32 input ) {
// System.out.println("ENTER CHESSBOARD CORNER "+input.width+" x "+input.height);
borderImg.setImage(input);
gradient.process(input,derivX,derivY);
interpX.setImage(derivX);
interpY.setImage(derivY);
cornerIntensity.process(derivX,derivY,intensity);
intensityInterp.setImage(intensity);
// adjust intensity value so that its between 0 and levels for OTSU thresholding
float featmax = ImageStatistics.max(intensity);
PixelMath.multiply(intensity, GRAY_LEVELS /featmax,intensity);
// int N = intensity.width*input.height;
// for (int i = 0; i < N; i++) {
// if( intensity.data[i] <= 2f ) {
// intensity.data[i] = 0f;
// }
// }
// convert into a binary image with high feature intensity regions being 1
inputToBinary.process(intensity,binary);
// find the small regions. Th se might be where corners are
contourFinder.process(binary);
corners.reset();
List<ContourPacked> packed = contourFinder.getContours();
// System.out.println(" * features.size = "+packed.size());
for (int i = 0; i < packed.size(); i++) {
contourFinder.loadContour(i,contour);
ChessboardCorner c = corners.grow();
UtilPoint2D_I32.mean(contour.toList(),c);
// compensate for the bias caused by how pixels are counted.
// Example: a 4x4 region is expected. Center should be at (2,2) but will instead be (1.5,1.5)
c.x += 0.5;
c.y += 0.5;
computeFeatures(c.x,c.y,c);
// System.out.println("radius = "+radius+" angle = "+c.angle);
// System.out.println("intensity "+c.intensity);
if( c.intensity < cornerIntensityThreshold ) {
corners.removeTail();
} else if( useMeanShift ) {
meanShiftLocation(c);
// TODO does it make sense to use mean shift first?
computeFeatures(c.x,c.y,c);
}
}
// System.out.println("Dropped "+dropped+" / "+packed.size());
} | java | public void process( GrayF32 input ) {
// System.out.println("ENTER CHESSBOARD CORNER "+input.width+" x "+input.height);
borderImg.setImage(input);
gradient.process(input,derivX,derivY);
interpX.setImage(derivX);
interpY.setImage(derivY);
cornerIntensity.process(derivX,derivY,intensity);
intensityInterp.setImage(intensity);
// adjust intensity value so that its between 0 and levels for OTSU thresholding
float featmax = ImageStatistics.max(intensity);
PixelMath.multiply(intensity, GRAY_LEVELS /featmax,intensity);
// int N = intensity.width*input.height;
// for (int i = 0; i < N; i++) {
// if( intensity.data[i] <= 2f ) {
// intensity.data[i] = 0f;
// }
// }
// convert into a binary image with high feature intensity regions being 1
inputToBinary.process(intensity,binary);
// find the small regions. Th se might be where corners are
contourFinder.process(binary);
corners.reset();
List<ContourPacked> packed = contourFinder.getContours();
// System.out.println(" * features.size = "+packed.size());
for (int i = 0; i < packed.size(); i++) {
contourFinder.loadContour(i,contour);
ChessboardCorner c = corners.grow();
UtilPoint2D_I32.mean(contour.toList(),c);
// compensate for the bias caused by how pixels are counted.
// Example: a 4x4 region is expected. Center should be at (2,2) but will instead be (1.5,1.5)
c.x += 0.5;
c.y += 0.5;
computeFeatures(c.x,c.y,c);
// System.out.println("radius = "+radius+" angle = "+c.angle);
// System.out.println("intensity "+c.intensity);
if( c.intensity < cornerIntensityThreshold ) {
corners.removeTail();
} else if( useMeanShift ) {
meanShiftLocation(c);
// TODO does it make sense to use mean shift first?
computeFeatures(c.x,c.y,c);
}
}
// System.out.println("Dropped "+dropped+" / "+packed.size());
} | [
"public",
"void",
"process",
"(",
"GrayF32",
"input",
")",
"{",
"//\t\tSystem.out.println(\"ENTER CHESSBOARD CORNER \"+input.width+\" x \"+input.height);",
"borderImg",
".",
"setImage",
"(",
"input",
")",
";",
"gradient",
".",
"process",
"(",
"input",
",",
"derivX",
","... | Computes chessboard corners inside the image
@param input Gray image. Not modified. | [
"Computes",
"chessboard",
"corners",
"inside",
"the",
"image"
] | f01c0243da0ec086285ee722183804d5923bc3ac | https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-feature/src/main/java/boofcv/alg/feature/detect/chess/DetectChessboardCorners.java#L144-L199 | train |
lessthanoptimal/BoofCV | main/boofcv-feature/src/main/java/boofcv/alg/feature/detect/chess/DetectChessboardCorners.java | DetectChessboardCorners.meanShiftLocation | public void meanShiftLocation( ChessboardCorner c ) {
float meanX = (float)c.x;
float meanY = (float)c.y;
// The peak in intensity will be in -r to r region, but smaller values will be -2*r to 2*r
int radius = this.shiRadius*2;
for (int iteration = 0; iteration < 5; iteration++) {
float adjX = 0;
float adjY = 0;
float total = 0;
for (int y = -radius; y < radius; y++) {
float yy = y;
for (int x = -radius; x < radius; x++) {
float xx = x;
float v = intensityInterp.get(meanX+xx,meanY+yy);
// Again, this adjustment to account for how pixels are counted. See center from contour computation
adjX += (xx+0.5)*v;
adjY += (yy+0.5)*v;
total += v;
}
}
meanX += adjX/total;
meanY += adjY/total;
}
c.x = meanX;
c.y = meanY;
} | java | public void meanShiftLocation( ChessboardCorner c ) {
float meanX = (float)c.x;
float meanY = (float)c.y;
// The peak in intensity will be in -r to r region, but smaller values will be -2*r to 2*r
int radius = this.shiRadius*2;
for (int iteration = 0; iteration < 5; iteration++) {
float adjX = 0;
float adjY = 0;
float total = 0;
for (int y = -radius; y < radius; y++) {
float yy = y;
for (int x = -radius; x < radius; x++) {
float xx = x;
float v = intensityInterp.get(meanX+xx,meanY+yy);
// Again, this adjustment to account for how pixels are counted. See center from contour computation
adjX += (xx+0.5)*v;
adjY += (yy+0.5)*v;
total += v;
}
}
meanX += adjX/total;
meanY += adjY/total;
}
c.x = meanX;
c.y = meanY;
} | [
"public",
"void",
"meanShiftLocation",
"(",
"ChessboardCorner",
"c",
")",
"{",
"float",
"meanX",
"=",
"(",
"float",
")",
"c",
".",
"x",
";",
"float",
"meanY",
"=",
"(",
"float",
")",
"c",
".",
"y",
";",
"// The peak in intensity will be in -r to r region, but ... | 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. | [
"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"... | f01c0243da0ec086285ee722183804d5923bc3ac | https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-feature/src/main/java/boofcv/alg/feature/detect/chess/DetectChessboardCorners.java#L283-L312 | train |
lessthanoptimal/BoofCV | integration/boofcv-android/src/main/java/boofcv/android/camera2/VisualizeCamera2Activity.java | VisualizeCamera2Activity.setThreadPoolSize | 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);
} | java | 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);
} | [
"public",
"void",
"setThreadPoolSize",
"(",
"int",
"threads",
")",
"{",
"if",
"(",
"threads",
"<=",
"0",
")",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"Number of threads must be greater than 0\"",
")",
";",
"if",
"(",
"verbose",
")",
"Log",
".",
"i",
... | 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. | [
"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",
"... | f01c0243da0ec086285ee722183804d5923bc3ac | https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/integration/boofcv-android/src/main/java/boofcv/android/camera2/VisualizeCamera2Activity.java#L163-L171 | train |
lessthanoptimal/BoofCV | integration/boofcv-android/src/main/java/boofcv/android/camera2/VisualizeCamera2Activity.java | VisualizeCamera2Activity.selectResolution | @Override
protected int selectResolution( int widthTexture, int heightTexture, Size[] resolutions ) {
// just wanted to make sure this has been cleaned up
timeOfLastUpdated = 0;
// select the resolution here
int bestIndex = -1;
double bestAspect = Double.MAX_VALUE;
double bestArea = 0;
for( int i = 0; i < resolutions.length; i++ ) {
Size s = resolutions[i];
int width = s.getWidth();
int height = s.getHeight();
double aspectScore = Math.abs(width*height-targetResolution);
if( aspectScore < bestAspect ) {
bestIndex = i;
bestAspect = aspectScore;
bestArea = width*height;
} else if( Math.abs(aspectScore-bestArea) <= 1e-8 ) {
bestIndex = i;
double area = width*height;
if( area > bestArea ) {
bestArea = area;
}
}
}
return bestIndex;
} | java | @Override
protected int selectResolution( int widthTexture, int heightTexture, Size[] resolutions ) {
// just wanted to make sure this has been cleaned up
timeOfLastUpdated = 0;
// select the resolution here
int bestIndex = -1;
double bestAspect = Double.MAX_VALUE;
double bestArea = 0;
for( int i = 0; i < resolutions.length; i++ ) {
Size s = resolutions[i];
int width = s.getWidth();
int height = s.getHeight();
double aspectScore = Math.abs(width*height-targetResolution);
if( aspectScore < bestAspect ) {
bestIndex = i;
bestAspect = aspectScore;
bestArea = width*height;
} else if( Math.abs(aspectScore-bestArea) <= 1e-8 ) {
bestIndex = i;
double area = width*height;
if( area > bestArea ) {
bestArea = area;
}
}
}
return bestIndex;
} | [
"@",
"Override",
"protected",
"int",
"selectResolution",
"(",
"int",
"widthTexture",
",",
"int",
"heightTexture",
",",
"Size",
"[",
"]",
"resolutions",
")",
"{",
"// just wanted to make sure this has been cleaned up",
"timeOfLastUpdated",
"=",
"0",
";",
"// select the r... | Selects a resolution which has the number of pixels closest to the requested value | [
"Selects",
"a",
"resolution",
"which",
"has",
"the",
"number",
"of",
"pixels",
"closest",
"to",
"the",
"requested",
"value"
] | f01c0243da0ec086285ee722183804d5923bc3ac | https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/integration/boofcv-android/src/main/java/boofcv/android/camera2/VisualizeCamera2Activity.java#L209-L240 | train |
lessthanoptimal/BoofCV | integration/boofcv-android/src/main/java/boofcv/android/camera2/VisualizeCamera2Activity.java | VisualizeCamera2Activity.setImageType | 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();
}
}
} | java | 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();
}
}
} | [
"protected",
"void",
"setImageType",
"(",
"ImageType",
"type",
",",
"ColorFormat",
"colorFormat",
")",
"{",
"synchronized",
"(",
"boofImage",
".",
"imageLock",
")",
"{",
"boofImage",
".",
"colorFormat",
"=",
"colorFormat",
";",
"if",
"(",
"!",
"boofImage",
"."... | Changes the type of image the camera frame is converted to | [
"Changes",
"the",
"type",
"of",
"image",
"the",
"camera",
"frame",
"is",
"converted",
"to"
] | f01c0243da0ec086285ee722183804d5923bc3ac | https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/integration/boofcv-android/src/main/java/boofcv/android/camera2/VisualizeCamera2Activity.java#L325-L338 | train |
lessthanoptimal/BoofCV | integration/boofcv-android/src/main/java/boofcv/android/camera2/VisualizeCamera2Activity.java | VisualizeCamera2Activity.renderBitmapImage | protected void renderBitmapImage( BitmapMode mode , ImageBase image ) {
switch( mode ) {
case UNSAFE: {
if (image.getWidth() == bitmap.getWidth() && image.getHeight() == bitmap.getHeight())
ConvertBitmap.boofToBitmap(image, bitmap, bitmapTmp);
} break;
case DOUBLE_BUFFER: {
// TODO if there are multiple processing threads bad stuff will happen here. Need one work buffer
// per thread
// convert the image. this can be a slow operation
if (image.getWidth() == bitmapWork.getWidth() && image.getHeight() == bitmapWork.getHeight())
ConvertBitmap.boofToBitmap(image, bitmapWork, bitmapTmp);
// swap the two buffers. If it's locked don't swap. This will skip a frame but will not cause
// a significant slow down
if( bitmapLock.tryLock() ) {
try {
Bitmap tmp = bitmapWork;
bitmapWork = bitmap;
bitmap = tmp;
} finally {
bitmapLock.unlock();
}
}
} break;
}
} | java | protected void renderBitmapImage( BitmapMode mode , ImageBase image ) {
switch( mode ) {
case UNSAFE: {
if (image.getWidth() == bitmap.getWidth() && image.getHeight() == bitmap.getHeight())
ConvertBitmap.boofToBitmap(image, bitmap, bitmapTmp);
} break;
case DOUBLE_BUFFER: {
// TODO if there are multiple processing threads bad stuff will happen here. Need one work buffer
// per thread
// convert the image. this can be a slow operation
if (image.getWidth() == bitmapWork.getWidth() && image.getHeight() == bitmapWork.getHeight())
ConvertBitmap.boofToBitmap(image, bitmapWork, bitmapTmp);
// swap the two buffers. If it's locked don't swap. This will skip a frame but will not cause
// a significant slow down
if( bitmapLock.tryLock() ) {
try {
Bitmap tmp = bitmapWork;
bitmapWork = bitmap;
bitmap = tmp;
} finally {
bitmapLock.unlock();
}
}
} break;
}
} | [
"protected",
"void",
"renderBitmapImage",
"(",
"BitmapMode",
"mode",
",",
"ImageBase",
"image",
")",
"{",
"switch",
"(",
"mode",
")",
"{",
"case",
"UNSAFE",
":",
"{",
"if",
"(",
"image",
".",
"getWidth",
"(",
")",
"==",
"bitmap",
".",
"getWidth",
"(",
... | 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. | [
"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",
"ima... | f01c0243da0ec086285ee722183804d5923bc3ac | https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/integration/boofcv-android/src/main/java/boofcv/android/camera2/VisualizeCamera2Activity.java#L420-L447 | train |
lessthanoptimal/BoofCV | integration/boofcv-android/src/main/java/boofcv/android/camera2/VisualizeCamera2Activity.java | VisualizeCamera2Activity.onDrawFrame | protected void onDrawFrame( SurfaceView view , Canvas canvas ) {
// Code below is usefull when debugging display issues
// Paint paintFill = new Paint();
// paintFill.setColor(Color.RED);
// paintFill.setStyle(Paint.Style.FILL);
// Paint paintBorder = new Paint();
// paintBorder.setColor(Color.BLUE);
// paintBorder.setStyle(Paint.Style.STROKE);
// paintBorder.setStrokeWidth(6*displayMetrics.density);
//
// Rect r = new Rect(0,0,view.getWidth(),view.getHeight());
// canvas.drawRect(r,paintFill);
// canvas.drawRect(r,paintBorder);
switch( bitmapMode) {
case UNSAFE:
canvas.drawBitmap(this.bitmap, imageToView, null);
break;
case DOUBLE_BUFFER:
bitmapLock.lock();
try{
canvas.drawBitmap(this.bitmap, imageToView, null);
} finally {
bitmapLock.unlock();
}
break;
}
} | java | protected void onDrawFrame( SurfaceView view , Canvas canvas ) {
// Code below is usefull when debugging display issues
// Paint paintFill = new Paint();
// paintFill.setColor(Color.RED);
// paintFill.setStyle(Paint.Style.FILL);
// Paint paintBorder = new Paint();
// paintBorder.setColor(Color.BLUE);
// paintBorder.setStyle(Paint.Style.STROKE);
// paintBorder.setStrokeWidth(6*displayMetrics.density);
//
// Rect r = new Rect(0,0,view.getWidth(),view.getHeight());
// canvas.drawRect(r,paintFill);
// canvas.drawRect(r,paintBorder);
switch( bitmapMode) {
case UNSAFE:
canvas.drawBitmap(this.bitmap, imageToView, null);
break;
case DOUBLE_BUFFER:
bitmapLock.lock();
try{
canvas.drawBitmap(this.bitmap, imageToView, null);
} finally {
bitmapLock.unlock();
}
break;
}
} | [
"protected",
"void",
"onDrawFrame",
"(",
"SurfaceView",
"view",
",",
"Canvas",
"canvas",
")",
"{",
"// Code below is usefull when debugging display issues",
"//\t\tPaint paintFill = new Paint();",
"//\t\tpaintFill.setColor(Color.RED);",
"//\t\tpaintFill.setStyle(Paint.Style.FILL);",
"/... | Renders the visualizations. Override and invoke super to add your own | [
"Renders",
"the",
"visualizations",
".",
"Override",
"and",
"invoke",
"super",
"to",
"add",
"your",
"own"
] | f01c0243da0ec086285ee722183804d5923bc3ac | https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/integration/boofcv-android/src/main/java/boofcv/android/camera2/VisualizeCamera2Activity.java#L452-L480 | train |
lessthanoptimal/BoofCV | main/boofcv-feature/src/main/java/boofcv/factory/feature/detect/intensity/FactoryIntensityPoint.java | FactoryIntensityPoint.median | 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);
} | java | 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);
} | [
"public",
"static",
"<",
"I",
"extends",
"ImageGray",
"<",
"I",
">",
",",
"D",
"extends",
"ImageGray",
"<",
"D",
">",
">",
"GeneralFeatureIntensity",
"<",
"I",
",",
"D",
">",
"median",
"(",
"int",
"radius",
",",
"Class",
"<",
"I",
">",
"imageType",
"... | Feature intensity for median corner detector.
@param radius Size of the feature it detects,
@param <I> Input image type.
@return Median feature intensity | [
"Feature",
"intensity",
"for",
"median",
"corner",
"detector",
"."
] | f01c0243da0ec086285ee722183804d5923bc3ac | https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-feature/src/main/java/boofcv/factory/feature/detect/intensity/FactoryIntensityPoint.java#L112-L116 | train |
lessthanoptimal/BoofCV | main/boofcv-feature/src/main/java/boofcv/factory/feature/detect/intensity/FactoryIntensityPoint.java | FactoryIntensityPoint.hessian | 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);
} | java | 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);
} | [
"public",
"static",
"<",
"I",
"extends",
"ImageGray",
"<",
"I",
">",
",",
"D",
"extends",
"ImageGray",
"<",
"D",
">",
">",
"GeneralFeatureIntensity",
"<",
"I",
",",
"D",
">",
"hessian",
"(",
"HessianBlobIntensity",
".",
"Type",
"type",
",",
"Class",
"<",... | Blob detector which uses the image's second order derivatives directly.
@see HessianBlobIntensity
@param type Type of Hessian
@param <I> Input image type.
@param <D> Derivative type.
@return Hessian based blob intensity | [
"Blob",
"detector",
"which",
"uses",
"the",
"image",
"s",
"second",
"order",
"derivatives",
"directly",
"."
] | f01c0243da0ec086285ee722183804d5923bc3ac | https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-feature/src/main/java/boofcv/factory/feature/detect/intensity/FactoryIntensityPoint.java#L128-L131 | train |
lessthanoptimal/BoofCV | main/boofcv-geo/src/main/java/boofcv/abst/feature/tracker/PointTrackerKltPyramid.java | PointTrackerKltPyramid.getInactiveTracks | @Override
public List<PointTrack> getInactiveTracks(List<PointTrack> list) {
if( list == null )
list = new ArrayList<>();
return list;
} | java | @Override
public List<PointTrack> getInactiveTracks(List<PointTrack> list) {
if( list == null )
list = new ArrayList<>();
return list;
} | [
"@",
"Override",
"public",
"List",
"<",
"PointTrack",
">",
"getInactiveTracks",
"(",
"List",
"<",
"PointTrack",
">",
"list",
")",
"{",
"if",
"(",
"list",
"==",
"null",
")",
"list",
"=",
"new",
"ArrayList",
"<>",
"(",
")",
";",
"return",
"list",
";",
... | KLT does not have inactive tracks since all tracks are dropped if a problem occurs. | [
"KLT",
"does",
"not",
"have",
"inactive",
"tracks",
"since",
"all",
"tracks",
"are",
"dropped",
"if",
"a",
"problem",
"occurs",
"."
] | f01c0243da0ec086285ee722183804d5923bc3ac | https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-geo/src/main/java/boofcv/abst/feature/tracker/PointTrackerKltPyramid.java#L305-L311 | train |
lessthanoptimal/BoofCV | main/boofcv-feature/src/main/java/boofcv/alg/feature/detect/intensity/impl/ImplSsdCorner_F32_MT.java | ImplSsdCorner_F32_MT.horizontal | @Override
protected void horizontal() {
float[] dataX = derivX.data;
float[] dataY = derivY.data;
float[] hXX = horizXX.data;
float[] hXY = horizXY.data;
float[] hYY = horizYY.data;
final int imgHeight = derivX.getHeight();
final int imgWidth = derivX.getWidth();
int windowWidth = radius * 2 + 1;
int radp1 = radius + 1;
BoofConcurrency.loopFor(0,imgHeight,row->{
int pix = row * imgWidth;
int end = pix + windowWidth;
float totalXX = 0;
float totalXY = 0;
float totalYY = 0;
int indexX = derivX.startIndex + row * derivX.stride;
int indexY = derivY.startIndex + row * derivY.stride;
for (; pix < end; pix++) {
float dx = dataX[indexX++];
float dy = dataY[indexY++];
totalXX += dx * dx;
totalXY += dx * dy;
totalYY += dy * dy;
}
hXX[pix - radp1] = totalXX;
hXY[pix - radp1] = totalXY;
hYY[pix - radp1] = totalYY;
end = row * imgWidth + imgWidth;
for (; pix < end; pix++, indexX++, indexY++) {
float dx = dataX[indexX - windowWidth];
float dy = dataY[indexY - windowWidth];
// saving these multiplications in an array to avoid recalculating them made
// the algorithm about 50% slower
totalXX -= dx * dx;
totalXY -= dx * dy;
totalYY -= dy * dy;
dx = dataX[indexX];
dy = dataY[indexY];
totalXX += dx * dx;
totalXY += dx * dy;
totalYY += dy * dy;
hXX[pix - radius] = totalXX;
hXY[pix - radius] = totalXY;
hYY[pix - radius] = totalYY;
}
});
} | java | @Override
protected void horizontal() {
float[] dataX = derivX.data;
float[] dataY = derivY.data;
float[] hXX = horizXX.data;
float[] hXY = horizXY.data;
float[] hYY = horizYY.data;
final int imgHeight = derivX.getHeight();
final int imgWidth = derivX.getWidth();
int windowWidth = radius * 2 + 1;
int radp1 = radius + 1;
BoofConcurrency.loopFor(0,imgHeight,row->{
int pix = row * imgWidth;
int end = pix + windowWidth;
float totalXX = 0;
float totalXY = 0;
float totalYY = 0;
int indexX = derivX.startIndex + row * derivX.stride;
int indexY = derivY.startIndex + row * derivY.stride;
for (; pix < end; pix++) {
float dx = dataX[indexX++];
float dy = dataY[indexY++];
totalXX += dx * dx;
totalXY += dx * dy;
totalYY += dy * dy;
}
hXX[pix - radp1] = totalXX;
hXY[pix - radp1] = totalXY;
hYY[pix - radp1] = totalYY;
end = row * imgWidth + imgWidth;
for (; pix < end; pix++, indexX++, indexY++) {
float dx = dataX[indexX - windowWidth];
float dy = dataY[indexY - windowWidth];
// saving these multiplications in an array to avoid recalculating them made
// the algorithm about 50% slower
totalXX -= dx * dx;
totalXY -= dx * dy;
totalYY -= dy * dy;
dx = dataX[indexX];
dy = dataY[indexY];
totalXX += dx * dx;
totalXY += dx * dy;
totalYY += dy * dy;
hXX[pix - radius] = totalXX;
hXY[pix - radius] = totalXY;
hYY[pix - radius] = totalYY;
}
});
} | [
"@",
"Override",
"protected",
"void",
"horizontal",
"(",
")",
"{",
"float",
"[",
"]",
"dataX",
"=",
"derivX",
".",
"data",
";",
"float",
"[",
"]",
"dataY",
"=",
"derivY",
".",
"data",
";",
"float",
"[",
"]",
"hXX",
"=",
"horizXX",
".",
"data",
";",... | Compute the derivative sum along the x-axis while taking advantage of duplicate
calculations for each window. | [
"Compute",
"the",
"derivative",
"sum",
"along",
"the",
"x",
"-",
"axis",
"while",
"taking",
"advantage",
"of",
"duplicate",
"calculations",
"for",
"each",
"window",
"."
] | f01c0243da0ec086285ee722183804d5923bc3ac | https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-feature/src/main/java/boofcv/alg/feature/detect/intensity/impl/ImplSsdCorner_F32_MT.java#L59-L124 | train |
lessthanoptimal/BoofCV | main/boofcv-feature/src/main/java/boofcv/alg/feature/detect/intensity/impl/ImplSsdCorner_F32_MT.java | ImplSsdCorner_F32_MT.vertical | @Override
protected void vertical( GrayF32 intensity ) {
float[] hXX = horizXX.data;
float[] hXY = horizXY.data;
float[] hYY = horizYY.data;
final float[] inten = intensity.data;
final int imgHeight = horizXX.getHeight();
final int imgWidth = horizXX.getWidth();
final int kernelWidth = radius * 2 + 1;
final int startX = radius;
final int endX = imgWidth - radius;
final int backStep = kernelWidth * imgWidth;
BoofConcurrency.loopBlocks(radius,imgHeight-radius,(y0,y1)->{
final float[] tempXX = work.pop();
final float[] tempXY = work.pop();
final float[] tempYY = work.pop();
for (int x = startX; x < endX; x++) {
// defines the A matrix, from which the eigenvalues are computed
int srcIndex = x + (y0-radius)*imgWidth;
int destIndex = imgWidth * y0 + x;
float totalXX = 0, totalXY = 0, totalYY = 0;
int indexEnd = srcIndex + imgWidth * kernelWidth;
for (; srcIndex < indexEnd; srcIndex += imgWidth) {
totalXX += hXX[srcIndex];
totalXY += hXY[srcIndex];
totalYY += hYY[srcIndex];
}
tempXX[x] = totalXX;
tempXY[x] = totalXY;
tempYY[x] = totalYY;
// compute the eigen values
inten[destIndex] = this.intensity.compute(totalXX,totalXY,totalYY);
destIndex += imgWidth;
}
// change the order it is processed in to reduce cache misses
for (int y = y0 + 1; y < y1; y++) {
int srcIndex = (y + radius) * imgWidth + startX;
int destIndex = y * imgWidth + startX;
for (int x = startX; x < endX; x++, srcIndex++, destIndex++) {
float totalXX = tempXX[x] - hXX[srcIndex - backStep];
tempXX[x] = totalXX += hXX[srcIndex];
float totalXY = tempXY[x] - hXY[srcIndex - backStep];
tempXY[x] = totalXY += hXY[srcIndex];
float totalYY = tempYY[x] - hYY[srcIndex - backStep];
tempYY[x] = totalYY += hYY[srcIndex];
inten[destIndex] = this.intensity.compute(totalXX,totalXY,totalYY);
}
}
work.recycle(tempXX);
work.recycle(tempXY);
work.recycle(tempYY);
});
} | java | @Override
protected void vertical( GrayF32 intensity ) {
float[] hXX = horizXX.data;
float[] hXY = horizXY.data;
float[] hYY = horizYY.data;
final float[] inten = intensity.data;
final int imgHeight = horizXX.getHeight();
final int imgWidth = horizXX.getWidth();
final int kernelWidth = radius * 2 + 1;
final int startX = radius;
final int endX = imgWidth - radius;
final int backStep = kernelWidth * imgWidth;
BoofConcurrency.loopBlocks(radius,imgHeight-radius,(y0,y1)->{
final float[] tempXX = work.pop();
final float[] tempXY = work.pop();
final float[] tempYY = work.pop();
for (int x = startX; x < endX; x++) {
// defines the A matrix, from which the eigenvalues are computed
int srcIndex = x + (y0-radius)*imgWidth;
int destIndex = imgWidth * y0 + x;
float totalXX = 0, totalXY = 0, totalYY = 0;
int indexEnd = srcIndex + imgWidth * kernelWidth;
for (; srcIndex < indexEnd; srcIndex += imgWidth) {
totalXX += hXX[srcIndex];
totalXY += hXY[srcIndex];
totalYY += hYY[srcIndex];
}
tempXX[x] = totalXX;
tempXY[x] = totalXY;
tempYY[x] = totalYY;
// compute the eigen values
inten[destIndex] = this.intensity.compute(totalXX,totalXY,totalYY);
destIndex += imgWidth;
}
// change the order it is processed in to reduce cache misses
for (int y = y0 + 1; y < y1; y++) {
int srcIndex = (y + radius) * imgWidth + startX;
int destIndex = y * imgWidth + startX;
for (int x = startX; x < endX; x++, srcIndex++, destIndex++) {
float totalXX = tempXX[x] - hXX[srcIndex - backStep];
tempXX[x] = totalXX += hXX[srcIndex];
float totalXY = tempXY[x] - hXY[srcIndex - backStep];
tempXY[x] = totalXY += hXY[srcIndex];
float totalYY = tempYY[x] - hYY[srcIndex - backStep];
tempYY[x] = totalYY += hYY[srcIndex];
inten[destIndex] = this.intensity.compute(totalXX,totalXY,totalYY);
}
}
work.recycle(tempXX);
work.recycle(tempXY);
work.recycle(tempYY);
});
} | [
"@",
"Override",
"protected",
"void",
"vertical",
"(",
"GrayF32",
"intensity",
")",
"{",
"float",
"[",
"]",
"hXX",
"=",
"horizXX",
".",
"data",
";",
"float",
"[",
"]",
"hXY",
"=",
"horizXY",
".",
"data",
";",
"float",
"[",
"]",
"hYY",
"=",
"horizYY",... | 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 | [
"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"
] | f01c0243da0ec086285ee722183804d5923bc3ac | https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-feature/src/main/java/boofcv/alg/feature/detect/intensity/impl/ImplSsdCorner_F32_MT.java#L130-L193 | train |
lessthanoptimal/BoofCV | main/boofcv-ip/src/main/java/boofcv/alg/distort/DistortImageOps.java | DistortImageOps.distortSingle | 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);
} | java | 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);
} | [
"public",
"static",
"<",
"Input",
"extends",
"ImageGray",
"<",
"Input",
">",
",",
"Output",
"extends",
"ImageGray",
"<",
"Output",
">",
">",
"void",
"distortSingle",
"(",
"Input",
"input",
",",
"Output",
"output",
",",
"PixelTransform",
"<",
"Point2D_F32",
"... | Applies a pixel transform to a single band image. Easier to use function.
@deprecated As of v0.19. Use {@link FDistort} instead
@param input Input (source) image.
@param output Where the result of transforming the image image is written to.
@param transform The transform that is being applied to the image
@param interpType Which type of pixel interpolation should be used. BILINEAR is in general recommended
@param borderType Specifies how to handle image borders. | [
"Applies",
"a",
"pixel",
"transform",
"to",
"a",
"single",
"band",
"image",
".",
"Easier",
"to",
"use",
"function",
"."
] | f01c0243da0ec086285ee722183804d5923bc3ac | https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-ip/src/main/java/boofcv/alg/distort/DistortImageOps.java#L105-L122 | train |
lessthanoptimal/BoofCV | main/boofcv-ip/src/main/java/boofcv/alg/distort/DistortImageOps.java | DistortImageOps.distortSingle | 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);
} | java | 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);
} | [
"public",
"static",
"<",
"Input",
"extends",
"ImageGray",
"<",
"Input",
">",
",",
"Output",
"extends",
"ImageGray",
"<",
"Output",
">",
">",
"void",
"distortSingle",
"(",
"Input",
"input",
",",
"Output",
"output",
",",
"boolean",
"renderAll",
",",
"PixelTran... | Applies a pixel transform to a single band image. More flexible but order to use function.
@deprecated As of v0.19. Use {@link FDistort} instead
@param input Input (source) image.
@param output Where the result of transforming the image image is written to.
@param renderAll true it renders all pixels, even ones outside the input image.
@param transform The transform that is being applied to the image
@param interp Interpolation algorithm. | [
"Applies",
"a",
"pixel",
"transform",
"to",
"a",
"single",
"band",
"image",
".",
"More",
"flexible",
"but",
"order",
"to",
"use",
"function",
"."
] | f01c0243da0ec086285ee722183804d5923bc3ac | https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-ip/src/main/java/boofcv/alg/distort/DistortImageOps.java#L135-L145 | train |
lessthanoptimal/BoofCV | main/boofcv-ip/src/main/java/boofcv/alg/distort/DistortImageOps.java | DistortImageOps.scale | @Deprecated
public static <T extends ImageBase<T>>
void scale(T input, T output, BorderType borderType, InterpolationType interpType) {
PixelTransformAffine_F32 model = DistortSupport.transformScale(output, input, null);
if( input instanceof ImageGray) {
distortSingle((ImageGray) input, (ImageGray) output, model, interpType, borderType);
} else if( input instanceof Planar) {
distortPL((Planar) input, (Planar) output, model, borderType, interpType);
}
} | java | @Deprecated
public static <T extends ImageBase<T>>
void scale(T input, T output, BorderType borderType, InterpolationType interpType) {
PixelTransformAffine_F32 model = DistortSupport.transformScale(output, input, null);
if( input instanceof ImageGray) {
distortSingle((ImageGray) input, (ImageGray) output, model, interpType, borderType);
} else if( input instanceof Planar) {
distortPL((Planar) input, (Planar) output, model, borderType, interpType);
}
} | [
"@",
"Deprecated",
"public",
"static",
"<",
"T",
"extends",
"ImageBase",
"<",
"T",
">",
">",
"void",
"scale",
"(",
"T",
"input",
",",
"T",
"output",
",",
"BorderType",
"borderType",
",",
"InterpolationType",
"interpType",
")",
"{",
"PixelTransformAffine_F32",
... | Rescales the input image and writes the results into the output image. The scale
factor is determined independently of the width and height.
@param input Input image. Not modified.
@param output Rescaled input image. Modified.
@param borderType Describes how pixels outside the image border should be handled.
@param interpType Which interpolation algorithm should be used. | [
"Rescales",
"the",
"input",
"image",
"and",
"writes",
"the",
"results",
"into",
"the",
"output",
"image",
".",
"The",
"scale",
"factor",
"is",
"determined",
"independently",
"of",
"the",
"width",
"and",
"height",
"."
] | f01c0243da0ec086285ee722183804d5923bc3ac | https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-ip/src/main/java/boofcv/alg/distort/DistortImageOps.java#L209-L220 | train |
lessthanoptimal/BoofCV | main/boofcv-ip/src/main/java/boofcv/alg/distort/DistortImageOps.java | DistortImageOps.boundBox | 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);
} | java | 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);
} | [
"public",
"static",
"RectangleLength2D_I32",
"boundBox",
"(",
"int",
"srcWidth",
",",
"int",
"srcHeight",
",",
"int",
"dstWidth",
",",
"int",
"dstHeight",
",",
"Point2D_F32",
"work",
",",
"PixelTransform",
"<",
"Point2D_F32",
">",
"transform",
")",
"{",
"Rectang... | 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.
@param srcWidth Width of the source image
@param srcHeight Height of the source image
@param dstWidth Width of the destination image
@param dstHeight Height of the destination image
@param transform Transform being applied to the image
@return Bounding box | [
"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",
"... | f01c0243da0ec086285ee722183804d5923bc3ac | https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-ip/src/main/java/boofcv/alg/distort/DistortImageOps.java#L289-L307 | train |
lessthanoptimal/BoofCV | main/boofcv-recognition/src/main/java/boofcv/alg/tracker/sfot/SparseFlowObjectTracker.java | SparseFlowObjectTracker.update | public boolean update( Image input , RectangleRotate_F64 output ) {
if( trackLost )
return false;
trackFeatures(input, region);
// See if there are enough points remaining. use of config.numberOfSamples is some what arbitrary
if( pairs.size() < config.numberOfSamples ) {
System.out.println("Lack of sample pairs");
trackLost = true;
return false;
}
// find the motion using tracked features
if( !estimateMotion.process(pairs.toList()) ) {
System.out.println("estimate motion failed");
trackLost = true;
return false;
}
if( estimateMotion.getFitQuality() > config.robustMaxError ) {
System.out.println("exceeded Max estimation error");
trackLost = true;
return false;
}
// update the target's location using the found motion
ScaleTranslateRotate2D model = estimateMotion.getModelParameters();
region.width *= model.scale;
region.height *= model.scale;
double c = Math.cos(model.theta);
double s = Math.sin(model.theta);
double x = region.cx;
double y = region.cy;
region.cx = (x*c - y*s)*model.scale + model.transX;
region.cy = (x*s + y*c)*model.scale + model.transY;
region.theta += model.theta;
output.set(region);
// make the current image into the previous image
swapImages();
return true;
} | java | public boolean update( Image input , RectangleRotate_F64 output ) {
if( trackLost )
return false;
trackFeatures(input, region);
// See if there are enough points remaining. use of config.numberOfSamples is some what arbitrary
if( pairs.size() < config.numberOfSamples ) {
System.out.println("Lack of sample pairs");
trackLost = true;
return false;
}
// find the motion using tracked features
if( !estimateMotion.process(pairs.toList()) ) {
System.out.println("estimate motion failed");
trackLost = true;
return false;
}
if( estimateMotion.getFitQuality() > config.robustMaxError ) {
System.out.println("exceeded Max estimation error");
trackLost = true;
return false;
}
// update the target's location using the found motion
ScaleTranslateRotate2D model = estimateMotion.getModelParameters();
region.width *= model.scale;
region.height *= model.scale;
double c = Math.cos(model.theta);
double s = Math.sin(model.theta);
double x = region.cx;
double y = region.cy;
region.cx = (x*c - y*s)*model.scale + model.transX;
region.cy = (x*s + y*c)*model.scale + model.transY;
region.theta += model.theta;
output.set(region);
// make the current image into the previous image
swapImages();
return true;
} | [
"public",
"boolean",
"update",
"(",
"Image",
"input",
",",
"RectangleRotate_F64",
"output",
")",
"{",
"if",
"(",
"trackLost",
")",
"return",
"false",
";",
"trackFeatures",
"(",
"input",
",",
"region",
")",
";",
"// See if there are enough points remaining. use of c... | Given the input image compute the new location of the target region and store the results in output.
@param input next image in the sequence.
@param output Storage for the output.
@return true if tracking is successful | [
"Given",
"the",
"input",
"image",
"compute",
"the",
"new",
"location",
"of",
"the",
"target",
"region",
"and",
"store",
"the",
"results",
"in",
"output",
"."
] | f01c0243da0ec086285ee722183804d5923bc3ac | https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-recognition/src/main/java/boofcv/alg/tracker/sfot/SparseFlowObjectTracker.java#L136-L186 | train |
lessthanoptimal/BoofCV | main/boofcv-recognition/src/main/java/boofcv/alg/tracker/sfot/SparseFlowObjectTracker.java | SparseFlowObjectTracker.trackFeatures | private void trackFeatures(Image input, RectangleRotate_F64 region) {
pairs.reset();
currentImage.process(input);
for( int i = 0; i < currentImage.getNumLayers(); i++ ) {
Image layer = currentImage.getLayer(i);
gradient.process(layer,currentDerivX[i],currentDerivY[i]);
}
// convert to float to avoid excessive conversions from double to float
float cx = (float)region.cx;
float cy = (float)region.cy;
float height = (float)(region.height);
float width = (float)(region.width);
float c = (float)Math.cos(region.theta);
float s = (float)Math.sin(region.theta);
float p = 1.0f/(config.numberOfSamples-1);
for( int i = 0; i < config.numberOfSamples; i++ ) {
float y = (p*i-0.5f)*height;
for( int j = 0; j < config.numberOfSamples; j++ ) {
float x = (p*j - 0.5f)*width;
float xx = cx + x*c - y*s;
float yy = cy + x*s + y*c;
// track in the forward direction
track.x = xx;
track.y = yy;
klt.setImage(previousImage,previousDerivX,previousDerivY);
if( !klt.setDescription(track) ) {
continue;
}
klt.setImage(currentImage,currentDerivX,currentDerivY);
KltTrackFault fault = klt.track(track);
if( fault != KltTrackFault.SUCCESS ) {
continue;
}
float xc = track.x;
float yc = track.y;
// validate by tracking backwards
if( !klt.setDescription(track) ) {
continue;
}
klt.setImage(previousImage,previousDerivX,previousDerivY);
fault = klt.track(track);
if( fault != KltTrackFault.SUCCESS ) {
continue;
}
float error = UtilPoint2D_F32.distanceSq(track.x, track.y, xx, yy);
if( error > maximumErrorFB ) {
continue;
}
// create a list of the observations
AssociatedPair a = pairs.grow();
a.p1.x = xx;
a.p1.y = yy;
a.p2.x = xc;
a.p2.y = yc;
}
}
} | java | private void trackFeatures(Image input, RectangleRotate_F64 region) {
pairs.reset();
currentImage.process(input);
for( int i = 0; i < currentImage.getNumLayers(); i++ ) {
Image layer = currentImage.getLayer(i);
gradient.process(layer,currentDerivX[i],currentDerivY[i]);
}
// convert to float to avoid excessive conversions from double to float
float cx = (float)region.cx;
float cy = (float)region.cy;
float height = (float)(region.height);
float width = (float)(region.width);
float c = (float)Math.cos(region.theta);
float s = (float)Math.sin(region.theta);
float p = 1.0f/(config.numberOfSamples-1);
for( int i = 0; i < config.numberOfSamples; i++ ) {
float y = (p*i-0.5f)*height;
for( int j = 0; j < config.numberOfSamples; j++ ) {
float x = (p*j - 0.5f)*width;
float xx = cx + x*c - y*s;
float yy = cy + x*s + y*c;
// track in the forward direction
track.x = xx;
track.y = yy;
klt.setImage(previousImage,previousDerivX,previousDerivY);
if( !klt.setDescription(track) ) {
continue;
}
klt.setImage(currentImage,currentDerivX,currentDerivY);
KltTrackFault fault = klt.track(track);
if( fault != KltTrackFault.SUCCESS ) {
continue;
}
float xc = track.x;
float yc = track.y;
// validate by tracking backwards
if( !klt.setDescription(track) ) {
continue;
}
klt.setImage(previousImage,previousDerivX,previousDerivY);
fault = klt.track(track);
if( fault != KltTrackFault.SUCCESS ) {
continue;
}
float error = UtilPoint2D_F32.distanceSq(track.x, track.y, xx, yy);
if( error > maximumErrorFB ) {
continue;
}
// create a list of the observations
AssociatedPair a = pairs.grow();
a.p1.x = xx;
a.p1.y = yy;
a.p2.x = xc;
a.p2.y = yc;
}
}
} | [
"private",
"void",
"trackFeatures",
"(",
"Image",
"input",
",",
"RectangleRotate_F64",
"region",
")",
"{",
"pairs",
".",
"reset",
"(",
")",
";",
"currentImage",
".",
"process",
"(",
"input",
")",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
... | Tracks features from the previous image into the current image. Tracks are created inside the specified
region in a grid pattern. | [
"Tracks",
"features",
"from",
"the",
"previous",
"image",
"into",
"the",
"current",
"image",
".",
"Tracks",
"are",
"created",
"inside",
"the",
"specified",
"region",
"in",
"a",
"grid",
"pattern",
"."
] | f01c0243da0ec086285ee722183804d5923bc3ac | https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-recognition/src/main/java/boofcv/alg/tracker/sfot/SparseFlowObjectTracker.java#L192-L262 | train |
lessthanoptimal/BoofCV | main/boofcv-recognition/src/main/java/boofcv/alg/tracker/sfot/SparseFlowObjectTracker.java | SparseFlowObjectTracker.declarePyramid | 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);
} | java | 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);
} | [
"private",
"void",
"declarePyramid",
"(",
"int",
"imageWidth",
",",
"int",
"imageHeight",
")",
"{",
"int",
"minSize",
"=",
"(",
"config",
".",
"trackerFeatureRadius",
"*",
"2",
"+",
"1",
")",
"*",
"5",
";",
"int",
"scales",
"[",
"]",
"=",
"TldTracker",
... | Declares internal data structures | [
"Declares",
"internal",
"data",
"structures"
] | f01c0243da0ec086285ee722183804d5923bc3ac | https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-recognition/src/main/java/boofcv/alg/tracker/sfot/SparseFlowObjectTracker.java#L267-L293 | train |
lessthanoptimal/BoofCV | main/boofcv-recognition/src/main/java/boofcv/alg/tracker/sfot/SparseFlowObjectTracker.java | SparseFlowObjectTracker.swapImages | 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;
} | java | 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;
} | [
"private",
"void",
"swapImages",
"(",
")",
"{",
"ImagePyramid",
"<",
"Image",
">",
"tempP",
";",
"tempP",
"=",
"currentImage",
";",
"currentImage",
"=",
"previousImage",
";",
"previousImage",
"=",
"tempP",
";",
"Derivative",
"[",
"]",
"tempD",
";",
"tempD",
... | Swaps the current and previous so that image derivative doesn't need to be recomputed or compied. | [
"Swaps",
"the",
"current",
"and",
"previous",
"so",
"that",
"image",
"derivative",
"doesn",
"t",
"need",
"to",
"be",
"recomputed",
"or",
"compied",
"."
] | f01c0243da0ec086285ee722183804d5923bc3ac | https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-recognition/src/main/java/boofcv/alg/tracker/sfot/SparseFlowObjectTracker.java#L298-L314 | train |
lessthanoptimal/BoofCV | main/boofcv-feature/src/main/java/boofcv/struct/flow/ImageFlow.java | ImageFlow.invalidateAll | public void invalidateAll() {
int N = width*height;
for( int i = 0; i < N; i++ )
data[i].x = Float.NaN;
} | java | public void invalidateAll() {
int N = width*height;
for( int i = 0; i < N; i++ )
data[i].x = Float.NaN;
} | [
"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 | [
"Marks",
"all",
"pixels",
"as",
"having",
"an",
"invalid",
"flow"
] | f01c0243da0ec086285ee722183804d5923bc3ac | https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-feature/src/main/java/boofcv/struct/flow/ImageFlow.java#L61-L65 | train |
lessthanoptimal/BoofCV | main/boofcv-feature/src/main/java/boofcv/alg/shapes/ellipse/EdgeIntensityEllipse.java | EdgeIntensityEllipse.process | public boolean process(EllipseRotated_F64 ellipse ) {
// see if it's disabled
if( numContourPoints <= 0 ) {
score = 0;
return true;
}
double cphi = Math.cos(ellipse.phi);
double sphi = Math.sin(ellipse.phi);
averageInside = 0;
averageOutside = 0;
int total = 0;
for (int contourIndex = 0; contourIndex < numContourPoints; contourIndex++) {
double theta = contourIndex*Math.PI*2.0/numContourPoints;
// copied from UtilEllipse_F64.computePoint() reduced number of cos and sin
double ct = Math.cos(theta);
double st = Math.sin(theta);
// location on ellipse in world frame
double px = ellipse.center.x + ellipse.a*ct*cphi - ellipse.b*st*sphi;
double py = ellipse.center.y + ellipse.a*ct*sphi + ellipse.b*st*cphi;
// find direction of the tangent line
// ellipse frame
double edx = ellipse.a*ct*ellipse.b*ellipse.b;
double edy = ellipse.b*st*ellipse.a*ellipse.a;
double r = Math.sqrt(edx*edx + edy*edy);
edx /= r;
edy /= r;
// rotate tangent into world frame
double dx = edx*cphi - edy*sphi;
double dy = edx*sphi + edy*cphi;
// define the line integral
double xin = px-dx*tangentDistance;
double yin = py-dy*tangentDistance;
double xout = px+dx*tangentDistance;
double yout = py+dy*tangentDistance;
if( integral.isInside(xin,yin) && integral.isInside(xout,yout)) {
averageInside += integral.compute(px,py, xin, yin);
averageOutside += integral.compute(px,py, xout, yout);
total++;
}
}
score = 0;
if( total > 0 ) {
score = Math.abs(averageOutside-averageInside)/(total*tangentDistance);
}
return score >= passThreshold;
} | java | public boolean process(EllipseRotated_F64 ellipse ) {
// see if it's disabled
if( numContourPoints <= 0 ) {
score = 0;
return true;
}
double cphi = Math.cos(ellipse.phi);
double sphi = Math.sin(ellipse.phi);
averageInside = 0;
averageOutside = 0;
int total = 0;
for (int contourIndex = 0; contourIndex < numContourPoints; contourIndex++) {
double theta = contourIndex*Math.PI*2.0/numContourPoints;
// copied from UtilEllipse_F64.computePoint() reduced number of cos and sin
double ct = Math.cos(theta);
double st = Math.sin(theta);
// location on ellipse in world frame
double px = ellipse.center.x + ellipse.a*ct*cphi - ellipse.b*st*sphi;
double py = ellipse.center.y + ellipse.a*ct*sphi + ellipse.b*st*cphi;
// find direction of the tangent line
// ellipse frame
double edx = ellipse.a*ct*ellipse.b*ellipse.b;
double edy = ellipse.b*st*ellipse.a*ellipse.a;
double r = Math.sqrt(edx*edx + edy*edy);
edx /= r;
edy /= r;
// rotate tangent into world frame
double dx = edx*cphi - edy*sphi;
double dy = edx*sphi + edy*cphi;
// define the line integral
double xin = px-dx*tangentDistance;
double yin = py-dy*tangentDistance;
double xout = px+dx*tangentDistance;
double yout = py+dy*tangentDistance;
if( integral.isInside(xin,yin) && integral.isInside(xout,yout)) {
averageInside += integral.compute(px,py, xin, yin);
averageOutside += integral.compute(px,py, xout, yout);
total++;
}
}
score = 0;
if( total > 0 ) {
score = Math.abs(averageOutside-averageInside)/(total*tangentDistance);
}
return score >= passThreshold;
} | [
"public",
"boolean",
"process",
"(",
"EllipseRotated_F64",
"ellipse",
")",
"{",
"// see if it's disabled",
"if",
"(",
"numContourPoints",
"<=",
"0",
")",
"{",
"score",
"=",
"0",
";",
"return",
"true",
";",
"}",
"double",
"cphi",
"=",
"Math",
".",
"cos",
"(... | Processes the edge along the ellipse and determines if the edge intensity is strong enough
to pass or not
@param ellipse The ellipse in undistorted image coordinates.
@return true if it passes or false if not | [
"Processes",
"the",
"edge",
"along",
"the",
"ellipse",
"and",
"determines",
"if",
"the",
"edge",
"intensity",
"is",
"strong",
"enough",
"to",
"pass",
"or",
"not"
] | f01c0243da0ec086285ee722183804d5923bc3ac | https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-feature/src/main/java/boofcv/alg/shapes/ellipse/EdgeIntensityEllipse.java#L79-L136 | train |
lessthanoptimal/BoofCV | main/boofcv-feature/src/main/java/boofcv/alg/feature/detect/interest/UnrollSiftScaleSpaceGradient.java | UnrollSiftScaleSpaceGradient.setImage | 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() );
} | java | 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() );
} | [
"public",
"void",
"setImage",
"(",
"GrayF32",
"image",
")",
"{",
"scaleSpace",
".",
"initialize",
"(",
"image",
")",
";",
"usedScales",
".",
"clear",
"(",
")",
";",
"do",
"{",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"scaleSpace",
".",
"get... | Sets the input image. Scale-space is computed and unrolled from this image
@param image | [
"Sets",
"the",
"input",
"image",
".",
"Scale",
"-",
"space",
"is",
"computed",
"and",
"unrolled",
"from",
"this",
"image"
] | f01c0243da0ec086285ee722183804d5923bc3ac | https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-feature/src/main/java/boofcv/alg/feature/detect/interest/UnrollSiftScaleSpaceGradient.java#L61-L83 | train |
lessthanoptimal/BoofCV | main/boofcv-feature/src/main/java/boofcv/alg/feature/detect/interest/UnrollSiftScaleSpaceGradient.java | UnrollSiftScaleSpaceGradient.lookup | 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;
} | java | 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;
} | [
"public",
"ImageScale",
"lookup",
"(",
"double",
"sigma",
")",
"{",
"ImageScale",
"best",
"=",
"null",
";",
"double",
"bestValue",
"=",
"Double",
".",
"MAX_VALUE",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"usedScales",
".",
"size",
"(",
... | Looks up the image which is closest specified sigma | [
"Looks",
"up",
"the",
"image",
"which",
"is",
"closest",
"specified",
"sigma"
] | f01c0243da0ec086285ee722183804d5923bc3ac | https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-feature/src/main/java/boofcv/alg/feature/detect/interest/UnrollSiftScaleSpaceGradient.java#L89-L102 | train |
lessthanoptimal/BoofCV | main/boofcv-geo/src/main/java/boofcv/alg/geo/bundle/jacobians/BundleCameraNumericJacobian.java | BundleCameraNumericJacobian.setModel | 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);
} | java | 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);
} | [
"public",
"void",
"setModel",
"(",
"BundleAdjustmentCamera",
"model",
")",
"{",
"this",
".",
"model",
"=",
"model",
";",
"numIntrinsic",
"=",
"model",
".",
"getIntrinsicCount",
"(",
")",
";",
"if",
"(",
"numIntrinsic",
">",
"intrinsic",
".",
"length",
")",
... | Specifies the camera model. The current state of its intrinsic parameters
@param model | [
"Specifies",
"the",
"camera",
"model",
".",
"The",
"current",
"state",
"of",
"its",
"intrinsic",
"parameters"
] | f01c0243da0ec086285ee722183804d5923bc3ac | https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-geo/src/main/java/boofcv/alg/geo/bundle/jacobians/BundleCameraNumericJacobian.java#L62-L72 | train |
lessthanoptimal/BoofCV | main/boofcv-feature/src/main/java/boofcv/alg/feature/associate/AssociateGreedy.java | AssociateGreedy.associate | @Override
public void associate( FastQueue<D> src , FastQueue<D> dst )
{
fitQuality.reset();
pairs.reset();
workBuffer.reset();
pairs.resize(src.size);
fitQuality.resize(src.size);
workBuffer.resize(src.size*dst.size);
//CONCURRENT_BELOW BoofConcurrency.loopFor(0, src.size, i -> {
for( int i = 0; i < src.size; i++ ) {
D a = src.data[i];
double bestScore = maxFitError;
int bestIndex = -1;
int workIdx = i*dst.size;
for( int j = 0; j < dst.size; j++ ) {
D b = dst.data[j];
double fit = score.score(a,b);
workBuffer.set(workIdx+j,fit);
if( fit <= bestScore ) {
bestIndex = j;
bestScore = fit;
}
}
pairs.set(i,bestIndex);
fitQuality.set(i,bestScore);
}
//CONCURRENT_ABOVE });
if( backwardsValidation ) {
//CONCURRENT_BELOW BoofConcurrency.loopFor(0, src.size, i -> {
for( int i = 0; i < src.size; i++ ) {
int match = pairs.data[i];
if( match == -1 )
//CONCURRENT_BELOW return;
continue;
double scoreToBeat = workBuffer.data[i*dst.size+match];
for( int j = 0; j < src.size; j++ , match += dst.size ) {
if( workBuffer.data[match] <= scoreToBeat && j != i) {
pairs.data[i] = -1;
fitQuality.data[i] = Double.MAX_VALUE;
break;
}
}
}
//CONCURRENT_ABOVE });
}
} | java | @Override
public void associate( FastQueue<D> src , FastQueue<D> dst )
{
fitQuality.reset();
pairs.reset();
workBuffer.reset();
pairs.resize(src.size);
fitQuality.resize(src.size);
workBuffer.resize(src.size*dst.size);
//CONCURRENT_BELOW BoofConcurrency.loopFor(0, src.size, i -> {
for( int i = 0; i < src.size; i++ ) {
D a = src.data[i];
double bestScore = maxFitError;
int bestIndex = -1;
int workIdx = i*dst.size;
for( int j = 0; j < dst.size; j++ ) {
D b = dst.data[j];
double fit = score.score(a,b);
workBuffer.set(workIdx+j,fit);
if( fit <= bestScore ) {
bestIndex = j;
bestScore = fit;
}
}
pairs.set(i,bestIndex);
fitQuality.set(i,bestScore);
}
//CONCURRENT_ABOVE });
if( backwardsValidation ) {
//CONCURRENT_BELOW BoofConcurrency.loopFor(0, src.size, i -> {
for( int i = 0; i < src.size; i++ ) {
int match = pairs.data[i];
if( match == -1 )
//CONCURRENT_BELOW return;
continue;
double scoreToBeat = workBuffer.data[i*dst.size+match];
for( int j = 0; j < src.size; j++ , match += dst.size ) {
if( workBuffer.data[match] <= scoreToBeat && j != i) {
pairs.data[i] = -1;
fitQuality.data[i] = Double.MAX_VALUE;
break;
}
}
}
//CONCURRENT_ABOVE });
}
} | [
"@",
"Override",
"public",
"void",
"associate",
"(",
"FastQueue",
"<",
"D",
">",
"src",
",",
"FastQueue",
"<",
"D",
">",
"dst",
")",
"{",
"fitQuality",
".",
"reset",
"(",
")",
";",
"pairs",
".",
"reset",
"(",
")",
";",
"workBuffer",
".",
"reset",
"... | Associates the two sets objects against each other by minimizing fit score.
@param src Source list.
@param dst Destination list. | [
"Associates",
"the",
"two",
"sets",
"objects",
"against",
"each",
"other",
"by",
"minimizing",
"fit",
"score",
"."
] | f01c0243da0ec086285ee722183804d5923bc3ac | https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-feature/src/main/java/boofcv/alg/feature/associate/AssociateGreedy.java#L64-L118 | train |
lessthanoptimal/BoofCV | main/boofcv-recognition/src/main/java/boofcv/alg/fiducial/qrcode/QrCodeAlignmentPatternLocator.java | QrCodeAlignmentPatternLocator.process | public boolean process(T image , QrCode qr ) {
this.qr = qr;
// this must be cleared before calling setMarker or else the distortion will be messed up
qr.alignment.reset();
reader.setImage(image);
reader.setMarker(qr);
threshold = (float)qr.threshCorner;
initializePatterns(qr);
// version 1 has no alignment patterns
if( qr.version <= 1 )
return true;
return localizePositionPatterns(QrCode.VERSION_INFO[qr.version].alignment);
} | java | public boolean process(T image , QrCode qr ) {
this.qr = qr;
// this must be cleared before calling setMarker or else the distortion will be messed up
qr.alignment.reset();
reader.setImage(image);
reader.setMarker(qr);
threshold = (float)qr.threshCorner;
initializePatterns(qr);
// version 1 has no alignment patterns
if( qr.version <= 1 )
return true;
return localizePositionPatterns(QrCode.VERSION_INFO[qr.version].alignment);
} | [
"public",
"boolean",
"process",
"(",
"T",
"image",
",",
"QrCode",
"qr",
")",
"{",
"this",
".",
"qr",
"=",
"qr",
";",
"// this must be cleared before calling setMarker or else the distortion will be messed up",
"qr",
".",
"alignment",
".",
"reset",
"(",
")",
";",
"... | Uses the previously detected position patterns to seed the search for the alignment patterns | [
"Uses",
"the",
"previously",
"detected",
"position",
"patterns",
"to",
"seed",
"the",
"search",
"for",
"the",
"alignment",
"patterns"
] | f01c0243da0ec086285ee722183804d5923bc3ac | https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-recognition/src/main/java/boofcv/alg/fiducial/qrcode/QrCodeAlignmentPatternLocator.java#L56-L72 | train |
lessthanoptimal/BoofCV | main/boofcv-recognition/src/main/java/boofcv/alg/fiducial/qrcode/QrCodeAlignmentPatternLocator.java | QrCodeAlignmentPatternLocator.initializePatterns | 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);
}
}
}
} | java | 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);
}
}
}
} | [
"void",
"initializePatterns",
"(",
"QrCode",
"qr",
")",
"{",
"int",
"where",
"[",
"]",
"=",
"QrCode",
".",
"VERSION_INFO",
"[",
"qr",
".",
"version",
"]",
".",
"alignment",
";",
"qr",
".",
"alignment",
".",
"reset",
"(",
")",
";",
"lookup",
".",
"res... | Creates a list of alignment patterns to look for and their grid coordinates | [
"Creates",
"a",
"list",
"of",
"alignment",
"patterns",
"to",
"look",
"for",
"and",
"their",
"grid",
"coordinates"
] | f01c0243da0ec086285ee722183804d5923bc3ac | https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-recognition/src/main/java/boofcv/alg/fiducial/qrcode/QrCodeAlignmentPatternLocator.java#L83-L107 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.