美文网首页
2. Mat对象创建与使用

2. Mat对象创建与使用

作者: 逍遥才子 | 来源:发表于2020-03-05 21:09 被阅读0次
#include <opencv.hpp>
#include <iostream>

using namespace cv;
using namespace std;

int main(int argc, char** argv) {
    Mat src = imread("D:/HUANGHAI_WORK/tools/opencv4/opencv/sources/samples/data/aloeL.jpg", IMREAD_COLOR);
    namedWindow("001-demo", WINDOW_NORMAL);
    imshow("001-demo", src);
    int width = src.cols;
    int height = src.rows;
    int dim = src.channels();
    int depth = src.depth();
    int type = src.type();
    if (type == CV_8UC3) {
        
    }
    printf("width:%d,height:%d,dim:%d,depth:%d,type:%d\n", width, height, dim, depth,type);
    //imwrite("F:/2.png", src);
    //create mat one
    Mat t1 = Mat(256, 256, CV_8UC3);
    t1 = Scalar(0,255,0);
    imshow("t1", t1);

    //create mat two
    Mat t2 = Mat(Size(256, 256), CV_8UC3);
    t2 = Scalar(255, 255, 0);
    imshow("t2", t2);

    //create mat three
    Mat t3 = Mat::zeros(Size(256, 256), CV_8SC3);
    imshow("t3", t3);

    Mat t4 = src;
    imshow("t4", t4);

    Mat t5 = src.clone();
    imshow("t5", t5);

    Mat t6 = Mat::zeros(src.size(), src.type());
    imshow("t6", t6);
//visit each pixel
    
    int ch = src.channels();
    for (int row = 0; row < height; row++) {
        for (int col = 0; col < width; col++) {
            if (ch==3)
            {
                Vec3b pixel = src.at<Vec3b>(row, col);
                int blue = pixel[0];
                int green = pixel[1];
                int red = pixel[2];
                src.at<Vec3b>(row, col)[0] = 255 - blue;
                src.at<Vec3b>(row, col)[1] = 255 - green;
                src.at<Vec3b>(row, col)[2] = 255 - red;
            }
            if (ch == 1)
            {
                int pv = src.at<uchar>(row, col);
                src.at<uchar>(row, col) = (255 - pv);
            }
        }
    }

    imshow("pixeldemo", src);



//基于指针遍历
    Mat result = Mat::zeros(src.size(), src.type());
    for (int row = 0; row < height; row++) {
        uchar* curr_row = src.ptr<uchar>(row);
        uchar* result_row = result.ptr<uchar>(row);
        for (int col = 0; col < width; col++) {
            if (dim == 3)
            {
                int blue = *curr_row++;
                int green = *curr_row++;
                int red = *curr_row++;

                *result_row ++ = blue;
                *result_row ++ = green;
                *result_row++ = red;

            }
            if (dim == 1)
            {
                int pv = *curr_row++;
                *result_row++ = pv;
            }
        }
    }
    waitKey(0);
    destroyAllWindows();
    return 0;
}
image.png

相关文章

网友评论

      本文标题:2. Mat对象创建与使用

      本文链接:https://www.haomeiwen.com/subject/ekphrhtx.html