//2014年4月18日15:43:42
//opencv中Mat類型資料的索引與修改,和多通道Mat資料的資料提取
#include <iostream>
#include "highgui.h"
#include "cxcore.h"
using namespace std;
using namespace cv;
//提取三通道的inputMat某個通道資料,填入outputMat中
//outputMat的資料類型必須是CV_8UC1
void extractMatChannelDate(const Mat *inputMat, int channelNum, Mat *outputMat);
int main(void)
{
Mat srcImg = imread("red.jpg");
imshow("original image", srcImg);
Mat temp = cvCreateMat(srcImg.rows, srcImg.cols, CV_8UC1);
//Mat temp;//會報錯,調用函數extractMatChannelDate()需要提前開辟好記憶體空間
extractMatChannelDate(&srcImg, 2, &temp);
#if 0
//彩色的Mat中,三個通道的顔色順序是BGR,下面的程式是特定位置的特定通道的像素值修改
//Mat.at()函數是個模闆重載函數,需要指定調用的格式,這裡參數類型Vec3b,是一個存放 3 個 uchar 資料的 Vec(向量),
//後面的[0][1][2]是其索引,代表索引不同的通道數值
for (int row=0;row<srcImg.rows; row++)
{
for (int col=0; col<srcImg.cols; col++)
{
srcImg.at<Vec3b>(row, col)[0] = 0;//blue
srcImg.at<Vec3b>(row, col)[1] = 255;//green
srcImg.at<Vec3b>(row, col)[2] = 255;//red
}
}
#endif
imshow("changed image", temp);
cvWaitKey(0);
return 0;
}
void extractMatChannelDate(const Mat *inputMat, int channelNum, Mat *outputMat)
{
for (int row=0;row<inputMat->rows; row++)
{
for (int col=0; col<inputMat->cols; col++)
{
outputMat->at<uchar>(row, col) = inputMat->at<Vec3b>(row, col)[channelNum-1];
}
}
return;
}