【问题标题】:How can I know the red, blue and red component value of a pixel in a color image using openCV?如何使用openCV知道彩色图像中像素的红色、蓝色和红色分量值?
【发布时间】:2020-05-02 15:19:01
【问题描述】:

彩色图像的像素值表示红、绿、蓝分量的总和 影响 。我想使用opencv提取每个组件的确切值,请建议!

【问题讨论】:

    标签: opencv


    【解决方案1】:

    都在OpenCV FAQ Wiki:

    Suppose, we have 8-bit 3-channel image I (IplImage* img):
    
    I(x,y)blue ~ ((uchar*)(img->imageData + img->widthStep*y))[x*3]
    I(x,y)green ~ ((uchar*)(img->imageData + img->widthStep*y))[x*3+1]
    I(x,y)red ~ ((uchar*)(img->imageData + img->widthStep*y))[x*3+2]
    

    如果您打算使用 OpenCV 进行任何认真的工作,您可能还想获得 O'Reilly 的 Learning OpenCV 的副本并阅读它 - 这将在上述非常基​​本的问题上节省大量时间。

    【讨论】:

    • 更新的书是OpenCV 2 cookbook。
    • @karlphilip:即使这本书似乎也有很多负面评论说它已经过时了——我想这在很大程度上取决于你是想使用旧的 C API 还是更新和更可变的 C++ API。
    • 因为 RGB 分量作为每个 8 位通道存储在像素内存中。我正在使用以下代码来获取单个组件 RGB 的值。请建议 IplImage*image = cvLoadImage("image.jpg") for (i = 0; i > 16);// 获取红色分量 int g = 0xff & (pixel >> 8); // 获取绿色组件 int b = 0xff & (pixel); // 获取蓝色分量;
    【解决方案2】:

    我建议学习opencv c++ api。像素由 uchar 的向量表示。 如果这是一个彩色图像,那么我们有 3 个像素一个 uchar。 Opencv 定义typedef Vec<uchar, 3> Vec3b; 然后:

    //load image
    cv::Mat img = cv::imread("myimage.png",1); // 1 means color image
    /* Here the cv::Mat can be seen as cv::Mat_<Vec3b>
     * Matrix of uchar with 3 channels for BGR (warning this is not RGB) 
     */
    // access to pixel value
    cv::Vec3b mypix = img.at<Vec3b>(i,j);
    uchar bluevalue = mypix.x;
    

    【讨论】:

    • 由于 RGB 分量以 8 位通道的形式存储在像素内存中 for eachfor (i = 0; i > 16);// 获取红色分量 g = 0xff & (pixel >> 8); // 获取绿色分量 b = 0xff & (pixel); // 获取蓝色组件
    • 我把代码写成:int main(int argc, char *argv[]) { IplImage *img = cvLoadImage("I.jpg"); int nl=img->高度; // 行数 int nc= img -> width * img -> nChannels; // 每行的元素总数 int step= img->widthStep; // 有效宽度 int channel = img -> nChannels; //加载图像 cv::Mat_ img1 = cv::imread("myimage.png",1); // 1 表示彩色图像 // 获取像素值 cv::Vec3b mypix = img1.at(5,5); uchar bluevalue = mypix.x;返回0; } 然后得到错误
    • error as-load_im.cpp: In function 'int main(int, char**)': error: 'Vec3b' was not declared in this scope 注意:建议的替代方案:/usr/include/ opencv/cxcore.hpp:248:23:注意:'cv::Vec3b' load_im.cpp:15:16:错误:模板参数 1 无效 load_im.cpp:15:23:错误:'= 之前的声明类型无效' token load_im.cpp:15:51: error: cannot convert 'cv::Mat' to 'int' in initialization load_im.cpp:18:25: error: request for member 'at' in 'img1', which is of非类类型“int”load_im.cpp:19:26:错误:“cv::Vec3b”没有名为“x”的成员
    • 请给出demo代码,从openCV中的彩色图像像素中分别提取R、G、B值
    【解决方案3】:

    此代码将打印像素 300、300 的红色和蓝色值:

    img1 = cv2.imread('Image.png', cv2.IMREAD_UNCHANGED)
    b,g,r = (img1[300, 300])
    print (r)
    print (b)
    

    【讨论】:

      猜你喜欢
      • 2022-12-19
      • 2016-09-22
      • 2017-08-19
      • 2011-10-28
      • 2014-02-23
      • 2016-11-15
      • 2022-12-06
      • 2019-02-07
      • 2017-11-28
      相关资源
      最近更新 更多