数字图像的二值化和反色图
环境:vs2019+OpenCV4.5.1
#include <opencv2/core/core.hpp>
#include<opencv2/highgui/highgui.hpp>
#include"opencv2/imgproc/imgproc.hpp"
#include <iostream>
#include <opencv2\imgproc\types_c.h>
#include <opencv2/highgui/highgui_c.h>
#include <math.h>
using namespace cv;
Mat SrcImage; //创建三个图像
Mat GrayImage;
//二值图
Mat BinaryImage;
//三通道图像的反色
Mat dst;
void on_trackbar(int pos, void*)
{
//转化为二值图
threshold(GrayImage, BinaryImage, pos, 255, CV_THRESH_BINARY);
namedWindow("二值图");
imshow("二值图", BinaryImage);
}
//灰度图反色(单色图像)
void on_gray_src()
{
int height = GrayImage.rows;
int width = GrayImage.cols;
for (int row = 0; row < height; row++)
{
for (int col = 0; col < width; col++)
{
int gray = GrayImage.at<uchar>(row, col);
GrayImage.at<uchar>(row, col) = 255 - gray;
}
}
imshow("反色", GrayImage);
}
//三通道反色
void on_dst()
{
dst.create(SrcImage.size(), SrcImage.type());
int height = SrcImage.rows;
int width = SrcImage.cols;
//获得通道数
int nc = SrcImage.channels();
//b,g,r 三通道
int b;
int g;
int r;
for (int row = 0; row < height; row++)
{
for (int col = 0; col < width; col++)
{
b = SrcImage.at<Vec3b>(row, col)[0];
g= SrcImage.at<Vec3b>(row, col)[1];
r = SrcImage.at<Vec3b>(row, col)[2];
//对每个通道都进行反转
dst.at<Vec3b>(row, col)[0] = 255 - b;
dst.at<Vec3b>(row, col)[1] = 255 - g;
dst.at<Vec3b>(row, col)[2] = 255 - r;
//只保留红色通道的值
/*
//这里是将b和g通道
dst.at<Vec3b>(row, col)[0] = 0;
dst.at<Vec3b>(row, col)[1] = 0;
dst.at<Vec3b>(row, col)[2] = r;
*/
}
}
imshow("三通道反色", dst);
}
void to_GrayImage()
{
//创建与原图同类型和同大小的矩阵
GrayImage.create(SrcImage.size(), SrcImage.type());
//将原图转换为灰度图像
cvtColor(SrcImage, GrayImage, CV_BGR2GRAY);
namedWindow("灰度图");
imshow("灰度图", GrayImage);
}
void creat_trackbar()
{
// 滑动条
int nThreshold = 0;
createTrackbar("二值图阈值", "二值图", &nThreshold, 254, on_trackbar);
}
int main()
{
SrcImage = imread("d:\\images\\im.jpg");
namedWindow("原图");
imshow("原图", SrcImage);
to_GrayImage();
on_trackbar(100, 0);
on_gray_src();
on_dst();
creat_trackbar();
waitKey();
}
注:若有疑问,下边的博客可能会有些帮助
OpenCV实现彩色图像转换为灰度图及二值化处理
OpenCV反色处理