mat.at<uchar>(row, col)
mat.at<Vec3b>(row, col)
image.ptr<uchar>(row)
?图像像素的读写操作主要是像素遍历与访问
数组遍历
灰度图像
int pv = image.at<uchar>(row, col); //读取图片像素灰度值 image.at<uchar>(row, col) = 255 - pv;? ?//取反
彩色图像
Vec3b bgr = image.at<Vec3b>(row, col);? ?//三通道的 image.at<Vec3b>(row, col)[0] = 255 - bgr[0]; image.at<Vec3b>(row, col)[1] = 255 - bgr[1]; image.at<Vec3b>(row, col)[2] = 255 - bgr[2];
?
int w = image.cols; //列数
int h = image.rows;//行数
int dims = image.channels();//通道数
for (int row = 0; row < h; row++) {
for (int col = 0; col < w; col++) {
if (dims == 1) { // 灰度图像
int pv = image.at<uchar>(row, col);
image.at<uchar>(row, col) = 255 - pv;
}
if (dims == 3) { // 彩色图像
Vec3b bgr = image.at<Vec3b>(row, col);
image.at<Vec3b>(row, col)[0] = 255 - bgr[0];
image.at<Vec3b>(row, col)[1] = 255 - bgr[1];
image.at<Vec3b>(row, col)[2] = 255 - bgr[2];
}
}
}
?
指针遍历
for (int row = 0; row < h; row++) {
uchar* current_row = image.ptr<uchar>(row);
for (int col = 0; col < w; col++) {
if (dims == 1) { // 灰度图像
int pv = *current_row;
*current_row++ = 255 - pv; // 赋值之后,指针后移
}
if (dims == 3) { // 彩色图像
*current_row++ = 255 - *current_row;
*current_row++ = 255 - *current_row;
*current_row++ = 255 - *current_row;
}
}
}
结果一样
?
|