I'm using a JS Library called Javascript Clipper for polygon operation. As stated from the manual, the coordinate format of an input path is like the follows,
var paths = [[{X:30,Y:30},{X:130,Y:30},{X:130,Y:130},{X:30,Y:130}],
[{X:60,Y:60},{X:60,Y:100},{X:100,Y:100},{X:100,Y:60}]];
My question is, how to convert a regular JS array, say
var x = [40, 100, 1, 5, 25, 10] and var y= [22, 32, 11, 45, 75, 19] to the required format shown above? The actual case is, these coordinate points will not be typed manually, but obtained from another function, the output of which is not in the format required by the Javascript Clipper Library.
Something like this:
function makePath(xVals, yVals) {
var pathArray = [];
xVals.forEach(function(xVal, index) {
var yVal = yVals[index];
var coordObj = {xVal, yVal};
pathArray.push(coordObj);
})
return pathArray;
}
You can pass it your arrays, x and y, as makePath(x,y) to get the combined array out.
My method assumes that the lengths of the arrays x and y are the same.
Related
I am new to TensorflowJS and I try to code something but I am stuck...
I have two input layers like that:
const input1 = tf.input({ shape: [64, 64, 3] });
const input2 = tf.input({ shape: [1536] });
The first one is for an image of 64 by 64 and the 3 is for RGB.
The second one is for an array that contains 1536 numbers (floats).
I tried to concatenate them with .concatenate().apply(input1, input2) but got the following error:
ValueError: A `Concatenate` layer requires inputs with matching shapes except for the concat axis. Got input shapes: [[null,64,64,3],[null,1536]]
I also tried to add { axis: -1 } or { axis: 1 } (found that on stack overflow but that doesnt work too).
I also tried that (answer by chat gpt) :
const flatten1 = tf.layers.flatten().apply(input1);
const flatten2 = tf.layers.flatten().apply(input2);
const concat = tf.layers.concatenate({ axis: -1 }).apply([flatten1, flatten2]);
but same error...
Can someone help me? I just want to add this to my tf.sequential() as an input...
PS: This is the module I use:
const tf = require('#tensorflow/tfjs-node');
This just shows you what concatenation is, and how can be done for those specific inputs.
This is a textual description of the code at the bottom of the post:
create an image-like shape (width, height, colorChannels)
create a random one dimensional array (aka vector) of 1536 values
1536 elements can be reshaped into a little "image" of 8 x 64 and 3 channels
Result is 72 x 64 x 8 so this should hint you what the code did (extend the axis with different number of values, that is it.
const original = tf.ones([64, 64, 3]);
const random = tf.randomNormal([1536]);
const reshaped = tf.reshape(random, [8, 64, 3]);
const axis = 0;
const concat = tf.concat([original, reshaped], axis);
console.log(concat);
<script src="https://cdn.jsdelivr.net/npm/#tensorflow/tfjs#2.0.0/dist/tf.min.js"></script>
Another possibility is flat, extend and then back re-shape but I find this simple enough.
Im trying to create a convex hull with opencv.js based on an array with points, does anyone know a way to do this correctly and efficient? An array would look like this:
[
[5,5],
[10,10],
[15,15]
...
]
-> where the first value would be the x and the second the y value, but it wouldn't be a problem to change this format to something more suitable.
Thnx for the help :)
As far I could experiment OpenCV stores contour/hull data in Mat format with type CV_32SC2: essentially a flat list of 32bit short integers in [x1,y1,x2,y2,x3,y3,...] order.
Note the two channels/planes part of 32SC2: one channel for all the x values and another for all the y values
You can manually create such a Mat, access it's data32S property and fill in each value:
let testHull = cv.Mat.ones(4, 1, cv.CV_32SC2);
testHull.data32S[0] = 100;
testHull.data32S[1] = 100;
testHull.data32S[2] = 200;
testHull.data32S[3] = 100;
testHull.data32S[4] = 200;
testHull.data32S[5] = 200;
testHull.data32S[6] = 100;
testHull.data32S[7] = 200;
However OpenCV.js comes with a handy method to convert a flat array of values to such a Mat:
let testHull = cv.matFromArray(4, 1, cv.CV_32SC2, [100,100,200,100,200,200,100,200])
If your array is nested, you can simply use JS Array's flat() method to flatten it from a 2D array([[x1,y1]...]) to a 1D array ([x1,y1,...]).
So you don't have to worry about the Mat type and all that you can wrap it all into a nice function, for example:
function nestedPointsArrayToMat(points){
return cv.matFromArray(points.length, 1, cv.CV_32SC2, points.flat());
}
Here's a quick demo:
function onOpenCvReady(){
cv.then(test);
}
function nestedPointsArrayToMat(points){
return cv.matFromArray(points.length, 1, cv.CV_32SC2, points.flat());
}
function test(cv){
console.log("cv loaded");
// make a Mat to draw into
let mainMat = cv.Mat.zeros(30, 30, cv.CV_8UC3);
// make a fake hull
let points = [
[ 5, 5],
[25, 5],
[25,25],
[ 5,25]
]
let hull = nestedPointsArrayToMat(points);
console.log("hull data", hull.data32S);
// make a fake hulls vector
let hulls = new cv.MatVector();
// add the recently created hull
hulls.push_back(hull);
// test drawing it
cv.drawContours(mainMat, hulls, 0, [192,64,0,0], -1, 8);
// output to canvas
cv.imshow('canvasOutput', mainMat);
}
<script async src="https://docs.opencv.org/4.4.0/opencv.js" onload="onOpenCvReady();" type="text/javascript"></script>
<canvas id="canvasOutput" width="30" height="30"></canvas>
Note that the above is a rough example, there's no data validation or any other fancier checks, but hopefully it illustrates the idea so it can be extended robustly as required.
Lets say that your points represent a contour:
var contours = new cv.MatVector();
for (var i = 0; i < points.size(); ++i) {
contours.push_back(new cv.Mat(points[i][0], points[i][1])
}
Now following this tutorial from opencv website:
// approximates each contour to convex hull
for (var i = 0; i < contours.size(); ++i) {
var tmp = new cv.Mat();
var cnt = contours.get(i);
// You can try more different parameters
cv.convexHull(cnt, tmp, false, true);
hull.push_back(tmp);
cnt.delete(); tmp.delete();
}
I'm working on simple genetics program involving theoretical flowers. For color assignment I'm using a simplified Punnett Square created thusly,
var momDom = mommaFlower.ColorOne;
var momRec = mommaFlower.ColorTwo;
var dadDom = papaFlower.ColorOne;
var dadRec = papaFlower.ColorTwo;
var punnet = [
[0,0],
[0,0],
];
punnet[0][0] = [momDom, dadDom];
punnet[0][1] = [momDom, dadRec];
punnet[1][0] = [momRec, dadDom];
punnet[1][1] = [momRec, dadRec];
return punnet[Math.floor(Math.random() * 2)][Math.floor(Math.random() * 2)];
so there is a relatively equal chance of any of the four color combinations for the child.
My trouble lies in translating this to Java, namely the destructuring assignment. What I have so far is
//getDomColor() = {255, 187, 187, 1.0}
float[][][][] punnet = {
{
{m.getDomColor(), f.getDomColor()},
{m.getDomColor(), f.getRecColor()}
},{
{m.getRecColor(), f.getDomColor()},
{m.getRecColor(), f.getRecColor()}
}
};
where the return on getDomColor, and getRecColor is a float array of rgb values. I had hoped it would be just as simple as JS's way, but I've since found out that Java does not have destructuring assignment. My question is, what would be the best way to translate my JS Punnett Square into Java, considering what I have so far.
I am trying to incorporate chroma.js into my leaflet map so that i can toggle between quantiles, equal interval, and k-means, but the second and third argument for the domain function does not change anything
var colorScale = chroma.scale('YlGnBu').domain(voterList, 3, 'quantiles');
Here is the full code for the function
this.getRegionItemColor = function(item) {
var regionData = Mapbook.getRegionData();
var voterList = Mapbook.getColorScheme();
var colorScale = chroma.scale('YlGnBu').domain(voterList, 3, 'quantiles');
if (!_.isUndefined(item)) {
var voters = item.voters,
minVoters = regionData.min_voters,
maxVoters = regionData.max_voters;
var alpha = colorScale(voters);
return alpha;
}
else {
return 0;
}
}
Does anyone know why changing the number of buckets or classification method does not change anything?
Strange... I looked into it and I do think there is a problem with the library. Let's consider a very simple and documented example.
If you look at the documentation on github, here is what is written (https://github.com/gka/chroma.js/wiki/Color-Scales):
// Calling .domain() with no arguments will return the current domain.
chroma.scale(['white', 'red']).domain([0, 100], 4).domain() // [0, 25, 50, 75, 100]
When I do the same, however, this returns [0,100] (and not [0, 25, 50, 75, 100]); as you said, the second argument has not changed anything. You may want to flag that behavior as a bug on the plugin github page. Unless someone has a good explanation?
I was having the same problem, then I realized that at the time I defined 'ColorScale', my domain was not yet populated. are you certain that 'voterList' had your dataset in it at the time you defined ColorScale?
Suppose, I have the following piece of code:
var brd2 = JXG.JSXGraph.initBoard('box2', {boundingbox: [-8.75, 2.5, 8.75, -2.5]});
var ax2 = brd2.create('axis', [[0,0],[1,0]]);
How can I change second point of axis?
Something like ax2.setSecondPoint([2,0])?
In general, how can I set property of any element?
Thank you.
Axis has two properties which names are self-explanatory: point1 and point2.
You can use setPosition method on any of them, e.g.
ax2.point2.setPosition(JXG.COORDS_BY_USER,[2,0])
Now there is one catch: you will not see this change on the chart unless you set needsRegularUpdate property of the axis object to true. Finally, to refresh the chart you should execute fullUpdate() method on the board variable. The whole looks like this:
var brd2 = JXG.JSXGraph.initBoard('box2', {boundingbox: [-8.75, 2.5, 8.75, -2.5]});
var ax2 = brd2.create('axis', [[0,0],[1,0]],{needsRegularUpdate:true});
ax2.point2.setPosition(JXG.COORDS_BY_USER,[2,0]);
brd2.fullUpdate();
References:
http://jsxgraph.uni-bayreuth.de/docs/symbols/JXG.Point.html#setPosition
http://jsxgraph.uni-bayreuth.de/wiki/index.php/Options (search for "special axis options")
Now to change properties like fixed, visible, etc. you should use setAttribute method (setProperty is deprecated). Example:
// Set property directly on creation of an element using the attributes object parameter
var board = JXG.JSXGraph.initBoard('jxgbox', {boundingbox: [-1, 5, 5, 1]};
var p = board.create('point', [2, 2], {visible: false});
// Now make this point visible and fixed:
p.setAttribute({
fixed: true,
visible: true
});
Source:
http://jsxgraph.uni-bayreuth.de/docs/symbols/JXG.GeometryElement.html#setAttribute
Last but not least a simple formula:
a + b = c
where:
a = using JavaScript debugging tools in browsers to investigate object properties
b = checking documentation for products you use
c= success :)