OpenCV学习 day3 图像操作

1.像素的操作

 通过读取像素 反转像素值:

#include <opencv2/opencv.hpp>
#include <iostream>

using namespace cv;
using namespace std;

int main()
{
    Mat src = imread("D:/learning/image/3.jpg", IMREAD_UNCHANGED); 
    if (src.empty())
    {
        cout << "Could not find the image!" << endl;
        return -1;
    }
    namedWindow("InputImage"); 
    imshow("InputImage", src); 
    
    int height = src.rows;
    int width = src.cols;
                            
    Mat dst;
    dst.create(src.size(), src.type());
    for (int row = 0; row < height; row++) {
        for (int col = 0; col < width; col++) {
            if (dst.channels() == 1) {
                int gray_pixel = src.at<uchar>(row, col);  //获取单通道图像像素值
                dst.at<uchar>(row, col) = 255 - gray_pixel;
            }
            else if(dst.channels() == 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;
            }
        }
    }
    imshow("image invert", dst);
    waitKey(0);
    return 0;
}

或者直接bitwise_not()函数

bitwise_not(src, dst);

   

猜你喜欢

转载自www.cnblogs.com/happyfan/p/12047420.html