15
16

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.

OpenCVで黒ピクセルを透過にする

Last updated at Posted at 2015-10-21

OpenCV 2.4.11で実装しています。
黒(0, 0, 0)のピクセルを透過にするには次のコードで実現可能です。
3チャネルのcv::Matを4チャネルに拡張し、4チャネル目(アルファチャネル)に0を書き込むことで透過にしています。
R, G, Bがそれぞれ0の時が黒であるので、R+G+B=0の時にアルファチャネルを0にしています。
なお、imshowでは透過部分の表示には対応していないため、透過であることを確認するために画像で書き出しています。

#include <cv.h>
#include <highgui.h>

int main(int argc, char** argv)
{
	cv::Mat source = cv::imread("image.png");
	cv::Mat alpha_image = cv::Mat(source.size(), CV_8UC3);
	cv::cvtColor(source, alpha_image, CV_RGB2RGBA);
	cv::imshow("original", source);
	cv::imshow("image", alpha_image);
	for (int y = 0; y < alpha_image.rows; ++y) {
		for (int x = 0; x < alpha_image.cols; ++x) {
			cv::Vec4b px = alpha_image.at<cv::Vec4b>(x, y);
			if (px[0] + px[1] + px[2] == 0) {
				px[3] = 0;
				alpha_image.at<cv::Vec4b>(x, y) = px;
			}
		}
	}
	cv::imwrite("new.png", alpha_image);
	cv::waitKey(0);
}
15
16
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
15
16

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?