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;
}
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;
}
}
}
贴张原图: 效果图:
|