Skip to content

Instantly share code, notes, and snippets.

@ryu39
Created January 1, 2016 03:34
Show Gist options
  • Save ryu39/a17211fb04f8a33197cc to your computer and use it in GitHub Desktop.
Save ryu39/a17211fb04f8a33197cc to your computer and use it in GitHub Desktop.
Test page for Cloud Vision API presented by Google.
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Cloud Vision API Test</title>
<!-- Bootstrap -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
<!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<!-- Include all compiled plugins (below), or include individual files as needed -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js" integrity="sha384-0mSbJDEHialfmuBBQP6A4Qrprq5OVfW37PRR3j5ELqxss1yVqOtnepnHVP9aJ7xS" crossorigin="anonymous"></script>
<script>
var escapeHtml = (function (String) {
var escapeMap = {
'&': '&amp;',
"'": '&#x27;',
'`': '&#x60;',
'"': '&quot;',
'<': '&lt;',
'>': '&gt;'
};
var escapeReg = '[';
var reg;
for (var p in escapeMap) {
if (escapeMap.hasOwnProperty(p)) {
escapeReg += p;
}
}
escapeReg += ']';
reg = new RegExp(escapeReg, 'g');
return function escapeHtml (str) {
str = (str === null || str === undefined) ? '' : '' + str;
return str.replace(reg, function (match) {
return escapeMap[match];
});
};
}(String));
$(function() {
var API_KEY = 'Please write your api key here.';
var MAX_RESULT_NUM = 10;
var LINE_COLOR = "rgb(255, 0, 0)";
var FONT_SIZE = 24;
var STRATEGIES = {
FACE_DETECTION: {
resultAttrName: 'faceAnnotations',
outputAttrNames: ['boundingPoly', 'detectionConfidence', 'angerLikelihood', 'blurredLikelihood', 'headwearLikelihood', 'joyLikelihood', 'sorrowLikelihood', 'surpriseLikelihood', 'underExposedLikelihood'],
drawImage: true
},
LANDMARK_DETECTION: {
resultAttrName: 'landmarkAnnotations',
outputAttrNames: ['mid', 'locale', 'description', 'score', 'confidence', 'topicality'],
drawImage: false
},
LOGO_DETECTION: {
resultAttrName: 'logoAnnotations',
outputAttrNames: ['mid', 'locale', 'description', 'score', 'confidence', 'topicality'],
drawImage: false
},
LABEL_DETECTION: {
resultAttrName: 'labelAnnotations',
outputAttrNames: ['mid', 'locale', 'description', 'score', 'condidence', 'topicality'],
drawImage: false
},
TEXT_DETECTION: {
resultAttrName: 'textAnnotations',
outputAttrNames: ['boundingPoly', 'mid', 'locale', 'description', 'score', 'confidence', 'topicality'],
drawImage: true
},
}
function clearResult() {
var errorMsg = $('#error-msg');
if (errorMsg) {
errorMsg.remove();
}
$('#result-table thead').find('tr').remove();
$('#result-table tbody').find('tr').remove();
var canvas = $('#canvas')[0];
var ctx = canvas.getContext('2d');
ctx.clearRect(0, 0, canvas.width, canvas.height);
canvas.width = 0;
canvas.height = 0;
}
function showResult(results, attrNames) {
var row = '<tr><th>#</th>';
attrNames.forEach(function(name) {
row += '<th>' + escapeHtml(name) + '</th>'
});
row += '</tr>';
$('#result-table thead').append(row);
if (!results) {
return;
}
results.forEach(function(elem, i) {
row = '<tr><td>' + (i + 1) + '</td>';
attrNames.forEach(function(name) {
var attrVal = elem[name];
if ((typeof attrVal) === 'object') {
row += '<td>' + escapeHtml(JSON.stringify(attrVal)) + '</td>'
} else {
row += '<td>' + escapeHtml(attrVal) + '</td>'
}
});
row += '</tr>'
$('#result-table tbody').append(row);
});
}
function drawImageWithDetectedArea(canvas, results) {
if (!results) {
return;
}
var img = new Image();
img.src = $('#img').attr('src');
canvas.width = img.width;
canvas.height = img.height;
var ctx = canvas.getContext('2d');
ctx.drawImage(img, 0, 0);
results.forEach(function(elem, index) {
var vertices = elem.boundingPoly.vertices;
ctx.beginPath();
ctx.moveTo(vertices[0].x, vertices[0].y)
for (var i = 1; i < vertices.length; i++) {
ctx.lineTo(vertices[i].x, vertices[i].y);
}
ctx.closePath();
ctx.strokeStyle = LINE_COLOR;
ctx.stroke();
ctx.fillStyle = LINE_COLOR;
ctx.font = FONT_SIZE
ctx.fillText(index + 1, vertices[vertices.length-1].x, vertices[vertices.length-1].y);
})
}
$('#input-img').change(function() {
clearResult();
var file = $(this).prop('files')[0];
var imgElem = $('#img');
if (file) {
var reader = new FileReader();
reader.onload = function() {
imgElem.attr('src', reader.result);
};
reader.readAsDataURL(file);
} else {
imgElem.attr('src', '');
}
});
$('#submit-btn').click(function() {
clearResult();
var apiType = $('#api-type').val();
var imgDataUrl = $('#img').attr('src');
var encodedImg = imgDataUrl.substring(imgDataUrl.indexOf(',') + 1)
var params = {
requests: [
{
image: { content: encodedImg },
features: [
{ type: apiType, maxResults: MAX_RESULT_NUM }
]
}
]
};
var strategy = STRATEGIES[apiType];
$.ajax({
type: 'POST',
url: 'https://vision.googleapis.com/v1alpha1/images:annotate?key=' + API_KEY,
contentType: 'application/json',
data: JSON.stringify(params),
success: function(res) {
console.log(res);
var apiResponse = res.responses[0];
if (apiResponse.error) {
$('#result').append('<div id="error-msg" class="alert alert-danger">APIの呼び出しでエラーが発生しました。コンソールでエラー内容を確認してください。</div>');
return;
}
var results = apiResponse[strategy.resultAttrName];
showResult(results, strategy.outputAttrNames);
if (strategy.drawImage) {
var canvas = $('#canvas')[0];
drawImageWithDetectedArea(canvas, results);
}
}
});
return false;
});
});
</script>
</head>
<body>
<div class="container">
<h1>Cloud Vision API Test</h1>
<p>
GoogleからLimited Previewで公開されている<a href="https://cloud.google.com/vision/" target="_blank">Cloud Vision API</a>のテスト用ページです。テスト対象の画像とAPI種別を選択後、「送信」を押すと結果が下に表示されます。
</p>
<div>
<form>
<div class="form-group">
<label for="input-img">入力画像</label>
<input type="file" id="input-img" name="input-img" class="form-control" accept="image/*" multiple="false" />
</div>
<div class="form-group">
<img id="img" src="" class="img-responsive"></img>
</div>
<div class="form-group">
<label for="api-type">API種別</label>
<select id="api-type" name="api-type" class="form-control">
<option value="FACE_DETECTION">FACE_DETECTION</option>
<option value="LANDMARK_DETECTION">LANDMARK_DETECTION</option>
<option value="LOGO_DETECTION">LOGO_DETECTION</option>
<option value="LABEL_DETECTION">LABEL_DETECTION</option>
<option value="TEXT_DETECTION">TEXT_DETECTION</option>
</select>
</div>
<button id="submit-btn" class="btn btn-primary">送信</button>
</form>
</div>
<hr>
<div id="result">
<h2>結果</h2>
<table id="result-table" class="table table-striped">
<thead></thead>
<tbody></tbody>
</table>
<canvas id="canvas" width="0" height="0"></canvas>
</div>
</div>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment