How to convert a tensor to a Uint8Array array in tensorflowjs - tensorflow.js

I use model.predict()to output a tensor A(size:512*512*3) by tensorflow.js and then I reshape it to A.reshape(512*512*3). But now I want to convert this tensor to an array so I can use it with three.js. How to solve this problem?

To convert a tensor to an array, You can use
data() or dataSync() to have a flatten typedarray
But currently the supported types are float32, int32; therefore the corresponding typedArray will be Float32Array and Int32Array. The typedarray constructors can be used to change the type of the typedarray
a = tf.tensor([1, 2, 3, 4])
buffer = a.dataSync().buffer
console.log(new Uint8Array(buffer))
console.log(new Uint16Array(buffer))
console.log(new Float32Array(buffer))
// To retrieve easily uint8 type, one can cast the tensor to `int32`
a = tf.tensor([1, 2, 3, 4], undefined, 'int32')
console.log(a.dtype)
buffer = a.dataSync().buffer
console.log(new Uint8Array(buffer))
console.log(new Float32Array(buffer))
<html>
<head>
<!-- Load TensorFlow.js -->
<script src="https://cdn.jsdelivr.net/npm/#tensorflow/tfjs#1.0.0"> </script>
</head>
<body>
</body>
</html>

Related

HERE maps - how to get all visible clusters?

I want to get array of currently visible clusters and then get each point data. I create method in React and it seems that method in theme for getClusterPresentation returns all possible clusters for all map zooms. How to get clusters data? This is my code:
const dataPoints = points.map(
point => new H.clustering.DataPoint(point.lat, point.lng, undefined, point),
);
const clusteredDataProvider = new H.clustering.Provider(dataPoints, {
clusteringOptions: {
eps: 32,
minWeight: 2,
},
});
const defaultTheme = clusteredDataProvider.getTheme();
clusteredDataProvider.setTheme({
getClusterPresentation: cluster => {
const clusterMarker = defaultTheme.getClusterPresentation(cluster);
return clusterMarker;
},
getNoisePresentation: noisePoint => {},
});
const layer = new H.map.layer.ObjectLayer(clusteredDataProvider);
map.addLayer(layer);
Please check the below code related to Marker Clustering. And you check same example in our Guide
/**
* Display clustered markers on a map
*
* Note that the maps clustering module https://js.api.here.com/v3/3.1/mapsjs-clustering.js
* must be loaded to use the Clustering
* #param {H.Map} map A HERE Map instance within the application
* #param {Object[]} data Raw data that contains airports' coordinates
*/
function startClustering(map, data) {
// First we need to create an array of DataPoint objects,
// for the ClusterProvider
var dataPoints = data.map(function (item) {
return new H.clustering.DataPoint(item.latitude, item.longitude);
});
// Create a clustering provider with custom options for clusterizing the input
var clusteredDataProvider = new H.clustering.Provider(dataPoints, {
clusteringOptions: {
// Maximum radius of the neighbourhood
eps: 32,
// minimum weight of points required to form a cluster
minWeight: 2
}
});
// Create a layer tha will consume objects from our clustering provider
var clusteringLayer = new H.map.layer.ObjectLayer(clusteredDataProvider);
// To make objects from clustering provder visible,
// we need to add our layer to the map
map.addLayer(clusteringLayer);
}
/**
* Boilerplate map initialization code starts below:
*/
// Step 1: initialize communication with the platform
// In your own code, replace variable window.apikey with your own apikey
var platform = new H.service.Platform({
apikey: window.apikey
});
var defaultLayers = platform.createDefaultLayers();
// Step 2: initialize a map
var map = new H.Map(document.getElementById('map'), defaultLayers.vector.normal.map, {
center: new H.geo.Point(30.789, 33.790),
zoom: 2,
pixelRatio: window.devicePixelRatio || 1
});
// add a resize listener to make sure that the map occupies the whole container
window.addEventListener('resize', () => map.getViewPort().resize());
// Step 3: make the map interactive
// MapEvents enables the event system
// Behavior implements default interactions for pan/zoom (also on mobile touch environments)
var behavior = new H.mapevents.Behavior(new H.mapevents.MapEvents(map));
// Step 4: create the default UI component, for displaying bubbles
var ui = H.ui.UI.createDefault(map, defaultLayers);
// Step 5: cluster data about airports's coordinates
// airports variable was injected at the page load
startClustering(map, airports);
#map {
width: 95%;
height: 450px;
background: grey;
}
#panel {
width: 100%;
height: 400px;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=yes">
<meta http-equiv="Content-type" content="text/html;charset=UTF-8">
<title>Marker Clustering</title>
<link rel="stylesheet" type="text/css" href="https://js.api.here.com/v3/3.1/mapsjs-ui.css" />
<link rel="stylesheet" type="text/css" href="demo.css" />
<link rel="stylesheet" type="text/css" href="styles.css" />
<link rel="stylesheet" type="text/css" href="../template.css" />
<script type="text/javascript" src='../test-credentials.js'></script>
<script type="text/javascript" src="https://js.api.here.com/v3/3.1/mapsjs-core.js"></script>
<script type="text/javascript" src="https://js.api.here.com/v3/3.1/mapsjs-service.js"></script>
<script type="text/javascript" src="https://js.api.here.com/v3/3.1/mapsjs-ui.js"></script>
<script type="text/javascript" src="https://js.api.here.com/v3/3.1/mapsjs-mapevents.js"></script>
<script type="text/javascript" src="https://js.api.here.com/v3/3.1/mapsjs-clustering.js"></script>
<script type="text/javascript" src="./data/airports.js"></script>
</head>
<body id="markers-on-the-map">
<div class="page-header">
<h1>Marker Clustering</h1>
<p>Cluster multiple markers together to better visualize the data</p>
</div>
<p>This example displays a map showing the distribution of
airports across the world. The locations were obtained by using
the OpenFlights Airport Database.
Instead of adding a marker for each location, the data has been clustered,
and individual airports are only shown at higher zoom levels.</p>
<div id="map"></div>
<h3>Code</h3>
<p>Marker clustering requires the presence of the <code>mapsjs-clustering</code> module of the API.
The <code>H.clustering.Provider</code> class is used to load in data points and prepare them for clustering.
The result is added to the map as an additional layer using the <code>map.addLayer()</code> method.</p>
<script type="text/javascript" src='demo.js'></script>
</body>
</html>

