output of predict in Tensorflow.js always show first example - tensorflow

I recently learning an image classifier using TensorFlow js in the browser, I made a simple image classification that can identify an image of Giorno and Jotaro, but when predicting a new image, the result always shows the first example(Jotaro) which I added, I'm trying to check the second function which added second example(Giorno), It just fine in console, and running well, this is my code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Giorno and Jotaro Classifier</title>
<script src="https://cdn.jsdelivr.net/npm/#tensorflow/tfjs/dist/tf.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/#tensorflow-models/mobilenet"></script>
<script src="https://cdn.jsdelivr.net/npm/#tensorflow-models/knn-classifier"></script>
</head>
<body>
<h1>Test Image</h1>
<img id="predict" src="anime/test_giorno.jpg" alt="" width="300">
</body>
</html>
<script>
const initScript = async function(){
const ClassifierKNN = knnClassifier.create();
const mobileneModule = await mobilenet.load();
for(let i=1; i<=3;i++){
const im = new Image(300,300);
im.src = 'anime/jotaro/'+i+'.jpg';
im.onload = ()=>{
let trainingImageJotaro = tf.browser.fromPixels(im);
let predJotaro = mobileneModule.infer(trainingImageJotaro,'conv_preds');
if(i)
ClassifierKNN.addExample(predJotaro,"Jotaro");
}
im.onload();
}
for(let i=1; i<=3;i++){
const im2 = new Image(300,300);
im2.src = 'anime/giorno/'+i+'.jpg';
im2.onload = ()=>{
let trainingImageGiorno = tf.browser.fromPixels(im2);
let predGiorno = mobileneModule.infer(trainingImageGiorno,'conv_preds');
ClassifierKNN.addExample(predGiorno,"Giorno");
}
im2.onload();
}
let imgX = document.getElementById('predict');
const tensorX = tf.browser.fromPixels(imgX);
const logitsX = mobileneModule.infer(tensorX,'conv_preds');
let result = await ClassifierKNN.predictClass(logitsX);
console.log('outout:');
console.log(result);
}
initScript();
</script>
the result of the script is always jotaro, but when I switch the loop position like this:
for(let i=1; i<=3;i++){
const im2 = new Image(300,300);
im2.src = 'anime/giorno/'+i+'.jpg';
im2.onload = ()=>{
let trainingImageGiorno = tf.browser.fromPixels(im2);
let predGiorno = mobileneModule.infer(trainingImageGiorno,'conv_preds');
ClassifierKNN.addExample(predGiorno,"Giorno");
}
im2.onload();
}
for(let i=1; i<=3;i++){
const im = new Image(300,300);
im.src = 'anime/jotaro/'+i+'.jpg';
im.onload = ()=>{
let trainingImageJotaro = tf.browser.fromPixels(im);
let predJotaro = mobileneModule.infer(trainingImageJotaro,'conv_preds');
if(i)
ClassifierKNN.addExample(predJotaro,"Jotaro");
}
im.onload();
}
the result always Giorno, can anyone help me with this problem?

Thanks #zer0sign, for sharing the solution in comments. For the benefit of community I am providing solution here (answer section)
This problem has been fixed, above issue occurs because, the second training data is executed after the testing data, therefore the code above only gets 1 label, because the second label has not been executed and therefore the output label of the predicted image always shows the label of the first training data.

Related

Why my JSONP Code doesn't save results into PDF file after converting from template in Google App Script

