Mat对象
测试代码
图像操作
测试代码
图像混合
测试代码
调整图像亮度和对比度
测试代码
绘制形状和文字
#include "pch.h"
#include<opencv2/opencv.hpp>
#include<iostream>
using namespace std;
using namespace cv;
Mat src, dst;
void MyLine();
void MyRectangle();
void MyEllipse();
void MyCircle();
void Randline();
int main(int argc, char** argv)
{
src = imread("3.jpg", 1);
if (src.empty())
{
cout << "could not load the picture..." << endl;
return -1;
}
cout << "src's channel is :" << src.channels() << endl;
namedWindow("src", WINDOW_AUTOSIZE);
src.at<Vec3b>(0, 0)[0] = 255;
src.at<Vec3b>(0, 0)[1] = 255;
src.at<Vec3b>(0, 0)[2] = 255;
int height = src.rows;
int width = src.cols;
for(int row=0;row<height;row++)
for (int col = 0; col < width; col++)
{
int b = src.at<Vec3b>(row, col)[0];
int g = src.at<Vec3b>(row, col)[1];
int r = src.at<Vec3b>(row, col)[2];
src.at<Vec3b>(row, col)[0] = 255 - b;
src.at<Vec3b>(row, col)[1] = 255 - g;
src.at<Vec3b>(row, col)[2] = 255 - r;
}
MyLine();
MyRectangle();
MyEllipse();
MyCircle();
Randline();
putText(src, "hello,world", Point(50, 50), CV_FONT_HERSHEY_PLAIN, 2.0, Scalar(255, 255, 0), 2, 8, false);
imshow("src", src);
Mat kernel = (Mat_<char>(3, 3) << 0, -1, 0, -1, 5, -1, 0, -1, 0);
cvtColor(src, src, COLOR_BGR2GRAY);
filter2D(src, dst, src.depth(), kernel);
namedWindow("dst", WINDOW_AUTOSIZE);
dst.at<uchar>(0, 0) = 255;
imshow("dst1", dst);
for(int row = 0;row<height;row++)
for (int col = 0; col < width; col++)
{
int k = dst.at<uchar>(row, col);
dst.at<uchar>(row, col) = 255 - k;
}
imshow("dst", dst);
//channels() 函数要带()才能正确运行
cout << "dst's channel is :" << dst.channels() << endl;
cout << "dst's cols is :" << dst.cols << endl;
cout << "dst's rows is :" << dst.rows << endl;
const uchar* firstRow = dst.ptr<uchar>(0);
//要用*转译,才能正确输出,不然会导致乱码
cout << "dst's firstRow is :" << *firstRow << endl;
Mat m1 = Mat::zeros(2, 2, CV_8UC1);
cout << "m1 :" << m1 << endl;
Rect r(10, 10, 50, 50);
Mat src1 = src(r);
imshow("src1", src1);
waitKey(0);
return 0;
}
void MyLine()
{
Point p1 = Point(20, 20);
Point p2;
p2.x = 120;
p2.y = 120;
Scalar color = Scalar(0, 255, 0);
line(src, p1, p2, color, 2, 8, 0);
}
void MyRectangle()
{
Rect rect = Rect(20, 20, 120, 120);
Scalar color = Scalar(255, 0, 0);
rectangle(src, rect, color, 1, 8, 0);
}
void MyEllipse()
{
Scalar color = Scalar(0, 0, 255);
ellipse(src, Point(80, 200), Size(30, 60), 90,0,360,color,1,8,0);
}
void MyCircle()
{
Scalar color = Scalar(0, 255, 255);
Point center = Point(src.cols / 2, src.rows / 2);
circle(src, center, 20, color, 2, 8, 0);
}
void Randline()
{
RNG rng(12345);
Point p1;
Point p2;
for (int i = 0; i < 30; i++)
{
Scalar color = Scalar(rng.uniform(0, 255), rng.uniform(0, 255), rng.uniform(0, 255));
p1.x = rng.uniform(0, src.cols);
p2.x = rng.uniform(0, src.cols);
p1.y = rng.uniform(0, src.rows);
p2.y = rng.uniform(0, src.rows);
line(src, p1, p2, color, 2, 8, 0);
imshow("src2", src);
waitKey(100);
}
}