目录

---------

图像处理基础

RGB -> 灰度转换公式

c++
PlainText
int Intensity = R * 0.0299 + G * 0.587 + b * 0.144;
c++
PlainText
int Intensity = (R + G + B) / 3;

Mat 类

什么是 Mat 类

  1. 类:c++ 中的数据和方法的集合
  2. 可用于保存图像
  3. 可以与保存矩阵

创建 Mat 类

c++
PlainText
cv:Mat srcMat(3, 4, CV_8UC3, Scalar(0, 0, 255));

其中 cv: 表示 OpenCV 的命名空间,命名无冲突时可以省略,大项目一般为多人合作,许多常见变量命名会导致冲突;srcMat 表示 Mat 类的实例。

Mat 实例函数参数含义:

此代码也可以写成以下形式:

c++
PlainText
cv:Mat srcMat; // 创建 srcMat,但未在内存分配空间
srcMat.create(3, 4, CV_8UC3); // 定义该 Mat 为3行4列,CV_8UC3 型,实质为在内存中开辟相应空间。该操作未赋初始值

元素类型命名规则

命名规则:CV_(位数)+(数据类型)+(通道数)

例如:CV_8UC3,表示位数为 8 bite,类型为 unsigned int,通道(C: channel)数为 3

数据类型有:

其他元素类型:

其他命名方式

c++
PlainText
cv::Mat m1 = (cg::Mat_<double>(3, 4) << 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12);

更直观:

c++
PlainText
cv::Mat m1 = (cg::Mat_<double>(3, 4) << 1, 2, 3, 4,
										5, 6, 7, 8,
										9, 10, 11, 12
);

更具体:

c++
PlainText
int cols = 4;
int rows = 3;
int type = CV_325;
int dataArray[] = { 0, 1, 2, 3,
                  	4, 5, 6, 7,
                   	8, 9, 10, 11
                  };
cv::Mat mat(rows, cols, type, &dataArray)

Mat 类的复制

浅复制:dstMat 指向 srcMat 同样的内存区域。对 srcMat 做出的修改均反映在 dstMat

PlainText
cv:Mat srcMat(3, 4, CV_8UC3, Scalar(0, 0, 255));
cv:Mat dstMat(3, 4, CV_8UC3, Scalar(0, 0, 255));
dstMat = srcMat;

深复制:在内存中开辟新区域,将 srcMat 全部内容复制到该区域

PlainText
cv:Mat srcMat(3, 4, CV_8UC3, Scalar(0, 0, 255));
cv:Mat dstMat(3, 4, CV_8UC3, Scalar(0, 0, 255));
srcMat.copy(dstMat);

RGB 图像像素操作

c++
PlainText
#include<opencv2/opencv.hpp>
using namespace cv;
int main() {
    Mat srcMat = imread("D:\\conis.png");
    int height = srcMat.rows;
    int width = srcMat.cols;
    for(int j = 0; j < height; j++) {
        for(int i = 0; i < width; i++) {
            srcMat.at<Vec3b>(j, i)[0] /= 2;
            srcMat.at<Vec3b>(j, i)[1] /= 2;
            srcMat.at<Vec3b>(j, i)[2] /= 2;
        }
    }
    imshow("test", srcMat);
    waitKey(0);
    return 0;
}

灰度图像像素操作

c++
PlainText
#include<opencv2/opencv.hpp>
using namespace cv;
int main() {
  	Mat srcMat = imread("F:/1.png", 0); // 参数0,读取图像的同时转换为灰度图
  	int height = srcMat.rows;
  	int width = srcMat.cols;
  	for(int j = 0; j < height; j++) {
    	for(int i = 0; i < width; i++) {
      		srcMat.at<uchar>(j, i) = srcMat.at<uchar>(j, i) / 2;
    	}
  	}
  	imshow("test", srcMat);
  	waitKey(0);
  	return 0;
}

二值化处理

公式: