Change the brightness and contrast of a part of the image

Given the image, I would like to change the brightness / contrast on a part of the image.

I use the example here to change the brightness / contrast of the whole image:

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);

Is there a way to do this only on the image sub-region without having to repeat the entire image in a for loop?

+4
source share
2 answers

You can do this in a simpler and more efficient way with the following steps:

Step 1: Crop the part of the image where you want to change the contrast.

Step 2: Apply the appropriate contrast / brightness changes to this cropped image.

Step 3: Paste the modified image back into the original image.

// 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

.

  • /

  • cv:: Rect,

, :

 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)));
+1

Source: https://habr.com/ru/post/1676674/


All Articles