图像处理:dither

#include
#include

using namespace std;
using namespace cv;

int main() {
	Mat img_gray0 = imread("xjj.jpg", IMREAD_GRAYSCALE);
	int img_h, img_w;
	img_h = img_gray0.size().height;
	img_w = img_gray0.size().width;

	Mat img_dither = Mat::zeros(Size(img_w + 1, img_h + 1), CV_8U);
	Mat img_undither = Mat::zeros(Size(img_w, img_h), CV_8U);
	int threshold = 128;

	//@ 给img_dither赋值,对img_undither二值化
	for (int i = 0; i < img_h; i++)
	{
		for (int j = 0; j(i, j) << endl;
			img_dither.at(i, j) = img_gray0.at(i, j);
			if (img_gray0.at(i, j)>threshold)
			{
				img_undither.at(i, j) = 255;
			}
            //@ 这里还有一种二值化方式,采用随机阈值进行二值化,这种也很有意思,得到的二值图像有更多的细节
            if (img_gray0.at(i, j)>(rand() % 255))
			{
				img_undither.at(i, j) = 255;
			}
		}
	}

	for (int i = 0; i < img_h; i++)
	{
		for (int j = 0; j(i, j);
			if (img_dither.at(i, j)>threshold)
			{
				new_pix = 255;
			}
			else
			{
				new_pix = 0;
			}
			//先对img_dither二值化
			img_dither.at(i, j) = new_pix;
			int quant_err = old_pix - new_pix;
			if (j > 0)
			{
				img_dither.at(i + 1, j - 1) = img_dither.at(i + 1, j - 1) + quant_err * 3 / 16;
			}
			img_dither.at(i + 1, j) = img_dither.at(i + 1, j) + quant_err * 5 / 16;
			img_dither.at(i, j + 1) = img_dither.at(i, j + 1) + quant_err * 7 / 16;
			img_dither.at(i + 1, j + 1) = img_dither.at(i + 1, j + 1) + quant_err * 1 / 16;
		}
	}
	imshow("src", img_gray0);
	imshow("img_undither", img_undither);
	imshow("img_dither", img_dither);
	waitKey();
	return 0;
}

图像处理:dither_第1张图片

C++里面查看Mat数据没有python方便,可以把数据保存到文件查看,还挺方便的 

    std::string savedither = "./save_data.xml";
    cv::FileStorage fs(savedither, cv::FileStorage::WRITE);
    fs << "img_gray0" << img_gray0;
    fs << "img_undither" << img_undither;
    fs << "img_dither" << img_dither;
    fs.release();

参考: 

利用Floyd-Steinberg方法(dithering),将灰度图转换为二值图_whoispo的博客-CSDN博客

你可能感兴趣的:(C++,opencv,图像处理,c++,opencv)