1. 程式人生 > >Opencv獲取並改變影象的畫素值

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;
}

上述的方法在效率方面不好,還有更快速的方法獲取畫素值:

  1. IplImage img;  
  2. for (i = 0;i < img->height;i++)  
  3. {  
  4.     for (j = 0;j < img->width;j++)  
  5.     {  
  6.         sum += ((uchar *)(img->imageData + img->widthStep * i))[j];//獲取畫素值
  7.         num++;  
  8.     }  
  9. }