簡體   English   中英

如何使用CvMat檢索像素值

[英]How can retrieve pixel value using CvMat

img->data.ptr[i,j]=img1.data.ptr[(m_c*w_in)+n_c];

我試過了,但這只顯示了我一個價值。 任何幫助,我們將不勝感激。

首先,您為什么要使用舊界面。 如果您有新的opencv,則將CvMat轉換為cv :: Mat,然后執行操作。 完成后,您可以將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 %d\n", col);
        return 0;
    }

    if (luma) 
        *luma = 0.2126 * red + 0.7152 * green + 0.0722 * blue;

    printf("\n\nb=%x g=%x, r=%x color=%x\n", blue, green, red, color);
    printf("cols=%d, step=%d, col=%d, x=%d, y=%d loc=%d\n", 
           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還支持double,float,string和integer類型。 因此,您可以根據自己的確信來存儲數據。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM