简体   繁体   中英

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::cvtColor(input,gray,CV_BGR2GRAY);

    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);
    cv::waitKey(0);
    return 0;
}

Giving this mask:

在此处输入图片说明

and this result:

在此处输入图片说明

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(mask.at<unsigned char>(j,i))
            {
                input.at<cv::Vec3b>(j,i)[2] = 255;
            }
        }

which will result int:

在此处输入图片说明

cv::Mat imBW = imread('bwImg.jpg',CV_LOAD_IMAGE_GRAYSCALE);
cv::Mat RGB_img = cv::Mat(imBW.rows, imBW.cols, CV_8UC3);
cv::Mat R_channel = 255-imBW;
cv::Mat B_channel = cv::Mat::zeros(imBW.rows, imBW.cols, CV_8UC1);
cv::Mat G_channel = cv::Mat::zeros(imBW.rows, imBW.cols, CV_8UC1);
vector<cv::Mat> channels;
channels.push_back(B_channel);
channels.push_back(G_channel);
channels.push_back(R_channel);
cv::merge(channels, RGB_img);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM