Opencv獲取並改變影象的畫素值
#include <iostream>
using namespace std;
#include "cv.h"
#include "highgui.h"
#pragma comment(lib,"cxcore.lib")
#pragma comment(lib,"cv.lib")
#pragma comment(lib,"ml.lib")
#pragma comment(lib,"cvaux.lib")
#pragma comment(lib,"highgui.lib")
#pragma comment(lib,"cvcam.lib")
int main(int argc, char* argv[])
{
IplImage *img = cvLoadImage("101.jpg",1);
CvScalar s;
cvNamedWindow("Image",1);
cvShowImage("Image",img);
for(int i = 0;i < img->height;i++)
{
for(int j = 0;j < img->width;j++)
{
s = cvGet2D(img,i,j); // get the (i,j) pixel value
s.val[0]=255;
s.val[1]=34;
s.val[2]=123;
cvSet2D(img,i,j,s);//set the (i,j) pixel value
}
}
cvShowImage("Image",img);
cvWaitKey(0); //等待按鍵
cvDestroyWindow( "Image" );//銷燬視窗
//cvReleaseImage( &img ); //釋放影象
return 0;
}
上述的方法在效率方面不好,還有更快速的方法獲取畫素值:
- IplImage img;
- for (i = 0;i < img->height;i++)
- {
- for (j = 0;j < img->width;j++)
- {
- sum += ((uchar *)(img->imageData + img->widthStep * i))[j];//獲取畫素值
- num++;
- }
- }