如何删除背景图像与Opencv [英] How to remove background image with Opencv
问题描述
我是新的opencv。我写一个删除的背景。
我的输入图片>
i'm new opencv . i writing a remove the background .
my input image
我按照以下步骤对我的程序进行了编码:\\ b $ b - 计算平均像素数
i coded my program as follow steps :
- calculate average pixels
//define roi of image
cv::Rect roi(0, 0, 20 , 20 );
//copies input image in roi
cv::Mat image_roi = imgGray( roi );
//imshow("roi", image_roi);
//computes mean over roi
cv::Scalar avgPixelIntensity = cv::mean( image_roi );
//prints out only .val[0] since image was grayscale
cout << "Pixel intensity over ROI = " << avgPixelIntensity.val[0] << endl;
- 根据平均像素值创建新的Mat图像:
-create new Mat image base on average pixels values :
//create new mat image base on avgPixelIntensity
cv::Mat areaSampleArv(imgGray.rows, imgGray.cols,imgGray.type(),avgPixelIntensity.val[0]);
imshow("areaSampleArv", areaSampleArv);
- 转换图片:
-Invert image :
void image_invert(Mat& image){
int height, width, step, channels;
uchar *data;
height = image.cols;
width = image.rows;
step = (int)image.step;
channels = image.channels();
data = (uchar *)image.data;
for(int i = 0; i < height; i++){
for(int j = 0; j < width; j++){
for(int k = 0; k < channels; k++){
data[i*step + j*channels + k] = 255 - data[i*step + j*channels + k];
}
}
}
//imwrite("/Users/thuydungle/Desktop/1234/inverted.png", image);
imshow("inverted", image);}
我的图片反转结果:
- 添加原始图片的反转图片:
-Add inverted image with original image:
Mat dst;
dst = areaSampleArv + im0;
imshow("dst", dst);
任何我的图片结果:
似乎很糟糕,我可以使用阈值提取数字?
所以,你能告诉我如何解决它吗?
谢谢!
seem it is very bad and i can use thresholding for extraction numbers ?
so , can you tell me how to fix it ?
thank !
推荐答案
您可以尝试 cv:inRange
颜色阈值。
You could try cv:inRange()
for color based threshold.
cv::Mat image = cv::imread(argv[1]);
if (image.empty())
{
std::cout << "!!! Failed imread()" << std::endl;
return -1;
}
cv::Mat threshold_image;
// MIN B:77 G:0 R:30 MAX B:130 G:68 R:50
cv::inRange(image, cv::Scalar(77, 0, 30),
cv::Scalar(130, 68, 50),
threshold_image);
cv::bitwise_not(threshold_image, threshold_image);
cv::imwrite("so_inrange.png", threshold_image);
int erode_sz = 4;
cv::Mat element = cv::getStructuringElement(cv::MORPH_ELLIPSE,
cv::Size(2*erode_sz + 1, 2*erode_sz+1),
cv::Point(erode_sz, erode_sz) );
cv::erode(threshold_image, threshold_image, element);
cv::imwrite("so_erode.png", threshold_image);
cv::dilate(threshold_image, threshold_image, element);
cv::imwrite("so_dilate.png", threshold_image);
cv::imshow("Color Threshold", threshold_image);
cv::waitKey();
您还可以执行 cv :: blur(threshold_image,threshold_image,cv: :Size(3,3));
之后 cv :: bitwise_not()
以获得稍好的结果。
You could also execute cv::blur(threshold_image, threshold_image, cv::Size(3, 3));
after cv::bitwise_not()
to get a slightly better result.
有乐趣改变代码。
这篇关于如何删除背景图像与Opencv的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!