//直方图均衡化void MainWindow::histEqualize(Mat& img, Mat& res){if(img.channels()==1){
int gray[256]={0};
double gray_prob[256]={0};
double sum_prob[256]={0};
int height = img.rows;
int width = img.cols;
int gray_sum =0;// 统计每个像素下的灰度个数for(int i =0; i < img.rows; i++){//定义行指针
uchar *ptr =(uchar*)img.data + i * img.cols;for(int j =0; j < img.cols; j++){
int value = ptr[j];
gray[value]++;
gray_sum++;}}//统计灰度频率for(int i =0; i <256; i++){
gray_prob[i]=((double)gray[i]/ gray_sum);}//计算累积概率
double sum =0;for(int i =0; i <256; i++){
sum += gray_prob[i];
sum_prob[i]= sum;}
res = Mat::zeros(img.rows, img.cols,CV_8UC1);//计算对应的新的灰度值
int val =0;for(int i =0; i < height; i++){//定义行指针
uchar *imgPtr =(uchar*)img.data + i * img.cols;
uchar *resPtr =(uchar*)res.data + i * res.cols;for(int j =0; j < width; j++){
val = imgPtr[j];
resPtr[j]=round(sum_prob[val]*255);}}}}
水平镜像
void MainWindow::mirrorLr(Mat& img, Mat & res){
res = Mat::zeros(img.rows, img.cols,CV_8UC1);
int width = img.cols;
int height = img.rows;for(int i =0; i < height; i ++){//定义行指针
uchar *imgPtr =(uchar*)img.data + i * img.cols;
uchar *resPtr =(uchar*)res.data + i * res.cols;for(int j =0; j < width; j ++){
resPtr[width - j -1]= imgPtr[j];}}}
图像旋转(双线性插值)
//图像旋转void MainWindow::rotateImg(Mat& img, Mat &res, double angle){
double theta = angle * pi /180;
double a =cos(theta);
double b =sin(theta);
int height = img.rows;
int width = img.cols;
int newHeight =ceil(width * b + a * height);
int newWidth =ceil(width * a + b * height);
res = Mat::zeros(newHeight, newWidth,CV_8UC1);
double temp1, temp2;//计算矩阵中的两个常数,这样不用以后每次都计算了
temp1 =-0.5* newWidth * a -0.5* newHeight * b +0.5* width;
temp2 =0.5* newWidth * b -0.5* newHeight * a +0.5* height;
float x, y;for(int y0 =0; y0 < newHeight; y0++){//定义行指针
uchar *ptr =(uchar*)res.data + y0 * res.cols;for(int x0 =0; x0 < newWidth; x0++){
x = x0 * a + y0 * b + temp1;
y =-x0 * b + y0 * a + temp2;if(x >=0&& x < width -1&& y >=0&& y < height -1){//双线性插值
int left =floor(x);
int right =ceil(x);
int top =floor(y);
int bottom =ceil(y);
float m = x - left;
float n = y - top;
ptr[x0]=(1- m)*(1- n)* img.at<uchar>(top, left)+
m*(1- n)*img.at<uchar>(top, right)+(1- m)*n* img.at<uchar>(bottom, left)+
m*n*img.at<uchar>(bottom, right);if(ptr[x0]>255){
ptr[x0]=255;}}else{//
ptr[x0]=255;}}}}