本机环境为vs2017+opencv3.4.1。首先需要在vs中配置opencv,右击项目,点击属性,在VC++目录中的包含目录和库目录中添加如下信息:
包含目录中添加:(此处根据自己电脑中opencv的路径进行添加)
D:\opencv\build\include\opencv2
D:\opencv\build\include\opencv
D:\opencv\build\include
?
库目录中添加:(此处根据自己电脑中opencv的路径进行添加)
D:\opencv\build\x64\vc15\lib
?
在链接器的输入中添加:
opencv_world3410d.lib
进行图片的打开与显示,代码如下:
#include <opencv2/opencv.hpp>
#include <iostream>
using namespace std;
using namespace cv;
int main(int arge, char**argv)
{
Mat src, gray_src;
src = imread("1.jpg");
if (src.empty()) {
cout << "找不到加载图片" << endl;
return -1;
}
namedWindow("input", CV_WINDOW_AUTOSIZE);
imshow("input", src);
waitKey(0);
return 0;
}
得到图片:
?
获得单通道灰度图的反差图,代码如下:
#include <opencv2/opencv.hpp>
#include <iostream>
using namespace std;
using namespace cv;
int main(int arge, char**argv)
{
Mat src, gray_src;
src = imread("1.jpg");
if (src.empty()) {
cout << "找不到加载图片" << endl;
return -1;
}
namedWindow("input", CV_WINDOW_AUTOSIZE);
imshow("input", src);
cvtColor(src, gray_src, CV_BGR2GRAY);
namedWindow("output", CV_WINDOW_AUTOSIZE);
//imshow("output", gray_src); //得到灰度图像
int height = gray_src.rows;
int width = gray_src.cols;
//单通道
for (int row = 0; row < height; row++) {
for (int col = 0; col < width; col++) {
int gray = gray_src.at<uchar>(row, col); //获得灰度图像像素值
gray_src.at<uchar>(row, col) = 255 - gray; //灰度图像反差处理
}
}
imshow("output", gray_src);
waitKey(0);
return 0;
}
效果如下:
?
获得三通道图像的反差图:
#include <opencv2/opencv.hpp>
#include <iostream>
using namespace std;
using namespace cv;
int main(int arge, char**argv)
{
Mat src, gray_src;
src = imread("1.jpg");
if (src.empty()) {
cout << "找不到加载图片" << endl;
return -1;
}
namedWindow("input", CV_WINDOW_AUTOSIZE);
imshow("input", src);
cvtColor(src, gray_src, CV_BGR2GRAY);
namedWindow("output", CV_WINDOW_AUTOSIZE);
//imshow("output", gray_src); //得到灰度图像
int height = gray_src.rows;
int width = gray_src.cols;
//单通道
for (int row = 0; row < height; row++) {
for (int col = 0; col < width; col++) {
int gray = gray_src.at<uchar>(row, col); //获得灰度图像像素值
gray_src.at<uchar>(row, col) = 255 - gray; //灰度图像反差处理
}
}
Mat dst;
dst.create(src.size(), src.type());
height = src.rows;
width = src.cols;
int nc = src.channels();
for (int row = 0; row < height; row++) {
for (int col = 0; col < width; col++) {
if(nc==1){
int gray = gray_src.at<uchar>(row, col); //获得灰度图像像素值
gray_src.at<uchar>(row, col) = 255 - gray;
}
else if (nc == 3) { //彩色图像反差处理
int b = src.at<Vec3b>(row, col)[0];
int g = src.at<Vec3b>(row, col)[1];
int r = src.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;
//gray_src.at<uchar>(row, col) = min(r,min(b, g));
}
}
}
//bitwise_not(src, dst); //彩色图像反差处理(快捷操作)
imshow("output", dst);
waitKey(0);
return 0;
}
效果如下:
?
|