Day 5 - Opencv 访问图像像素值
1. 访问图像像素值
#include <opencv2/core.hpp>
#include <opencv2/highgui.hpp>
#include <random>
#include <iostream>
//加入椒盐噪声的函数
void addSalt(cv::Mat image, int n);
int main(int argc, char** argv)
{
cv::Mat image = cv::imread("376001.jpg");
if (image.empty())
{
std::cout << "\n Durn, couldn't read image filename " << std::endl;
return 1;
}
addSalt(image, 100);
cv::namedWindow("saltedImage");
cv::imshow("saletedImage", image);
cv::waitKey(0);
return 0;
}
//image: 输入图像
//n : 改变的像素数
void addSalt(cv::Mat image, int n)
{
//随机数生成器
std::default_random_engine generator;
std::uniform_int_distribution<int> randomRow(0, image.rows - 1); //在区间内按照均匀分布随机生成数字序列
std::uniform_int_distribution<int> randomCol(0, image.cols - 1);
int i = 0;
int j = 0;
for (int k = 0; k < n; k++){
i = randomRow(generator); //在区间内随机生成数字
j = randomCol(generator);
if (image.type() == CV_8UC1)
{
image.at<uchar>(i, j) = 255;
}
else if (image.type() == CV_8UC3)
{
image.at<cv::Vec3b>(i, j)[0] = 255;
image.at<cv::Vec3b>(i, j)[1] = 255;
image.at<cv::Vec3b>(i, j)[2] = 255;
}
}
}
- std::default_random_engine generator:默认构造函数,使用默认种子来设置初始状态
祥解 http://c.biancheng.net/view/638.html - std::uniform_int_distribution://均匀分布:第一个参数是下边界,第二个参数是上边界
详解:http://c.biancheng.net/view/639.html
贴张原图:
效果图: