[英]how to change the black pixels in the below image to red pixels using opencv libraries with c++
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: 找到良好阈值(将图像像素分为两类(“更多黑色”和“更多白色”)的一种方法是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;
}
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. 对于此图像,由OTSU计算的阈值为127,这意味着每个等于或小于127(或小于127,我不确定)的灰度像素强度将重新着色为红色。
If you want to keep the shading effect withing the black/red region, you can remove input.setTo(cv::Scalar(0,0,255), mask);
如果要在黑色/红色区域内保持阴影效果,则可以删除input.setTo(cv::Scalar(0,0,255), mask);
lind and replace it by: 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;
}
}
which will result int: 这将导致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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.