答案 0 :(得分:5)
常见的方法是对图像进行阈值处理,因此在您的情况下,您会说强度小于某个阈值的每个像素都会被视为黑色,然后重新着色为红色。找到一个好的阈值(将图像的像素分为两类(“更黑”和“更白”)的一种方法是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;
}
给这个面具:
,结果如下:
对于此图像,由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;
}
}
将导致int:
答案 1 :(得分:1)
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);