从输入图像中获取RGB像素,并在opencv中重建输出图像

时间:2011-07-29 04:41:08

标签: image opencv rgb

我想在opencv中加载图像并将图像分割成通道(RGB),我想增加任何一种颜色并获得相应的输出图像。是否有最简单的方法来解决这个问题?

4 个答案:

答案 0 :(得分:1)

要将任何标量添加到RGB图像,您可以使用cvAddS(srcImage,scalarToAdd,dstImage)。 这是一个例子:

int main(int argc, char** argv)

{
// Create a named window with the name of the file.
cvNamedWindow( argv[1], 1 );
// Load the image from the given file name.
IplImage* img = cvLoadImage( argv[1] );
//Make a scalar to add 30 to Blue Color and 20 to Red (BGR format)
CvScalar colorAdd = cvScalar(30.0, 0, 20.0);
cvAddS(img, colorAdd, img);
// Show the image in the named window
cvShowImage( argv[1], img );
// Idle until the user hits the “Esc” key.
while( 1 ) {
if( cvWaitKey( 100 ) == 27 ) break;
}
cvDestroyWindow( argv[1] );
cvReleaseImage( &img );
exit(0);
}

尚未测试代码,希望它有所帮助。

答案 1 :(得分:1)

@karlphillip:通常是RGB图像的更好解决方案 - 处理行尾的任何填充,也可以与OMP很好地并行化!

for (int i=0; i < height;i++) 
{
    unsigned char *pRow = pRGBImg->ptr(i);
    for (int j=0; j < width;j+=bpp) 
    // For educational puporses, here is how to print each R G B channel:
      std::cout << std::dec << "R:" << (int) pRow->imageData[j] <<  
                          " G:" << (int) pRow->imageData[j+1] <<  
                          " B:" << (int) pRow->imageData[j+2] << " "; 
    }
}

答案 2 :(得分:0)

使用OpenCV C ++接口,您只需使用重载算术运算符将Scalar添加到图像中。

int main(int argc, const char * argv[]) {
    cv::Mat image;
    // read an image
    if (argc < 2)
        return 2;

    image = cv::imread(argv[1]);

    if (!image.data) {
        std::cout << "Image file not found\n";
        return 1;
    }

    cv::Mat image2 = image.clone(); // Make a deep copy of the image
    image2 += cv::Scalar(30,0,20); // Add 30 to blue, 20 to red

    cv::namedWindow("original");
    cv::imshow("original", image);

    cv::namedWindow("addcolors");
    cv::imshow("addcolors", image2);

    cv::waitKey(0);
    return 0;
}

答案 3 :(得分:0)

另一种选择是手动迭代图像的像素,并在您感兴趣的频道上工作。这将使您可以灵活地单独或作为一个组操作每个通道。

以下代码使用OpenCV的C接口:

IplImage* pRGBImg = cvLoadImage("test.png", CV_LOAD_IMAGE_UNCHANGED); 
int width = pRGBImg->width; 
int height = pRGBImg->height;
int bpp = pRGBImg->nChannels; 
for (int i=0; i < width*height*bpp; i+=bpp) 
{
  // For educational puporses, here is how to print each R G B channel:
  std::cout << std::dec << "R:" << (int) pRGBImg->imageData[i] <<  
                          " G:" << (int) pRGBImg->imageData[i+1] <<  
                          " B:" << (int) pRGBImg->imageData[i+2] << " "; 
}

但是,如果您想为某个频道添加固定值,您可能需要查看@ Popovici的答案。