图像取反

图像取反:反转图像的像素强度,使图像中的前景变为背景,背景变为前景。
显然这是一个一对一的映射,即像素值0变为255,1变为254…254变为1,255变为0。对应的查找表为lookup[256]={255,254,…,1,0}。

代码如下:

#include <iostream>
#include "opencv2/core/core.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/highgui/highgui.hpp"

using namespace std;
using namespace cv;

void Invert(Mat &img, const uchar* const lookup)
{
    int rows=img.rows;
    int cols=img.cols*img.channels();
    for(int i=0; i<rows; i++)
    {
        uchar *p=img.ptr<uchar>(i);    //定义指针p  指向第i行的头
        for(int j=0; j<cols;j++)  
            p[j]=lookup[p[j]];         //j在移动  把p【j】赋值 
    }
}

int main()
{
    Mat src=imread("C://1.bmp");  
    if(!src.data)
    {
        cout<<"error! The image is not built!"<<endl;
        return -1;
    }
    // 为了演示效果,将图片转换成灰度图片
    Mat img1=src;
    //cvtColor( src, img1, CV_RGB2GRAY );
    imshow("First",img1);
    //建立查找表
    uchar lookup[256];
    for(int i=0; i<256; i++)
        lookup[i]=255-i; //定义映射表中的值   反转图像
    //调用自定义图像取反函数
    Invert(img1, lookup);
    imshow("Second",img1);
    waitKey();
    return 0;
}

图像取反