OpenCV中映像色素的讀取與修改

來源:互聯網
上載者:User

在影像處理中我們常常需要對映像的色素值進行處理,這就要求我們知道如何擷取映像的色素值和如何去修改它。

在對色素值的擷取時我們需要知道所要處理映像的類型和通道數,接下來我對常見的單通道(灰階級)和三通道(彩色級)映像做一個簡單的說明。

對於灰階級映像來說擷取映像在(x,y)點的色素值可以使用下面的方法:
Mat img=imread("H:\\VS2010Ultimtrial\\file\\testOpenCV\\test.jpg");
Scalar idensity=img.at<uchar>(50,50);

但是如何去讀取映像的值呢?

在灰階級映像中,可以直接使用idensity.val[0]來得到色素值。

當然也可以用同樣的方式改變單通道映像的色素值,如下所示:
idensity.val[0]=value;

對於三通道(彩色級)映像來說,從imread我們知道,返回的色素值是按BGR的順序返回的,所以我們可以使用下面的程式來獲得映像的色素值:

Vec3b idensity=img.at<Vec3b>(100,50);
 uchar blue=idensity.val[0];
 uchar green=idensity.val[1];
 uchar red=idensity.val[2];

當然我們也可以使用下面的方式來獲得浮點型映像的色素值:

Vec3f idensity=img.at<Vec3f>(100,50);
float blue=idensity.val[0];
float green=idensity.val[1];
float red=idensity.val[2];

對於三通道映像的色素值的修改我們可以使用下面的方式來進行,

   idensity=cvGet2D(scr,i,j);
   idensity.val[0]+=50;
   idensity.val[1]+=50;
   idensity.val[2]+=50;
   cvSet2D(scr,i,j,idensity);

在上面的程式中,我們使用了兩個函數cvGet2D()和cvSet2D(),這兩個函數的原型聲明如下:

cvGet2D(const CvArr *arr,int index0,int index1);

cvSet2D(const CvArr *arr,int index0,int index1,CvScalar value);

 

參考程式如下所示:

IplImage *scr;
 scr=cvLoadImage("H:\\VS2010Ultimtrial\\file\\testOpenCV\\test.jpg",1);
 Scalar idensity;
 cvNamedWindow("美女",CV_WINDOW_AUTOSIZE);
 cvShowImage("test.jpg",scr);
 for(int i=0;i<scr->height;i++)
 {
  for(int j=0;j<scr->width;j++)
  {
   idensity=cvGet2D(scr,i,j);
   cout<<"before modified..."<<endl;
   cout<<idensity.val[0]<<" "<<idensity.val[1]<<" "<<idensity.val[2]<<endl;
   idensity.val[0]+=50;//修改色素值
   idensity.val[1]+=50;
   idensity.val[2]+=50;
   cvSet2D(scr,i,j,idensity);
   cout<<"after modified..."<<endl;
   cout<<idensity.val[0]<<" "<<idensity.val[1]<<" "<<idensity.val[2]<<endl;
  }
  cout<<endl;
 }
 cvShowImage("test1.jpg",scr);
 cvWaitKey();

 cvReleaseImage(&scr);

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.