#include <opencv.hpp>
#include<iostream>
#include <string>
#include<conio.h>
#include<time.h>
#include<math.h>
using namespace cv;
using namespace std;
//测试时间
void PrintMs(const char* text = " ")
{
static long long last = 0;
long long cur = getTickCount();
if (last == 0)
{
last = cur;
return;
}
long long ms = 0;
ms = ((double)(cur - last) / getTickFrequency()) * 1000;
if (*text != 0)
{
printf("%s = %dms\n", text, ms);
}
last = getCPUTickCount();
}
int main()
{
Mat m,m2;
//创建指定大小的数组,数据类型为TYPE,
m.create(100, 100, CV_8UC3);
//构造指定数组,数据类型为TYPE,值全为0的数组
m2 = Mat::zeros(1000, 1000, CV_8UC3);
Point point(300, 300);
circle(m2, point, 100, Scalar(0, 127, 127), 1, 8, 0);
namedWindow("circle", 1);
imshow("circle", m2);
RNG rng;
//多通道数组访问,通过模板函数at<>访问
for (int i = 0; i < m2.rows; i++)
{
for (int j = 0; j < m2.cols; j++)
{
m2.at<Vec3b>(j, i)[0] = rng.uniform(0, 255);
m2.at<Vec3b>(j, i)[1] = rng.uniform(0, 255);
m2.at<Vec3b>(j, i)[2] = rng.uniform(0, 255);
}
}
imshow("at<> mat", m2);
PrintMs("at>mat");
//直接地址访问连续空间
for (int i = 0; i < m2.rows*m2.elemSize(); i++)
{
m2.data[i] = 0; //B
m2.data[i + 1] = 127; //G
m2.data[i + 2] = 0; //R
}
imshow("lianxu di zhi kong jian", m2);
PrintMs("直接地址访问连续空间");
//直接地址访问不连续空间
for (int i = 0; i < m2.rows; i++)
{
for (int j = 0; j < m2.cols; j++)
{
(&m2.data[i*m2.step])[j*3] = 255; //B
(&m2.data[i * m2.step])[j * 3+1] = 255; //G
(&m2.data[i * m2.step])[j * 3+2] = 1; //R
}
}
imshow("bu lianxu kong jian", m2);
PrintMs("直接地址访问不连续空间");
//通过ptr接口遍历Mat(模板函数)
//性能基本等同有地址访问
//mat.ptr<Vec3b>(row) 返回的指针
//mat.ptr<Vec3b>(row,col);
for (int i = 0; i < m2.rows; i++)
{
for (int j = 0; j < m2.cols; j++)
{
Vec3b *c= m2.ptr<Vec3b>(i, j);
c->val[0] = 255;
c->val[1] = 0;
c->val[2] = 0;
}
}
imshow("ptr *", m2);
PrintMs("通过ptr接口遍历Mat(模板函数):");
//try 捕获异常
try{
//使用at引用遍历
for (int i = 0; i < m2.rows; i++)
{
for (int j = 0; j < m2.cols; j++)
{
Vec3b& c = m2.at<Vec3b>(i, j);
c[0] = 100;
c[1] = 100;
c[2] = 100;
}
}
}
catch (Exception &ex)
{
cout << ex.what() << endl;//抛出一场
}
imshow("use at<> reference", m2);
PrintMs("使用at引用遍历:");
//使用迭代器遍历Mat
//可以不用管Mat的行列
auto it = m2.begin<Vec3b>();
auto it_end = m2.end<Vec3b>();
for (; it!=it_end; it++)
{
(*it).val[0] = 0;
(*it).val[1] = 0;
(*it).val[2] = 255;
}
imshow("use *it", m2);
PrintMs("使用迭代器遍历Mat:");
waitKey(0);
return 0;
}
opencv遍历图像方法集合
最新推荐文章于 2023-04-26 20:45:00 发布