2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

opencv.jsの作法 その9

Last updated at Posted at 2020-01-26

#概要

opencv.jsの作法を調べてみた。
輪郭を検出して、背景を消すをやって見た。

#写真

image.png

#サンプルコード

var cvs = document.getElementById('canvasInput');
var ctx= cvs.getContext('2d');
var img = new Image();
img.src = data;
img.onload = function() {
  ctx.drawImage(img, 0, 0);
	var src = cv.imread('canvasInput');
  var dstC1 = new cv.Mat(280, 500, cv.CV_8UC1);
	var dstC3 = cv.Mat.ones(280, 500, cv.CV_8UC3);
	var dstC4 = new cv.Mat(280, 500, cv.CV_8UC4);
	var mask = cv.Mat.ones(280, 500, cv.CV_8UC3);
	var dst = cv.Mat.ones(280, 500, cv.CV_8UC3);
	cv.cvtColor(src, dstC1, cv.COLOR_RGBA2GRAY, 0);
	cv.threshold(dstC1, dstC4, 205, 210, cv.THRESH_BINARY);
	let contours = new cv.MatVector();
	let hierarchy = new cv.Mat();
	cv.findContours(dstC4, contours, hierarchy, cv.RETR_LIST, cv.CHAIN_APPROX_SIMPLE, {
		x: 0,
		y: 0
	});
	for (let i = 0; i < contours.size(); i++)
	{
	  var cnt = contours.get(i);
		var area = cv.contourArea(cnt, false);
		let color = new cv.Scalar(255, 255, 255);
		if (area > 30000 && area < 50000) cv.drawContours(mask, contours, i, color, cv.FILLED);
	}
	contours.delete();
	hierarchy.delete();
	for (var i = 0; i < src.rows; i++)
	{
		for (var j = 0; j < src.cols; j++)
		{
			if (mask.ucharPtr(i, j)[0] == 255)
			{
				dst.ucharPtr(i, j)[0] = src.ucharPtr(i, j)[0];
				dst.ucharPtr(i, j)[1] = src.ucharPtr(i, j)[1];
				dst.ucharPtr(i, j)[2] = src.ucharPtr(i, j)[2];
			}
			else
			{
			  dst.ucharPtr(i, j)[0] = 255;
				dst.ucharPtr(i, j)[1] = 255;
				dst.ucharPtr(i, j)[2] = 255;
			}
		}
	}
	cv.imshow('canvasOutput', dst);
	src.delete();
}	
	
	
	

#成果物

以上。

2
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?