Skip to content

Instantly share code, notes, and snippets.

@pirosuke pirosuke/index.html
Created May 8, 2019

What would you like to do?
Image Convert With OpenCV.js
<title>OpenCV.js Test</title>
<img src="./lena.jpg" id="src-image" style="width: 400px;" />
<img id="hidden-image" src="./lena.jpg" style="display: none;" />
<canvas id="dest-canvas"></canvas>
<canvas id="hidden-canvas" style="display: none;"></canvas>
<input type="file" id="input-file" />
<input type="button" value="グレースケール化" id="gray-scale-btn" />
<input type="button" value="線画化" id="linedraw-btn" />
<a href="#" id="download-btn" download="converted.png">ダウンロード</a>
<script src="./opencv.js" type="text/javascript"></script>
<script src="./index.js" type="text/javascript"></script>
const srcImg = document.getElementById('src-image');
const hiddenImg = document.getElementById('hidden-image');
const fileInput = document.getElementById('input-file');
const canvas = document.getElementById('dest-canvas');
const hiddenCanvas = document.getElementById('hidden-canvas');
const grayScaleBtn = document.getElementById('gray-scale-btn');
const lineDrawBtn = document.getElementById('linedraw-btn');
const downloadBtn = document.getElementById('download-btn');
function convertImageToGray(img) {
let dst = new cv.Mat();
cv.cvtColor(img, dst, cv.COLOR_RGBA2GRAY, 0);
return dst;
function convertImageToLineDrawing(img) {
const kernel = cv.getStructuringElement(cv.MORPH_RECT,new cv.Size(5,5));
const imgGray = new cv.Mat();
cv.cvtColor(img, imgGray, cv.COLOR_RGBA2GRAY);
const imgDilated = new cv.Mat();
cv.dilate(imgGray, imgDilated, kernel, new cv.Point(-1, 1), 1);
const imgDiff = new cv.Mat();
cv.absdiff(imgDilated, imgGray, imgDiff);
const contour = new cv.Mat();
cv.bitwise_not(imgDiff, contour);
return contour;
function dataUriToBlob(dataUri) {
const b64 = atob(dataUri.split(',')[1]);
const u8 = Uint8Array.from(b64.split(''), e => e.charCodeAt());
return new Blob([u8], {type: 'image/png'});
fileInput.addEventListener('change', e => {
srcImg.src = URL.createObjectURL([0]);
hiddenImg.src = URL.createObjectURL([0]);
}, false);
grayScaleBtn.addEventListener('click', e => {
let src = cv.imread(srcImg);
const dst = convertImageToGray(src);
cv.imshow('dest-canvas', dst);
let hiddenSrc = cv.imread(hiddenImg);
const hiddenDst = convertImageToGray(hiddenSrc);
cv.imshow('hidden-canvas', hiddenDst);
lineDrawBtn.addEventListener('click', e => {
const src = cv.imread(srcImg);
const dst = convertImageToLineDrawing(src);
cv.imshow('dest-canvas', dst);
const hiddenSrc = cv.imread(hiddenImg);
const hiddenDst = convertImageToLineDrawing(hiddenSrc);
cv.imshow('hidden-canvas', hiddenDst);
downloadBtn.addEventListener('click', e => {
const data = hiddenCanvas.toDataURL();
const url = URL.createObjectURL(dataUriToBlob(data));
downloadBtn.href = url;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.