包括基本的图像读取,深拷贝和浅拷贝,salt,使用指针遍历图像,颜色缩减,图像锐化
#include <iostream>
#include <opencv2\opencv.hpp>
#include <opencv2\highgui\highgui.hpp>
#define _CRT_SECURE_NO_DEPRECATE
void salt(cv::Mat &image, int n); //图像中随机元素设置为白色(255)
void colreduc( cv::Mat &image, int div = 64); //遍历图像颜色缩减
void Sharp(const cv::Mat &image, cv::Mat &result); //图像锐化
int main()
{
cv::Mat image2;
cv::Mat image = cv::imread("1.jpg");
std::cout << "size:" << image.size().height <<","<< image.size().width << std::endl;
image.copyTo(image2); //图像拷贝,深拷贝
double duration;
duration = static_cast<double>(cv::getTickCount()); //时钟初始个数
Sharp(image, image2);
//经历总的时钟个数
duration = static_cast<double>(cv::getTickCount()) - duration;
//时间等于时钟个数除以频率
duration /= cv::getTickFrequency();
std::cout << "Time:" << duration << std::endl;
cv::namedWindow("Orignial image");
cv::imshow("Orignial image",image);
cv::namedWindow("Salt image");
cv::imshow("Salt image", image2);
cv::waitKey(0);
return 0;
}
void salt(cv::Mat &image, int n)
{
for (int k = 0; k < n; k++)
{
int i = rand() % image.cols;
int j = rand() % image.rows;
if (image.channels() == 1)
{
image.at<uchar>(j, i) = 255;
}
else if (image.channels() == 3)
{
image.at<cv::Vec3b>(j, i)[0] = 255; //通道表示方法
image.at < cv::Vec3b>(j, i)[1] = 255;
image.at<cv::Vec3b>(j, i)[2] = 255;
}
}
}
//使用迭代器进行颜色缩减
void colreduc(cv::Mat &image,int div)
{
//result.create(image.rows, image.cols, image.type());
//初始位置的迭代器
cv::Mat_<cv::Vec3b>::iterator it = image.begin<cv::Vec3b>();
cv::Mat_<cv::Vec3b>::iterator itend = image.end<cv::Vec3b>();
for (; it != itend; ++it)
{
(*it)[0] = (*it)[0] / div * div + div / 2; //对元素进行操作
(*it)[1] = (*it)[1] / div * div + div / 2;
(*it)[2] = (*it)[2] / div * div + div / 2;
}
//指针遍历图像
/*int n = result.rows;
int nc = result.cols * result.channels();
uchar mask = 0xFF << 4;
for (int j = 0; j < n; j++)
{
const uchar* data_in = image.ptr<uchar>(j);
uchar* data_out = result.ptr<uchar>(j);
for (int i = 0; i < nc; i++)
{
data_out[i] = (data_in[i] & mask) + div / 2;
}
}*/
}
//图像锐化
void Sharp(const cv::Mat &image, cv::Mat &result)
{
result.create(image.size(), image.type());
for (int j = 1; j < image.rows - 1; j++)
{
const uchar* current = image.ptr<const uchar>(j);
const uchar* up = image.ptr<const uchar>(j - 1);
const uchar* down = image.ptr<const uchar>(j + 1);
uchar* output = result.ptr<uchar>(j);
for (int i = 1; i < image.cols - 1; i++)
{
*output++ = cv::saturate_cast<uchar>( 5 * current[i] - current[i + 1] - current[i - 1] - up[i] - down[i]);
}
}
result.row(0).setTo(cv::Scalar(0));
result.row(result.rows - 1).setTo(cv::Scalar(0));
result.col(0).setTo(cv::Scalar(0));
result.col(result.cols - 1).setTo(cv::Scalar(0));
}
注:
1.大多数的c++操作符都被重载了,所以可以写出例如:
result = 0.1 * image1 + 0.8 * image2