目前只会两种操作像素点的方法,不过感觉只要能操作就行了。
环境:Ununtu14.04 Clion OpenCV3.2
1.指针
使用Mat类中获取指针的函数,获得图像中某行的指针,进而找到列的地址,即可操作对应地址的像素点,如下代码所示
uchar *row_ptr = image1.ptr < uchar > (y);
uchar *data_ptr = &row_ptr[x * image1.channels()];
row_ptr获取了第y行图像的起始地址,接着data_ptr获取第x列的地址,如果是单通道图像,使用*data_ptr = ...;即可对该点像素进行赋值。
2.直接使用at()方法。
若图像为单通道图像,直接使用image.at<uchar>(y, x) = ...;即可对第y行,x列的对应点进行操作。
3.实践
#include <iostream>
#include <chrono>
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
using namespace std;
int main() {
cv::Mat image;
// IMREAD_UNCHANGED = -1
// IMREAD_GRAYSCALE = 0
image = cv::imread("../test.jpg", -1);
// 判断图像文件是否正确读取
if (image.data == nullptr) //数据不存在,可能是文件不存在
{
cout << "文件不存在." << endl;
return 0;
}
// 文件顺利读取, 首先输出一些基本信息
cout << "图像宽为" << image.cols << ",高为" << image.rows << ",通道数为"
<< image.channels() << endl;
// 用cv::imshow显示图像
cv::imshow("test", image);
// 暂停程序,等待一个按键输入
cv::waitKey(0);
// 遍历图像, 注意以下遍历方式亦可使用于随机像素访问
// 使用 std::chrono 来给算法计时
chrono::steady_clock::time_point t1 = chrono::steady_clock::now();
for (size_t y = 0; y < image.rows; y++) {
for (size_t x = 0; x < image.cols; x++) {
uchar *row_ptr = image.ptr < uchar > (y);
uchar *data_ptr = &row_ptr[x * image.channels()];
for (int c = 0; c != image.channels(); c++) {
uchar data = data_ptr[c];
}
}
}
chrono::steady_clock::time_point t2 = chrono::steady_clock::now();
chrono::duration<double> time_used = chrono::duration_cast<chrono::duration<double>>(t2 - t1);
cout << "遍历图像用时:" << time_used.count() << " 秒。" << endl;
// 使用clone函数来拷贝数据
cv::Mat image1 = image.clone();
cv::Mat image2 = image.clone();
for (size_t y = image1.rows / 2 - 5; y <= image1.rows / 2 + 5; y++) {
for (size_t x = 0; x < image1.cols; x++) {
uchar *row_ptr = image1.ptr < uchar > (y);
uchar *data_ptr = &row_ptr[x * image1.channels()];
if (image1.channels() == 1)
*data_ptr = 240;
if (image1.channels() == 3) {
data_ptr[0] = 0;
data_ptr[1] = 160;
data_ptr[2] = 0;
}
}
}
for (size_t y = image2.rows / 2 - 5; y <= image2.rows / 2 + 5; y++) {
for (size_t x = 0; x < image2.cols; x++) {
if (image2.channels() == 1)
image2.at<uchar>(y, x) = 180;
if (image2.channels() == 3) {
cv::Vec3b pixel;
pixel[0] = 0;
pixel[1] = 160;
pixel[2] = 0;
image2.at<cv::Vec3b>(y, x) = pixel;
}
}
}
cv::imshow("image1", image1);
cv::imshow("image2", image2);
cv::waitKey(0);
// 关于 cv::Mat 的拷贝
// 直接赋值并不会拷贝数据
cv::Mat image_another = image;
// 修改 image_another 会导致 image 发生变化
// 将左上角50*50的块置零
image_another(cv::Rect(0, 0, 50, 50)).setTo(0);
cv::imshow("image_another", image);
cv::waitKey(0);
// 使用clone函数来拷贝数据
cv::Mat image_clone = image.clone();
image_clone(cv::Rect(0, 0, 50, 50)).setTo(255);
cv::imshow("image_clone", image_clone);
cv::waitKey(0);
return 0;
}
最终效果为