I'm trying to save my results into PDF file after google sheet calculation. Here's my google sheet file: Google sheet(img)
After someone submit my form J Column sum all answers and gets 39. Then I want to convert my template file template(img) to PDF, so I wrote this code:
function afterFormSubmit(e) {
Logger.log(JSON.stringify(e));
var formValues = e.namedValues;
Logger.log(formValues);
const info = e.namedValues;
createPDF(info);
}
function createPDF(info){
const pdfFolder = DriveApp.getFolderById("1YPyX8gv3W-JXR0uovMdr");
const tempFolder = DriveApp.getFolderById("1m9Xcc9hmhJjc83cSgCW26u");
const templateDoc = DriveApp.getFileById("1r4m3-FtzMzlO_SmGMPuGraJhEIBsQA");
const newTempFile = templateDoc.makeCopy(tempFolder);
const openDoc = DocumentApp.openById(newTempFile.getId())
const body = openDoc.getBody();
body.replaceText("{T}", info['Timestamp'][0]);
body.replaceText("{A2}" ,info['answer2'][0]);
body.replaceText("{A3}" ,info['answer3'][0]);
body.replaceText("{A4}" ,info['answer4'][0]);
body.replaceText("{A5}" ,info['answer5'][0]);
body.replaceText("{A6}" ,info['answer6'][0]);
body.replaceText("{A7}" ,info['answer7'][0]);
body.replaceText("{E}", info['Email'][0]);
body.replaceText("{R}" ,info['Results'][0]); //Please fix it: PDF Not showing/Saving Results
openDoc.saveAndClose();
const blobPDF = newTempFile.getAs(MimeType.PDF);
const pdfFile = pdfFolder.createFile(blobPDF).setName("Quiz finish time:"+" "+ info['Timestamp'][0]);
tempFolder.removeFile(newTempFile);
}
But when this code converts my template file to PDF he don't show/save my result {R} PDF(img), but all other body.replaceText(); works well. Maybe someone know how to deal with that (how to save/show Result into PDF file)?
I get response that my google app script code is only for google form responses... So my first code didn't works to get Results... But this one is what I'm looked for:
function afterFormSubmit() {
var ss= SpreadsheetApp.openById("YOUR_SHEET_ID").getSheetByName("SHEET_NAME");
ss.getLastRow();
var info=ss.getRange("A"+ss.getLastRow()+":J"+ss.getLastRow()).getValues()[0];
Logger.log(info);
createPDF(info);
}
function createPDF(info){
const pdfFolder = DriveApp.getFolderById("FOLDER_ID");
const tempFolder = DriveApp.getFolderById("FOLDER_ID");
const templateDoc = DriveApp.getFileById("DOC_ID");
const newTempFile = templateDoc.makeCopy(tempFolder);
const openDoc = DocumentApp.openById(newTempFile.getId())
const body = openDoc.getBody();
var dt=Utilities.formatDate(info[0],"GMT"-5.00,"MM/dd/YYYY HH:mm:ss");
body.replaceText("{T}", dt);
body.replaceText("{A3}" ,info[2]);
body.replaceText("{A4}" ,info[3]);
body.replaceText("{A5}" ,info[4]);
body.replaceText("{A6}" ,info[5]);
body.replaceText("{A7}" ,info[6]);
body.replaceText("{E}", info[7]);
body.replaceText("{A2}" ,info[8]);
body.replaceText("{R}" ,info[9]);
openDoc.saveAndClose();
const blobPDF = newTempFile.getAs(MimeType.PDF);
const pdfFile = pdfFolder.createFile(blobPDF).setName("Quiz finish time:"+" "+ dt);
tempFolder.removeFile(newTempFile);
}
````

Convert an existing Kinect RGB infrared image to an array of distances

