Pixel access in OpenCV 2.2

前端 未结 3 1465
不思量自难忘°
不思量自难忘° 2020-11-28 14:54

Hi I want to use opencv to tell me the pixel values of a blank and white image so the output would look like this

10001
00040
11110   
00100
相关标签:
3条回答
  • 2020-11-28 15:38

    In opencv 2.2, I'd use the C++ interface.

    cv::Mat in = /* your image goes here, 
                    assuming single-channel image with 8bits per pixel */
    for(int row = 0; row < in.rows; ++row) {
        unsigned char* inp  = in.ptr<unsigned char>(row);
        for (int col = 0; col < in.cols; ++col) {
            if (*inp++ == 0) {
                std::cout << '1';
            } else {
                std::cout << '0';
            }
            std::cout << std::endl;
        }
    }
    
    0 讨论(0)
  • 2020-11-28 15:47

    IplImage is the old format for images. You should use the new format, CvMat, which can store arbitrary matrices. An image is just a matrix, after all.

    You can then access the pixels using the function cvGet2D, which returns a CvScalar.

    0 讨论(0)
  • 2020-11-28 16:00

    IplImage struct have a variable char* imageData - it's just a buffer of all pixels. To read it properly you have to know your image format. For example for RGB888 image 3 first chars in imageData array will represent the r,g,b values of the first pixel at the first row. If you know the image format - you can read the data properly. Image format can be restored reading another values of IplImage structure:

    http://opencv.willowgarage.com/documentation/basic_structures.html

    Also i think it's more efficient to write the loop like this:

    uchar r,g,b;
    
    for (int y = 0; y < cvFrame->height; y++)
    {
        uchar *ptr = (uchar*) (cvFrame_->imageData + y*cvFrame_->widthStep);
        for (int x = 0; x < cvFrame_->width; x++)
        {       
            r = ptr[3*x];
            g = ptr[3*x + 1];
            b = ptr[3*x + 2];
        }
    }
    

    This code is for RGB888 image

    0 讨论(0)
提交回复
热议问题