2
1

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/C++)

Last updated at Posted at 2016-11-29

参照: グレイコード(Wikipedia)

空間コード化法なんかでグレイコード画像を使いたいことが多々ある.ので,OpenCV/C++での実装例.
offsetを与えて中央に寄せているので,必要がなければoffsetを消す.

# include <vector>
# include <cmath>
# include <opencv2/opencv.hpp>

int main()
{
	const cv::Size im_size(1280, 800);

	std::vector<cv::Mat> im_vec;
	std::vector<int> graycode(im_size.width);

	const int bit_num = static_cast<int>(std::ceil(std::log2(im_size.width))) - 1;
	const int offset = static_cast<int>(std::pow(2, bit_num) - im_size.width) / 2;

	// generate gray code
	for (int px = 0; px < im_size.width; ++px)
	{
		// shift to center
		const int bit = px + offset;

		// gray code
		graycode[px] = bit ^ (bit >> 1);
	}

	// make images
	for (int i = 0; i < bit_num; ++i)
	{
		cv::Mat im = cv::Mat::zeros(im_size, CV_8U);

		for (int py = 0; py < im_size.height; ++py)
		{
			uchar* const im_ptr = im.ptr<uchar>(py);

			for (int px = 0; px < im_size.width; ++px)
			{
				// extract i-th bit
				const uchar val = ((graycode[px] >> (bit_num - i - 1)) & 0x01);
				im_ptr[px] = val * 255;
			}
		}
		im_vec.push_back(im.clone());
	}

	// show
	for (const auto& im : im_vec)
	{
		cv::imshow("im", im);
		cv::waitKey(-1);
	}
}
2
1
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
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?