I have a screenshot of the infrared output of a Kinect using OpenKinect on a Mac.
I would like to calculate the distance of the green wall and the orange posts. I'm only bothered about a single dimension array, say y = 240 (along the horizontal center of the image).
I have tried using MarvinJ to convert the image to greyscale and save the colour value to an array, but I quickly found that this is not the way to go about this, due to the integer colour values of the greyscale image are very similar and do not represent the depth well enough.
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Greyscale Test</title>
</head>
<body>
<script src="https://www.marvinj.org/releases/marvinj-0.9.js"></script>
<script>
image = new MarvinImage();
image.load("ir_test.png", imageLoaded);
function imageLoaded() {
var imageOut = new MarvinImage(image.getWidth(), image.getHeight());
var image2 = new MarvinImage(image.getWidth(), image.getHeight());
Marvin.invertColors(image, image2);
Marvin.invertColors(image2, imageOut);
var y = 240;
var colour_array = [];
for (var x = 0; x < imageOut.getWidth(); x++) { // For loop to loop through the x-axis
var colour = imageOut.getIntComponent0(x, y);
colour_array.push(colour);
}
document.getElementById('colour_array_div').innerHTML = colour_array;
}
</script>
<div id="colour_array_div"></div>
</body>
</html>
What I'm trying to work out is how to convert the colour to a distance, preferably in millimeters.
I ended up converting each pixel to their RGB hex values and then converted the hex value to a decimal number.
This gave me a range of values between 0 and 16777215.
I copied the output to a CSV file then processed the value of each pixel in Excel. I converted the decimal colour value to a distance in meters.
I found the range of the Kinect's depth sensor to be 0.8m-3.5m [https://openkinect.org/wiki/Imaging_Information]
I converted the decimal value to a meter value using an answer from this question: Excel Function name to map one ratio to another
value/(inhi-inlo)*(outhi-outlo)+outlo
Here is a graph of the output:
The code I used to generate the array of decimal colour values is:
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Colour Test</title>
</head>
<body>
<script src="https://www.marvinj.org/releases/marvinj-0.9.js"></script>
<script>
image = new MarvinImage();
image.load("ir_test.png", imageLoaded);
function imageLoaded() {
var imageOut = new MarvinImage(image.getWidth(), image.getHeight());
var image2 = new MarvinImage(image.getWidth(), image.getHeight());
Marvin.invertColors(image, image2);
Marvin.invertColors(image2, imageOut);
var y = 240;
var colour_array = [];
for (var x = 0; x < imageOut.getWidth(); x++) { // For loop to loop through the x-axis
var red = imageOut.getIntComponent0(x, y);
var green = imageOut.getIntComponent1(x, y);
var blue = imageOut.getIntComponent2(x, y);
var hex_colour = rgbToHex(red,green,blue);
var colour = parseInt(hex_colour, 16); //https://stackoverflow.com/questions/57803/how-to-convert-decimal-to-hexadecimal-in-javascript
colour_array.push(colour);
}
document.getElementById('colour_array_div').innerHTML = colour_array;
}
//https://stackoverflow.com/questions/5623838/rgb-to-hex-and-hex-to-rgb
function componentToHex(c) {
var hex = c.toString(16);
return hex.length == 1 ? "0" + hex : hex;
}
function rgbToHex(r, g, b) {
return componentToHex(r) + componentToHex(g) + componentToHex(b);
}
</script>
<div id="colour_array_div"></div>
</body>
</html>

http-equiv="X-UA-Compatible" and IE - 9 compatibility view - site crashes

