首页 > 解决方案 > OpenCV:输出图像为蓝色

问题描述

所以我正在制作这个项目,我在 OpenCV 上制作图像的反射(不使用翻转功能),唯一的问题(我认为)要完成它,是应该反映出来的图像, 出来时都是蓝色的。

我拥有的代码(我取出了通常的部分,问题应该在这里):

Mat imageReflectionFinal = Mat::zeros(Size(220,220),CV_8UC3);

for(unsigned int r=0; r<221; r++)
    for(unsigned int c=0; c<221; c++) {
       Vec3b intensity = image.at<Vec3b>(r,c);
       imageReflectionFinal.at<Vec3b>(r,c) = (uchar)(c, -r + (220)/2);
    }

    ///displays images
    imshow( "Original Image", image );
    imshow("Reflected Image", imageReflectionFinal);
    waitKey(0);
    return 0;
}

标签: c++imageopencvopencv3.0

解决方案


您的代码存在一些问题。正如所指出的,您的迭代变量超出了实际的图像尺寸。不要使用硬编码边界,​​您可以使用inputImage.colsandinputImage.rows来获取图像尺寸。

有一个已设置但未使用的变量(BGR Vec3b) -Vec3b intensity = image.at<Vec3b>(r,c);

最重要的是,目前尚不清楚您要达到的目标。该行(uchar)(c, -r + (220)/2);没有提供太多信息。另外,您将原始图像翻转到哪个方向?X轴还是Y轴?

这是在 X 方向翻转图像的可能解决方案:

//get input image:
cv::Mat testMat = cv::imread( "lena.png" );

//Get the input image size:
int matCols = testMat.cols;
int matRows = testMat.rows;

//prepare the output image:
cv::Mat imageReflectionFinal = cv::Mat::zeros( testMat.size(), testMat.type() );

//the image will be flipped around the x axis, so the "target"
//row will start at the last row of the input image:
int targetRow = matRows-1;

//loop thru the original image, getting the current pixel value:
for( int r = 0; r < matRows; r++ ){
    for( int c = 0; c < matCols; c++ ) {
        //get the source pixel:
        cv::Vec3b sourcePixel = testMat.at<cv::Vec3b>( r , c );
        //source and target columns are the same:
        int targetCol = c;
        //set the target pixel
        imageReflectionFinal.at<cv::Vec3b>( targetRow , targetCol ) = sourcePixel;
    }
    //for every iterated source row, decrease the number of
    //target rows, as we are flipping the pixels in the x dimension:
    targetRow--;
}

结果:

在此处输入图像描述


推荐阅读