我正在尝试将背景颜色从白色更改为黑色。因此,我尝试遍历所有像素,并检查是否将其更改为0,是否为白色。但是出了点问题。

这是我的代码

Mat img = imread("t.PNG");
for (int x = 0; x < img.rows; x++)
{
    for (int y = 0; y < img.cols; y++)
    {
        if (img.at<Vec3b>(Point(x, y))[0] >=245 && img.at<Vec3b>(Point(x, y))[1] >= 245 && img.at<Vec3b>(Point(x, y))[2] >= 245)
        {

            img.at<Vec3b>(Point(x, y)) = { 0,0,0 };
        }
    }
}
imwrite("img.png",img);
imshow(" ",img);
waitKey(0);

这是我要转换的图像

opencv - 将背景颜色从白色更改为黑色时出错-LMLPHP

最佳答案

如果要逐像素迭代,请更改循环:

for (int row = 0; row < img.rows; row++)
{
    for (int col = 0; col < img.cols; col++)
    {
        if (img.at<cv::Vec3b>(cv::Point(col, row))[0] >=245 && img.at<cv::Vec3b>(cv::Point(col, row))[1] >= 245 && img.at<cv::Vec3b>(cv::Point(col, row))[2] >= 245)
        {
            img.at<cv::Vec3b>(cv::Point(col, row)) = { 0,0,0 };
        }
    }
}

更好,更清晰的解决方案是使用背景遮罩。为此更改循环:
cv::Mat gray,mask;
cv::cvtColor(img,gray,CV_BGR2GRAY);
cv::compare(gray, cv::Scalar(245,245,245), mask, CV_CMP_GT);
img.setTo(cv::Scalar(0,0,0), mask);

关于opencv - 将背景颜色从白色更改为黑色时出错,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/49250543/

10-11 22:30
查看更多