#include "opencv2/opencv.hpp"
#include "opencv2/video/background_segm.hpp"
using namespace cv;
using namespace std;
int main()
{
VideoCapture capture;
capture.open(0);
int frameNum = 1;
Mat frame, mask, thresholdImage, output;
if (!capture.isOpened())
cout << "fail to open!" << endl;
capture >> frame;
Ptr<BackgroundSubtractorMOG2> bgsubtractor = createBackgroundSubtractorMOG2();
bgsubtractor->setVarThreshold(20);
while (true) {
capture >> frame;
++frameNum;
// 视频遮挡
//cv::Mat logo = cv::imread("mark.bmp");
Mat logo(400, 300, CV_8UC3, Scalar(0, 0, 255));
cv::Mat imageROI;
int x = (frame.cols - logo.cols)/2;
int y = frame.rows - logo.rows;
imageROI = frame(cv::Rect(x, y, logo.cols, logo.rows));
logo.copyTo(imageROI);
cv::namedWindow("result");
cv::imshow("result", frame);
// 背景建模法提取前景mask
//bgSubtractor(frame, mask, 0.001);
bgsubtractor->apply(frame, mask, -1);
// 计算黑白二值前景的非黑像素占比
int nTotalPixel = 0;
int nWhitePixel = 0;
Mat_<uchar>::iterator it = mask.begin<uchar>();
Mat_<uchar>::iterator itend = mask.end<uchar>();
for (; it != itend; ++it)
{
nTotalPixel++;
if ((*it)>0) nWhitePixel += 1;//二值化后,像素点是0或者255
}
float fPercent = (nWhitePixel / (float)nTotalPixel) * 100;
// 在图片中显示结果
char text[64] = { 0 };
sprintf(text, "%d/%d=%.4f", nWhitePixel, nTotalPixel, fPercent);
cv::putText(mask, text, cv::Point(50, 60), cv::FONT_HERSHEY_SIMPLEX, 1, cv::Scalar(255, 23, 0), 2, 4);
imshow("mask", mask);
waitKey(10);
}
return 0;
}
opencv图像遮掩及移动区域像素占比
最新推荐文章于 2024-06-11 11:17:21 发布