Bing Map V8 Cluster Pass real time data

I am just starting with Bing map. Gone through few examples in official documentation.
Example from Bing map V8 official documentation
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta charset="utf-8" />
<script type='text/javascript'
src='http://www.bing.com/api/maps/mapcontrol?callback=GetMap' async defer></script>
<script type="text/javascript">
var map, clusterLayer;
function GetMap() {
map = new Microsoft.Maps.Map('#myMap',{
credentials: 'Your Bing Maps Key',
zoom: 3
});
Microsoft.Maps.loadModule("Microsoft.Maps.Clustering", function () {
//Generate 3000 random pushpins in the map view.
var pins = Microsoft.Maps.TestDataGenerator.getPushpins(3000, map.getBounds());
//Create a ClusterLayer with options and add it to the map.
clusterLayer = new Microsoft.Maps.ClusterLayer(pins, {
clusteredPinCallback: customizeClusteredPin
});
map.layers.insert(clusterLayer);
});
}
function customizeClusteredPin(cluster) {
//Add click event to clustered pushpin
Microsoft.Maps.Events.addHandler(cluster, 'click', clusterClicked);
}
function clusterClicked(e) {
if (e.target.containedPushpins) {
var locs = [];
for (var i = 0, len = e.target.containedPushpins.length; i < len; i++) {
//Get the location of each pushpin.
locs.push(e.target.containedPushpins[i].getLocation());
}
//Create a bounding box for the pushpins.
var bounds = Microsoft.Maps.LocationRect.fromLocations(locs);
//Zoom into the bounding box of the cluster.
//Add a padding to compensate for the pixel area of the pushpins.
map.setView({ bounds: bounds, padding: 100 });
}
}
</script>
</head>
<body>
<div id="myMap" style="position:relative;width:600px;height:400px;"></div>
</body>
</html>
In above bing map cluster example how to replace the TestDataGenerator data with realtime data JSON like below
mapData = [{"Name":"Point: 0","Latitude":22.0827,"Longitude":80.2707},
{"Name":"Point: 1","Latitude":24.0827,"Longitude":80.2707},
{"Name":"Point: 2","Latitude":26.0827,"Longitude":80.2707},
{"Name":"Point: 3","Latitude":28.0827,"Longitude":80.2707},
{"Name":"Point: 4","Latitude":20.0827,"Longitude":80.2707},
{"Name":"Point: 5","Latitude":22.0827,"Longitude":82.2707},
{"Name":"Point: 6","Latitude":30.0827,"Longitude":80.2707},
{"Name":"Point: 7","Latitude":22.0827,"Longitude":84.2707},
{"Name":"Point: 8","Latitude":32.0827,"Longitude":84.2707},
{"Name":"Point: 9","Latitude":18.0827,"Longitude":80.2707}];
When I pass above object in ClusterLayer I am getting following error
Uncaught TypeError: i[t].getLocation is not a function(…)
You have to loop through your data and turn it into pushpins. Here's a code sample:
var pins = [];
for(var i = 0;i < mapData.length;i++){
var pin = new Microsoft.Maps.Pushpin(new Microsoft.Maps.Location(mapData[i].Latitude, mapData[i].Longitude));
//Store the original data object in the pushpins metadata so that you can access other properties like Name.
pin.metedata = mapData[i];
pins.push(pin);
}
//Now "pins" is an array of pushpins. Add them to the map or to the clustering layer.

Iterate through two objects in Handlebars

