0

I'm trying grayscale contrast stretching with c++ program, so a source I follow for that is here. There is a code I've got so far:

#include<iostream>
#include<opencv2/opencv.hpp>
#include<opencv2/core/core.hpp>
#include<opencv2/highgui/highgui.hpp>
#include<opencv2/imgproc/imgproc.hpp>

using namespace cv;
using namespace std;

int computeStretched(int x, int l1, int l2, int r1, int r2);

int main() {
  Mat img = imread("pict6.jpg"); // Mat type initialization of an original image
  Mat grayScaleImg(img.size(), CV_8UC1);; // Gray scale mat initialization
  cvtColor(img, grayScaleImg, COLOR_BGR2GRAY); // conversion of image input to grayscaled view

  for (int i = 0; i < img.rows; i++) {
        for (int j = 0; j < img.cols; j++) {
            for (int k = 0; k < 3; k++) {
              int output = computeStretched(grayScaleImg.at<Vec3b>(i, j)[k], 70, 0, 200, 255);
              stretch_result.at<Vec3b>(i, j) = saturate_cast<uchar>(output);
            }
        }
  } 

waitKey(0);
return 0;
}

int computeStretched(int x, int l1, int l2, int r1, int r2) {
    float calcVal;

    if (0 <= x && x <= l1) {
       calcVal = (l2 / l1) * x;
    }else if (l1 < x && x <= r1) {
       calcVal = ((r2 - l2) / (r1 - l1)) * (x - l1) + l2;
    }else if (r1 < x && x <= 255) {
       calcVal  = ((255 - r2)/(255 - r1)) * (x - r1) + r2;
    }

    return (int)calcVal;
}

Hovewer, the image I put to processing isn't RGB-converted, but grayscale one. I want to do same operation as in the sample code using plainly grayscale picture too. What must be changed in the listing above to enable that?

Max_ReFactor
  • 67
  • 2
  • 7
  • [`cv::imread`](https://docs.opencv.org/4.1.0/d4/da8/group__imgcodecs.html#ga288b8b3da0892bd651fce07b3bbd3a56) has IMREAD_GRAYSCALE flag, use that and you won't have to differentiate between color and grayscale images – zteffi Nov 27 '19 at 13:57
  • GrayScaleImage.at(i,j) instead of .at(i,j) & remove that k loop ... read this section :https://docs.opencv.org/2.4/doc/user_guide/ug_mat.html – Ziri Nov 28 '19 at 05:15

1 Answers1

0

You have GrayScale image that means 1 channel.

so modify your code accordingly :

for (int i = 0; i < img.rows; i++) {
    for (int j = 0; j < img.cols; j++) {

          int output = computeStretched(grayScaleImg.at<uchar>(i, j), 70, 0, 200, 255);
          stretch_result.at<uchar>(i, j) = saturate_cast<uchar>(output);

    }

}

Initlize "stretch_result

Ziri
  • 718
  • 7
  • 16