OpenCV学习5--图像操作

修改像素值
灰度图像
img.at< uchar>(y,x) = 128;

RGB三通道图像
img.at< Vec3b>(y,x)[0]=128;//blue
img.at< Vec3b>(y,x)[1]=128;//blue
img.at< Vec3b>(y,x)[2]=128;//blue

空白图像
img=Scalar(0);

ROI选择
Rect r(10,10,100,100);
Mat smalling=img(r);

Vec3b与Vec3F
Vec3b对应三通道的顺序是blue、green、red的uchar类型数据
Vec3f对应三通道的float类型数据
把CV_8UC1转换到CV32F1实现如下:
src.convertTo(dst,CV_32F);

实例程序:

#include
#include
#include
#include   

using namespace cv;
using namespace std;

int main()
{ 
    Mat img = imread("1.jpg");
    if(img.empty())
    {
        cout << "Image Load Failed"<< endl;
        //system("pause");
        return -1;
    }

    namedWindow("MyWindow2", CV_WINDOW_AUTOSIZE);
    imshow("MyWindow2", img);
    Mat gray_img;
    cvtColor(img,gray_img,CV_BGR2GRAY);
    int height = gray_img.rows;
    int width = gray_img.cols;

    namedWindow("output",WINDOW_AUTOSIZE);
    imshow("output",gray_img);

    //单通道的像素操作
    for(int row = 0;rowfor(int col = 0;colint gray = gray_img.at(row,col);
            gray_img.at(row,col) = 255 -gray;
        }
    }

    imshow("output2",gray_img);

    Mat dst;
    dst.create(img.size(),img.type());
    height = dst.rows;
    width = dst.cols;
    int cn = dst.channels();

    for(int row = 0;rowfor(int col = 0;col < width;col++){
            if(cn == 1)
            { 
            }
            else if(cn == 3){                          //彩色图像的反差处理
                int b = img.at(row,col)[0]; 
                int g = img.at(row,col)[1]; 
                int r = img.at(row,col)[2]; 
                dst.at(row,col)[0] = 255 -b;
                dst.at(row,col)[1] = 255 -g;
                dst.at(row,col)[2] = 255 -r;
            }
        }
    }

    imshow("output4",dst);
    Mat outimg;
    bitwise_not(img,outimg);
    imshow("output5",outimg);
    waitKey(0);

    return 0; 
}

效果:
OpenCV学习5--图像操作_第1张图片

源码和原图片请到Github下载:
https://github.com/MRwangmaomao/OpencvPixel-Project.git

你可能感兴趣的:(图像处理)