#include <iostream> #include "opencv2/opencv.hpp" using namespace std; void colorReduce(cv::Mat &image,int div=64) { int rows =image.rows; int n = image.cols*image.channels(); cout<<"rows"<<rows<<"channels:"<<n<<endl; for(int i=0;i<rows;i++) { uchar* data=image.ptr<uchar>(i); for(int j=0;j<n;j++) { data[j]=data[j]/div*div+div/2; } } } void colorReduce(cv::Mat &imageIn,cv::Mat &imageOut,int div=64) { imageOut.create(imageIn.rows,imageIn.cols,imageIn.type()); if(imageOut.channels() ==3) { cv::MatIterator_<cv::Vec3b> itbegin=imageOut.begin<cv::Vec3b>(); cv::MatIterator_<cv::Vec3b> itend=imageOut.end<cv::Vec3b>(); for( ;itbegin != itend;++itbegin) { (*itbegin)[0] =(*itbegin)[0]/div*div+div/2; (*itbegin)[1] =(*itbegin)[1]/div*div+div/2; (*itbegin)[2] =(*itbegin)[2]/div*div+div/2; } } } int main() { cv::Mat matImage =cv::imread("E:/QtMaterial/images/boldt.jpg",1);//0: load pic in gray cv::Mat matBackImage =matImage.clone(); colorReduce(matBackImage,64); cv::imshow("Process1",matBackImage); cv::imshow("Image",matImage); colorReduce(matImage,matImage,64); cv::imshow("Process2",matImage); cv::waitKey(); return 0; }
at的使用例程
#include <iostream> #include "opencv2/opencv.hpp" #include "math.h" using namespace std; /* add salt *@image: source image *@n: the number of salt */ 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<char>(j,i)=255; } 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; } } } int main() { cv::Mat image =cv::imread("E:/QtMaterial/images/boldt.jpg");//OR ("E:\QtMaterial\images\boldt.jpg"); salt(image,30000);//200*292=60000 cv::namedWindow("Image with salt"); cv::imshow("Image with salt",image); cv::waitKey(); return 0; }