Rohit Rohit - 2 months ago 9x
C++ Question

how to change the black pixels in the below image to red pixels using opencv libraries with c++


I want to change the black pixels in the image to red pixels, such that the ball should look white and red. I want to use OpenCV libraries and code it in C++. I have tried converting the image to RGB.


Common approach is to threshold the image, so in your case you would say that each pixel with an intensity less than some threshold will be considered as being black and then recolored to red. One way to find a good threshold (that divides the image's pixel into two classes ("more black" and "more white") is OTSU thresholding:

int main()
    cv::Mat input = cv::imread("../inputData/ball_thresholding.jpg");

    cv::Mat gray;

    cv::Mat mask;
    // compute inverse thresholding (dark areas become "active" pixel in the mask) with OTSU thresholding:
    double grayThres = cv::threshold(gray, mask, 0, 255, CV_THRESH_BINARY_INV | CV_THRESH_OTSU);

    // color all masked pixel red:
    input.setTo(cv::Scalar(0,0,255), mask);

    // compute median filter to remove the whitish black parts and darker white parts

    cv::imshow("input", input);
    return 0;

Giving this mask:

enter image description here

and this result:

enter image description here

For this image, the threshold that was computed by OTSU is 127, which means that each grayscale pixel intensity of 127 or less (or less than 127, I'm not sure) will be recolored to red.

If you want to keep the shading effect withing the black/red region, you can remove input.setTo(cv::Scalar(0,0,255), mask); lind and replace it by:

// keep the shading:
    for(int j=0; j<input.rows; ++j)
        for(int i=0; i<input.cols; ++i)
            if(<unsigned char>(j,i))
      <cv::Vec3b>(j,i)[2] = 255;

which will result int:

enter image description here