5
6

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 5 years have passed since last update.

Java OpenCVのkmeansを使って減色

Last updated at Posted at 2016-04-05

#Java OpenCvのkmeansを使って減色
画像処理で減色しようと思い、k-means法を利用したときハマったのでメモ。
参考:減色処理:Core.kmeans

##目的
参考サイト見ながら減色処理しようとしたけど、期待する画像が出力されない・・・。
下サイトでやってるような処理結果が欲しい!
k-meansクラスタリングによる画像分割,減色

##方法・コード
BGR画像をk-meansで減色して、出力されるようコードを編集しました。

cluster
	public static Mat cluster(Mat cutout, int k) {
		Mat samples = cutout.reshape(1, cutout.cols() * cutout.rows());
		Mat samples32f = new Mat();
		samples.convertTo(samples32f, CvType.CV_32F, 1.0 / 255.0);

		Mat labels = new Mat();
		TermCriteria criteria = new TermCriteria(TermCriteria.COUNT, 100, 1);
		Mat centers = new Mat();
		Core.kmeans(samples32f, k, labels, criteria, 1, Core.KMEANS_PP_CENTERS, centers);		
		
		centers.convertTo(centers, CvType.CV_8UC1, 255.0);
		centers.reshape(3);
		
		Mat dst = cutout.clone();
		int rows = 0;
		for(int y = 0; y < cutout.rows(); y++) {
			for(int x = 0; x < cutout.cols(); x++) {
				int label = (int)labels.get(rows, 0)[0];
				int r = (int)centers.get(label, 2)[0];
				int g = (int)centers.get(label, 1)[0];
				int b = (int)centers.get(label, 0)[0];
				dst.put(y, x, b,g,r);
				rows++;
			}
		}
		return dst;
	}

##結果
sample.jpg

いいね!

以上!

5
6
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
5
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?