004图像操作

图像操作

  • 读写图像

  • 读写像素

  • 修改像素

 

01读写图像

  • imread可以加载灰度或RGB图像

  • imwirte保存图像文件

 

02读写像素

  • 读一个GRAY像素点的像素值(CV_8UC1)

    Scalar intensity = img.at<uchar>(y, x);

    或者 Scalar intensity = img.at<uchar>(Point(x, y));

  • 读一个RGB像素点的像素值

    Vec3f intensity = img.at<Vec3f>(y, x);

    float blue = intensity.val[0];

    float green = intensity.val[1];

    float red = intensity.val[2];

 

03修改像素值

  • 灰度图像

    img.at<uchar>(y, x) = 128;

  • RGB三通道图像

    img.at<Vec3b>(y,x)[0]=128; // blue

    img.at<Vec3b>(y,x)[1]=128; // green

    img.at<Vec3b>(y,x)[2]=128; // red

  • 空白图像赋值

    img = Scalar(0);

  • ROI选择

    Rect r(10, 10, 100, 100);

    Mat smallImg = img(r);

 

04Vec3bVec3F

  • Vec3b对应三通道的顺序是blue、green、red的uchar类型数据。

  • Vec3f对应三通道的float类型数据

  • 把CV_8UC1转换到CV32F1实现如下:

    src.convertTo(dst, CV_32F);

 

 1 #include<opencv2/core/core.hpp>
 2 #include<opencv2/opencv.hpp>
 3 #include<opencv2/imgcodecs.hpp>
 4 #include<opencv2/highgui/highgui.hpp>
 5 #include<iostream>
 6 
 7 using namespace cv;
 8 using namespace std;
 9 
10 int main(int argc, char** argv)
11 {
12     Mat src, gray_src;
13     src = imread("C:/Users/aber/Desktop/data/baboon.jpg");
14     if (!src.data)
15     {
16         cout << "could not load the image..." << endl;
17         return -1;
18     }
19 
20     
21     int height = src.rows;//高度
22     int width = src.cols;//宽度
23     int channels = src.channels();
24     cout << ("height=%d width=%d channels=%d", height, width, channels)<< endl;
25     for (int row = 0; row < height; row++)
26     {
27         for (int col = 0; col < width; col++)
28         {
29             if (channels == 3)
30             {
31                 src.at<Vec3b>(row, col)[0] = 128;//blue
32                 src.at<Vec3b>(row, col)[2] = 128;//red
33             }
34         }
35     }
36 
37     cvtColor(src, gray_src, COLOR_BGR2GRAY);
38     namedWindow("gray_src", 1);
39     imshow("gray_src", gray_src);
40     int height_gray = gray_src.rows;
41     int width_gray = gray_src.cols;
42     for (int row = 0; row < height_gray; row++)
43     {
44         for (int col = 0; col < width_gray; col++)
45         {
46             int gray = gray_src.at<uchar>(row, col);
47             gray_src.at<uchar>(row, col) = 255 - gray;
48             //std::cout << ("gray:%d", gray) << std::endl;
49         }
50     }
51 
52     imshow("gray invert", gray_src);
53     namedWindow("input", 1);
54     imshow("input", src);
55     waitKey(0);
56     return 0;
57 }

 

 

 

 

 

posted @ 2021-06-03 20:05  阿尔飞  阅读(61)  评论(0)    收藏  举报