改变图像部分的亮度和对比度

时间:2017-05-08 17:14:34

标签: c++ opencv

鉴于图像,我想改变图像部分的亮度/对比度。

我使用示例here来更改整个图像的亮度/对比度:

RNG rng(cv::getTickCount());
float min_alpha = 0.1;
float max_alpha = 2.0;
float alpha = rng.uniform(min_alpha, max_alpha);
float beta = -2.0;
image.convertTo(new_image, -1, alpha, beta);

有没有办法只在图像的子区域上执行此操作而无需在for循环中迭代整个图像?

2 个答案:

答案 0 :(得分:2)

您可以通过以下步骤以更简单/更有效的方式执行此操作:

步骤1:裁剪图像中要更改对比度的部分。

步骤2:对此裁剪图像应用适当的对比度/亮度变化。

步骤3:将已更改的图像粘贴回原始图像。

// Step 1
int rect_x = originalImg.cols / 5;
int rect_y = 0;
int rect_width = originalImg.cols / 6;
int rect_height = originalImg.rows;

cv::Rect ROI(rect_x, rect_y, rect_width, rect_height);
cv::Mat cropped_image = originalImg (ROI);

Mat image = imread( argv[1] );
Mat new_image = Mat::zeros( image.size(), image.type() );

// Step 2
std::cout<<" Basic Linear Transforms "<<std::endl;
std::cout<<"-------------------------"<<std::endl;
std::cout<<"* Enter the alpha value [1.0-3.0]: ";std::cin>>alpha;
std::cout<<"* Enter the beta value [0-100]: "; std::cin>>beta;

for( int y = 0; y < cropped_image.rows; y++ ) {
    for( int x = 0; x < cropped_image.cols; x++ ) {
        for( int c = 0; c < 3; c++ ) {
            enhanced_cropped_image.at<Vec3b>(y,x)[c] =
            saturate_cast<uchar>( alpha*( cropped_image.at<Vec3b>(y,x)[c] ) + beta );
        }
    }
}
// Or this for Step 2
float min_alpha = 0.1;
float max_alpha = 2.0;
float alpha = rng.uniform(min_alpha, max_alpha);
float beta = -2.0;
cropped_image.convertTo(enhanced_cropped_image, -1, alpha, beta);
// Step 3
enhanced_cropped_image.copyTo(originalImg(cv::Rect(rect_x, rect_y, rect_width, rect_height)));

希望它有所帮助!

答案 1 :(得分:1)

这是一种方法。

  1. 更改整个图像的亮度/对比度

  2. 指定要裁剪的cv :: Rect区域

  3. 将裁剪的部分复制到原始图像中的相同位置

  4. 这是我写的一个片段:

     Mat partial_illum_img;
     RNG rng(cv::getTickCount());
     float min_alpha = 0.1;
     float max_alpha = 2.0;
     float alpha = rng.uniform(min_alpha, max_alpha);
     float beta = -2.0;
     image.convertTo(illum_img, -1, alpha, beta);
     image.copyTo(partial_illum_img);
    
     // Crop a rectangle from converted image
     int rect_x = illum_img.cols / 5;
     int rect_y = 0;
     int rect_width = illum_img.cols / 6;
     int rect_height = illum_img.rows;
    
     cv::Rect illumROI(rect_x, rect_y, rect_width, rect_height);
     cv::Mat crop_after_illum = illum_img(illumROI);
     crop_after_illum.copyTo(partial_illum_img(cv::Rect(rect_x, rect_y, rect_width, rect_height)));