I have a backbone model that I'm trying to extract specific values from. Something like: (using raw Object but assume its a backbone Model)
var x = {
primary : ["a","b","c"],
attributes : {
a : 1,
b : 2,
d : 4
}
}
In the end, it should render 1 2
I'm thinking something like
{{#each primary}}
{{#if attributes[this]}}{{attributes[this]}}{{/if}}
{{/each}}
but that doesn't seem to work. Ideas?
There is lookup helper made for it:
The lookup helper allows for dynamic parameter resolution using Handlebars variables. This is useful for resolving values for array indexes.
var source = $("#template").html();
var template = Handlebars.compile(source);
var data = {
primary : ["a","b","c"],
attributes : {
a : 1,
b : 2,
d : 4
}
};
$('body').append(template(data));
<script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/4.0.11/handlebars.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script id="template" type="text/x-handlebars-template">
{{#primary}}
{{lookup ../attributes this}}
{{/primary}}
</script>

Javascript: Can array shift and reverse methods not be called in the same line of code?

This single line in javascript:
myarray.reverse().shift().reverse()
doesn't seem to work in the same way as the three separate lines
myarray.reverse();
myarray.shift();
myarray.reverse();
Is this expected? Or is it a bug?
I know I can replace this with
myarray.pop();
but that's not the point. I want to understand what is the expected behavior.
I made a small html to demonstrate this:
<html> <body>
<button onclick="myFunction1()">Func1</button>
<button onclick="myFunction2()">Func2</button>
<p id="demo"></p>
<script>
var fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo").innerHTML = fruits;
function myFunction1() {
fruits.reverse();
fruits.shift();
fruits.reverse();
document.getElementById("demo").innerHTML = fruits;
}
function myFunction2() {
fruits.reverse().shift().reverse();
document.getElementById("demo").innerHTML = fruits;
}
</script>
</body> </html>
I expected both Func1 and Func2 to act the same way., but the Func2 button doesn't work as expected, although Func1 does.
You cannot just chain method calls like that in JavaScript. The later calls will be invoked on the return value of the previous call, not on the original object.
myArray.shift() returns the (formerly) first element of the array. It does not return the (original or the modified) array (reverse does return the array after updating it in-place).
So myArray.shift().reverse() reverses the first element.
Whereas myArray.shift(); myArray.reverse(); first removes the first element and then reverses the rest of the array.

Google Map v3 Ground Overlay?

I have spent two days puzzling this and failed. Any assistance will be greatly appreciated.
I need a map centered on -18.975750, 32.669184 in a canvas of 1500px x 900px. I then to need to overlay coverage PNGs (obtained form www.heywhatsthat.com) with set code- transparency.
I have eventually arrived at the following code and it fails. I would like to add more than one PNG bound by it's co-ords, but cant even get one to work.
<script src="http://maps.google.com/maps?file=api&v=3&key=AIzaSyAGbZjXr2wr7dT2P3O5pNo5wvVF3JiaopU&sensor=false"
type="text/javascript"></script>
<script type="text/javascript">
function initialize() {
if (GBrowserIsCompatible()) {
var map = new google.maps.MAP(document.getElementById("map_canvas"));
map.setCenter(new GLatLng(-18.975750, 32.669184), 13);
map.setUIToDefault();
var imageBounds = new google.maps.LatLngBounds(
new google.maps.LatLng(-19.000417,30.999583),
new google.maps.LatLng(-17.999583,32.000417));
var oldmap = new google.maps.GroundOverlay(
"http://www.earthstation.mobi/cloakpS19E031.png",imageBounds);
oldmap.setMap(map);
}
</script>
</head>
<body onload="initialize()" onunload="GUnload()">
<div id="map_canvas" style="width: 1500px; height: 900px"></div>
</body>
</html>
What am I mssing and please point me in the right direction add multiple png overlays with transparency in the options.
Thanks
Brian
Zimbabwe
You have a lot of issues with your code. It looks like you're trying to migrate from V2 to V3, and you still have V2 methods and objects in your code. You're also not loading the JS APi correctly when you call in the of your HTML.
Here is functional code that displays the overlay using the V3 API, but it looks like the original center coordinates that you used do not place the map at the center of the overlay (you'll need to figure that out yourself). I've added comments where relevant so that you can see where you went astray. Note the call to the API library in the first script tag.
<script src="http://maps.googleapis.com/maps/api/js?key=AIzaSyAGbZjXr2wr7dT2P3O5pNo5wvVF3JiaopU&sensor=false"
type="text/javascript"></script>
<script type="text/javascript">
function initialize() {
//You don't need to use GBrowserIsCompatible, it's only for V2 of the API
//if (GBrowserIsCompatible()) {
//You need to set up options for the map that you reference when you
//instantiate the map object
var myOptions = {
center: new google.maps.LatLng(-18.975750, 32.669184),
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
//Your code references google.maps.MAP; it's google.maps.Map
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
var imageBounds = new google.maps.LatLngBounds(
new google.maps.LatLng(-19.000417,30.999583),
new google.maps.LatLng(-17.999583,32.000417));
var oldmap = new google.maps.GroundOverlay(
"http://www.earthstation.mobi/cloakpS19E031.png",imageBounds);
oldmap.setMap(map);
//} <--Your code was missing this closing bracket for the conditional
//But the conditional is not even needed, since GBrowserCompatible is a V2 thing
}
</script>
</head>
<body onload="initialize()">
<div id="map_canvas" style="width: 1500px; height: 900px"></div>
</body>
</html>

Resources