
Opencv的图像处理通常处理像素,因此需要读取像素。我使用示例来说明如何通过在uchar格式和float格式之间进行转换来处理图像的像素。
在C ++函数处理中,指针通常用于更改图像值。因此,此示例还使用指针访问像素。

以下是灰度图像转换。通过读取每行中第一个像素的地址,可以访问每个像素。注意图像是什么格式,以及像素的第一个地址是什么格式。接收地址时,不同的格式会导致错误。
void uchar2float(const Mat tyuchar, Mat &tyfloat)
{
for (int i = 0; i < tyuchar.rows; i++)
{
const uchar* ty1 = tyuchar.ptr(i);
float* ty2 = tyfloat.ptr(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(i);
float* ty2 = tyfloat.ptr(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(i);
uchar* ty2 = tyuchar.ptr(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.pc-fly.com/a/shumachanpin/article-334437-1.html
马云忽悠了太做淘宝卖家亏得一踏糊涂