如何使用 CvMat 检索像素值

How can retrieve pixel value using CvMat

本文关键字:像素 检索 CvMat 何使用      更新时间:2023-10-16
img->data.ptr[i,j]=img1.data.ptr[(m_c*w_in)+n_c];

我试过这个,但它只显示一个值。任何帮助都可以不胜感激。

首先,为什么要使用旧界面。如果您有新的opencv,则将CvMat转换为cv::Mat,然后执行操作。完成后,您可以将垫子转换回CvMat。

首先,切换到cv::Mat然后,您可以通过多种方式访问像素 x,y:

cv::Mat img;
int x,y;
//[...] Initialize here x and y
cv::Point p(x,y);
int stride = img.step1();
//All of these are valid ways to access pixel x,y
img.at<uint8_t>(y,x); //Or, for example, cv::Vec3b in place of uint8_t in case of color images
img.at<uint8_t>(p);
//The following are valid only for grayscale 8-bit images, otherwise they have to be modified a bit
img.ptr(y)[x];
img.ptr()[y * stride + x]; 

事实上,一旦你切换到cv::Mat,你可以在这里找到其他广泛的答案 OpenCV从Mat图像和这里获取像素通道值 在openCV中访问某些像素RGB值

这是一个古老的问题,仅适用于任何没有使用较新的cv:mat格式并且必须使用cvmat访问像素的人。使用 OpenCV 1.1 进行测试。

static unsigned long get_color(IplImage *img, CvPoint* pt, double *luma) {
    uchar blue, green, red;
    unsigned long color = 0;
    CvMat hdr; 
    CvMat *mat = cvGetMat(img, &hdr);
    int col = mat->step / mat->cols;
    uchar *pix = mat->data.ptr + (pt->y * mat->step + pt->x * col);
    if (col == 1) {
        // Grayscale
        color = *pix;
        blue = color * 11 / 100;
        green = color * 59 / 100;
        red = color * 30 / 100;
    } else if (col == 3) {
        // 3 channel RGB
        blue = *pix;
        green = *(pix + 1);
        red = *(pix + 2); 
        color = red << 16 | green << 8 | blue;
    } else {
        printf("Unsupported number of channel %dn", col);
        return 0;
    }
    if (luma) 
        *luma = 0.2126 * red + 0.7152 * green + 0.0722 * blue;
    printf("nnb=%x g=%x, r=%x color=%xn", blue, green, red, color);
    printf("cols=%d, step=%d, col=%d, x=%d, y=%d loc=%dn", 
           mat->cols, mat->step, col, pt->x, pt->y,
           (pt->y * mat->step + pt->x * col));
    return color;
}

输出:

1. Output from a grayscaled 600x600 Red.jpeg file
// Pixel (0,0)
b=8 g=2c, r=16 color=4c
cols=600, step=600, col=1, x=0, y=0 loc=0
// Pixel (1,0)
b=8 g=2c, r=16 color=4c
cols=600, step=600, col=1, x=1, y=0 loc=1
// Pixel (1,1)
b=8 g=2c, r=16 color=4c
cols=600, step=600, col=1, x=1, y=1 loc=601

2. Output from a 3 channel rgb 600x600 Red.jpeg file
// Pixel (0,0)
b=0 g=0, r=fe color=fe0000
cols=600, step=1800, col=3, x=0, y=0 loc=0
// Pixel (1,0)
b=0 g=0, r=fe color=fe0000
cols=600, step=1800, col=3, x=1, y=0 loc=3
// Pixel (1,1)
cols=600, step=1800, col=3, x=1, y=1 loc=1803
b=0 g=0, r=fe color=fe0000

要使用CvMat访问数据,您必须使用"img->data.ptr[x*col+y]",它可以用来存储uchar的数据。CvMat 还支持双精度、浮点型、字符串和整数类型。因此,您可以根据自己的说服力存储数据。