1、Mat像素的读取:
指针读取像素运行效率高。如果Mat是CV_32F,也只需要将里面的uchar改成float就行了。
//设置灰度图像素
for(int i = 0; i < grayFrame.rows; ++i)
{
uchar *p = grayFrame.ptr<uchar>(i);
for(int j = 0; j < grayFrame.cols; ++j)
{
p[j] = 255;//白色
}
}
//设置彩色图像素
for(int i = 0; i < colorFrame.rows; ++i)
{
Vec3b *p3 = colorFrame.ptr<Vec3b>(i);
for(int j = 0; j < colorFrame.cols; ++j)
{
p3[j][0] = 255;//蓝色
p3[j][1] = 0;
p3[j][2] = 0;
}
}
2、逐像素比较两幅图像,将不同之处设为红色
#include<opencv2/core/core.hpp>
#include<opencv2/highgui/highgui.hpp>
#include<iostream>
#include <stdlib.h> // c function abs
using namespace std;
using namespace cv;
Point2i compete_pixe1(Mat& src1, Mat& src2, int i, int j) {
Vec3b *pixel1 = src1.ptr<Vec3b>(i);
Vec3b *pixel2 = src2.ptr<Vec3b>(i);
int threshold = 60;
Point2i p = Point2i(-1, -1);
if (abs(int(pixel1[j][0]) - int(pixel2[j][0])) > threshold && abs(int(pixel1[j][1]) - int(pixel2[j][1])) > threshold && abs(int(pixel1[j][2]) - int(pixel2[j][2])) > threshold)
{
p.x = i;
p.y = j;
}
return p;
}
int main() {
Mat Image1 = imread("1.jpg");
Mat Image2 = imread("0.jpg");
Mat show_Image = Image1.clone();
int rowNumber = show_Image.rows;
int colNumber = show_Image.cols;
Point2d diff_p;
double time0 = static_cast<double>(getTickCount());
//逐像素进行比较(RGB)
for (int i = 0; i < rowNumber; ++i) {
for (int j = 0; j < colNumber; ++j) {
diff_p = compete_pixe1(Image1, Image2, i, j);
if (diff_p.x != -1 && diff_p.y != -1) {
show_Image.ptr<uchar>(i, j)[0] = 0;
show_Image.ptr<uchar>(i, j)[1] = 0;
show_Image.ptr<uchar>(i, j)[2] = 255;
}
}
}
time0 = ((double)getTickCount() - time0) / getTickFrequency();
cout << "运行时间为:" << time0 << "秒" << endl;
imshow("效果图", show_Image);
waitKey(0);
return 0;
}