I added this tag:
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
in to my header.
In IE 9 my browser crashes if I add the domain of my site in to the compatibility view list of the browser and then I call my website.
Also the browser crashes if I work on IE 11 and I am going to browsermode 9.
I have to add this meta tag.
What can I do?
Where do I wrong?
additional:
I found out that this meta tag doesn`t work well in combination with this part of script:
window.CSSHover = (function(){
var REG_INTERACTIVE = /(^|\s)((([^a]([^ ]+)?)|(a([^#.][^ ]+)+)):(hover))/i,
REG_AFFECTED = /(.*li?|.*ul?)\:(hover)/i,
REG_PSEUDO = /[^:]+:([a-z-]+).*/i,
REG_SELECT = /(\.([a-z0-9_-]+):[a-z]+)|(:[a-z]+)/gi,
REG_CLASS = /\.([a-z0-9_-]*on(hover))/i,
REG_MSIE = /msie (5|6|7|8|9)/i,
REG_COMPAT = /backcompat/i;
var CSSHOVER_PREFIX = 'csh-';
var CSSHover = {
elements: [],
I am calling this script in the body with: [%- IF BROWSER=="MSIE" AND BROWSERVERSION < "9.0" -%]style="behavior: url(/css/csshover.h);" [%- END -%]
callbacks: {},
init:function() {
if(!REG_MSIE.test(navigator.userAgent) && !REG_COMPAT.test(window.document.compatMode)) return;
var sheets = window.document.styleSheets, l = sheets.length;
for(var i=0; i<l; i++) {
this.parseStylesheet(sheets[i]);
}
},

Is there a working sample of the Google custom search rest API?

I need to create a screen which automates Google search.
I know JavaScript and I'm trying to get GSE works.
I have a search engine and an API key.
The problem is Google's documentation is cyclic i.e. pages point to each other.
There is no working sample from where I can start my research.
Please help if you know of a working sample.
The documents I have read are:
cselement-devguide
introduction
I know this is an old question, but here is what I did to make the API results formatted like the Google Site Search used to give since they are ending the paid accounts and will have ads now. The API way has an option to pay still for over 100 searches per day, so going with that but had to format the results still, and used the existing one to build the css to do similar styling also.
Search form going to this page is just a simple:
<form action="search-results.htm" id="cse-search-box">
<div>
<input class="" name="q" type="text">
<input class="" type="submit">
</div>
</form>
and then the search results page:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<title>JSON/Atom Custom Search API Example</title>
<!--<link href="default.css" rel="stylesheet" type="text/css">-->
<link href="google.css" rel="stylesheet" type="text/css">
</head>
<body>
<div class="gsc-result-info" id="resInfo-0"></div>
<hr/>
<div id="googleContent"></div>
<script>
//Handler for response from google.
function hndlr(response) {
if (response.items == null) {
//Sometimes there is a strange thing with the results where it says there are 34 results/4 pages, but when you click through to 3 then there is only 30, so page 4 is invalid now.
//So if we get to the invalid one, send them back a page.
window.location.replace("searchresults.htm?start=" + (start - 10) + "&q=" + query);
return;
}
//Search results load time
document.getElementById("resInfo-0").innerHTML = "About " + response.searchInformation.formattedTotalResults + " results (" + response.searchInformation.formattedSearchTime + " seconds)";
//Clear the div first, CMS is inserting a space for some reason.
document.getElementById("googleContent").innerHTML = "";
//Loop through each item in search results
for (var i = 0; i < response.items.length; i++) {
var item = response.items[i];
var content = "";
content += "<div class='gs-webResult gs-result'>" +
"<table class='gsc-table-result'><tbody><tr>";
//Thumbnail image
if (item.pagemap.cse_thumbnail != null)
content += "<td class='gsc-table-cell-thumbnail gsc-thumbnail'><div class='gs-image-box gs-web-image-box gs-web-image-box-portrait'><a class='gs-image' href='" + item.link + "'>" +
"<img class='gs-image' class = 'gs-image-box gs-web-image-box gs-web-image-box-portrait' src='" + item.pagemap.cse_thumbnail[0].src + "'></a></td>";
//Link
content += "<td><a class='gs-title' href='" + item.link + "'>" + item.htmlTitle + "</a><br/>";
//File format for PDF, etc.
if (item.fileFormat != null)
content += "<div class='gs-fileFormat'><span class='gs-fileFormat'>File Format: </span><span class='gs-fileFormatType'>" + item.fileFormat + "</span></div>";
//description text and URL text.
content += item.htmlSnippet.replace('<br>','') + "<br/><div class='gs-bidi-start-align gs-visibleUrl gs-visibleUrl-long' dir='ltr' style='word-break:break-all;'>" + item.htmlFormattedUrl +"</div>" +
"<br/></td></tr></tbody></table></div>";
document.getElementById("googleContent").innerHTML += content;
}
//Page Controls
var totalPages = Math.ceil(response.searchInformation.totalResults / 10);
console.log(totalPages);
var currentPage = Math.floor(start / 10 + 1);
console.log(currentPage);
var pageControls = "<div class='gsc-results'><div class='gsc-cursor-box gs-bidi-start-align' dir='ltr'><div class='gsc-cursor'>";
//Page change controls, 10 max.
for (var x = 1; x <= totalPages && x<=10; x++) {
pageControls += "<div class='gsc-cursor-page";
if (x === currentPage)
pageControls += " gsc-cursor-current-page";
var pageLinkStart = x * 10 - 9;
pageControls+="'><a href='search-results.htm?start="+pageLinkStart+"&q="+query+"'>"+x+"</a></div>";
}
pageControls += "</div></div></div>";
document.getElementById("googleContent").innerHTML += pageControls;
}
//Get search text from query string.
var query = document.URL.substr(document.URL.indexOf("q=") + 2);
var start = document.URL.substr(document.URL.indexOf("start=") + 6, 2);
if (start === "1&" || document.URL.indexOf("start=") === -1)
start = 1;
//Load the script src dynamically to load script with query to call.
// DOM: Create the script element
var jsElm = document.createElement("script");
// set the type attribute
jsElm.type = "application/javascript";
// make the script element load file
jsElm.src = "https://www.googleapis.com/customsearch/v1?key=yourApikeyhere&cx=yoursearchengineidhere&start="+start+"&q=" +query +"&callback=hndlr";
// finally insert the element to the body element in order to load the script
document.body.appendChild(jsElm);
</script>
</body>
</html>

Get the hostname with action script 2

I am creating some campaign swf banners and I don't use action script very often so any help from the experts would be great thanks.
I am supplying my banners on my website as resource downloads. And tutorials of how to embed the swf which has some javascript flashvars.
These flash variable is then concatenated into a google campaign link to change the utm_source.
This is my javascript...
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/swfobject/2.2/swfobject.js"></script>
<script type="text/javascript">
var flashvars = {};
flashvars.campaignSource = window.location.hostname;
var params = {};
params.loop = "true";
params.quality = "best";
params.wmode = "opaque";
params.swliveconnect = "true";
params.allowscriptaccess = "always";
var attributes = {};
swfobject.embedSWF("banner.swf", "banner_mpu", "300", "250", "9.0.0", false, flashvars, params, attributes);
</script>
and my html...
<div id="banner_mpu">
<a href="http://www.adobe.com/go/getflashplayer">
<img src="http://www.adobe.com/images/shared/download_buttons/get_flash_player.gif" alt="Get Adobe Flash player" />
</a>
</div>
So the above js works great, however, not everyone will use my tutorial code and will probably use there own methods to embed the swf banner on their site.
So I need some back up action script 2 to get the current hostname into a action script variable
This is my action script which I have so far on my button (swf)...
on(release) {
function GetTheHostname() {
var RootFullUrl = _root._url;
txtFullUrl.text = RootFullUrl;
var lastSlashIndex:Number = RootFullUrl.lastIndexOf("/");
var DriveIndex:Number = RootFullUrl.indexOf("|");
if (DriveIndex>=0) {
baseUrl = RootFullUrl.substring(0, DriveIndex);
baseUrl += ":";
} else {
baseUrl = "";
}
baseUrl += RootFullUrl.substring(DriveIndex+1, lastSlashIndex+1);
txtBaseUrl.text = baseUrl;
return baseUrl;
}
var campaignSourceAS2:String= GetTheHostname();
if ( _root.campaignSource == undefined ) {
getURL("http://www.mysite.co.uk/?utm_source=" + campaignSourceAS2 + "&utm_medium=MPU&utm_campaign=My%20Campaign%202012", "_blank");
} else {
getURL("http://www.mysite.co.uk/?utm_source=" + _root.campaignSource + "&utm_medium=MPU&utm_campaign=My%20Campaign%202012", "_blank");
}
}
The problem with my action script is that it returns the full current URL.
Can any one please help me adapt the GetTheHostname function to get the host name instead of the baseURL
Thanks in advance
In that case, I guess it would be as easy as stripping the http:// from the url and then get all that's left to the first /
A one-liner to go from 'http://www.example.com/category/actionscript' to 'www.example.com' would be
var baseURL:String = _root._url.split("http://").join("").split("/")[0];
and to replace your full method
getURL("http://www.mysite.co.uk/?utm_source=" + (_root.campaignSource || _root._url.split("http://").join("").split("/")[0]) + "&utm_medium=MPU&utm_campaign=My%20Campaign%202012", "_blank");