opencv的圖像處理通常會對像素進行處理,因此需要讀取像素,我通過實例-----使用uchar格式與float格式互相轉化來說明如何對圖像的像素進行處理。
在C++函數處理時,通常是使用指針來改變圖像值,因此,本例也是使用指針訪問像素。
下面爲灰度圖轉換,通過讀取每一行第一個像素的地址,來訪問每一個像素。注意圖像是什麼格式,像素首地址就是什麼格式,不同格式取地址會出錯。
void uchar2float(const Mat tyuchar, Mat &tyfloat)
{
for (int i = 0; i < tyuchar.rows; i++)
{
const uchar* ty1 = tyuchar.ptr<uchar>(i);
float* ty2 = tyfloat.ptr<float>(i);
for (int j = 0; j < tyuchar.cols; j++)
{
ty2[j] = ty1[j];
}
}
}
彩色圖像轉換,由於彩色圖像包含3個通道,因此需要乘上通道數來訪問到需要的處理的像素。
void uchar2float(const Mat tyuchar, Mat& tyfloat)
{
for (int i = 0; i < tyuchar.rows; i++)
{
const uchar* ty1 = tyuchar.ptr<uchar>(i);
float* ty2 = tyfloat.ptr<float>(i);
for (int j = 0; j < tyuchar.cols; j++)
{
//ty2[j] = ty1[j];
const uchar* dataWarpCol1 = ty1 + j * tyuchar.channels();
float* dataWarpCol2 = ty2 + j * tyfloat.channels();
dataWarpCol2[0] = dataWarpCol1[0];
dataWarpCol2[1] = dataWarpCol1[1];
dataWarpCol2[2] = dataWarpCol1[2];
}
}
}
同理,float 轉化爲 uchar
灰度圖像:
void float2uchar(const Mat tyfloat, Mat &tyuchar)
{
for (int i = 0; i < tyfloat.rows; i++)
{
const float* ty1 = tyfloat.ptr<float>(i);
uchar* ty2 = tyuchar.ptr<uchar>(i);
for (int j = 0; j < tyfloat.cols; j++)
{
if (ty1[j] < 0){ ty2[j] = 0; }
else if (ty1[j]>255){ ty2[j] = 255; }
else{ ty2[j] = ty1[j]; }
}
}
}
彩色圖像,應該有更好的寫法,希望有思路的方法可以指正我,謝謝!!!
void float2uchar(const Mat tyfloat, Mat& tyuchar)
{
for (int i = 0; i < tyfloat.rows; i++) {
const float* ty1 = tyfloat.ptr<float>(i);
uchar* ty2 = tyuchar.ptr<uchar>(i);
for (int j = 0; j < tyfloat.cols; j++) {
uchar* dataWarpCol2 = ty2 + j * tyuchar.channels();
const float* dataWarpCol1 = ty1 + j * tyfloat.channels();
if (dataWarpCol1[0] < 0) dataWarpCol2[0] = 0;
else if (dataWarpCol1[0] > 255) dataWarpCol2[0] = 255;
else dataWarpCol2[0] = dataWarpCol1[0];
if (dataWarpCol1[1] < 0) dataWarpCol2[1] = 0;
else if (dataWarpCol1[1] > 255) dataWarpCol2[1] = 255;
else dataWarpCol2[1] = dataWarpCol1[1];
if (dataWarpCol1[2] < 0) dataWarpCol2[2] = 0;
else if (dataWarpCol1[2] > 255) dataWarpCol2[2] = 255;
else dataWarpCol2[2] = dataWarpCol1[2];
}
}
}
參考文獻:https://www.cnblogs.com/adong7639/p/4600330.html
完!(笑)