如何使用带有c ++的opencv库将下面图像中的黑色像素更改为红色像素

Roh*_*hit 0 c++ opencv image-processing

球

我想将图像中的黑色像素更改为红色像素,以使球看起来应该是白色和红色。我想使用OpenCV库并用C ++编写代码。我尝试将图像转换为RGB。

Mic*_*cka 6

常见的方法是对图像进行阈值处理,因此在您的情况下,您会说强度小于某个阈值的每个像素将被视为黑色,然后重新着色为红色。找到良好阈值(将图像像素分为两类(“更多黑色”和“更多白色”)的一种方法是OTSU阈值处理:

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;
}
Run Code Online (Sandbox Code Playgroud)

给这个面具:

在此处输入图片说明

结果:

在此处输入图片说明

对于此图像,由OTSU计算的阈值为127,这意味着每个等于或小于127(或小于127,我不确定)的灰度像素强度将重新着色为红色。

如果要使阴影效果与黑色/红色区域保持一致,则可以删除input.setTo(cv::Scalar(0,0,255), mask);lind并将其替换为:

// 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;
            }
        }
Run Code Online (Sandbox Code Playgroud)

这将导致int:

在此处输入图片说明