7.19的练习题3已经完成了,不过好像有几个bug,一是这个程序要按一下键盘上的一才能正常拍摄,不然有掉帧的感觉,二是程序显示的时间中小时这一项差了十个小时,可能是美国的时间,不想改了,将就用,然后在键盘上点1是提高分辨率,2是减少分辨率,由于是一开始最大分辨率显示,所以要按2才会有效果,马赛克直接用小矩形做,像素转灰度通道太麻烦。话不多说,上代码。
#include <iostream>
#include <opencv2/opencv.hpp>
#include <ctime>
#include <string>
using namespace std;
using namespace cv;
void draw_rect(Mat& image, int x, int y, int step, int flag);
void masaike(Mat& image);
void show_time(Mat &image);
int t = 0;
int main()
{
VideoCapture capture(0);
Mat image;
while (true)
{
if ((640 + 100 * t <= 640) && (480 + 100 * t <= 480) && (640 + 100 * t > 0) && (480 + 100 * t > 0))
{
capture.set(CAP_PROP_FRAME_WIDTH, 640 + 100 * t);
capture.set(CAP_PROP_FRAME_HEIGHT, 480 + 100 * t);
}
namedWindow("窗口", WINDOW_FREERATIO);
capture >> image;
if (image.empty())
break;
masaike(image);
show_time(image);
imshow("窗口", image);
char c = waitKey(1);
if (c == '1')
t += 1;
if (c == '2')
t -= 1;
}
}
void draw_rect(Mat& image,int x,int y,int step,int flag)
{
std::vector<cv::Point> pts;
pts.push_back(cv::Point(x, y));
pts.push_back(cv::Point(x+step, y));
pts.push_back(cv::Point(x+step, y+step));
pts.push_back(cv::Point(x, y+step));
if (flag == 0)
cv::fillPoly(image, pts, cv::Scalar(120,120,120));
else if (flag == 1)
cv::fillPoly(image, pts, cv::Scalar(150,150,150));
else
cv::fillPoly(image, pts, cv::Scalar(180,180,180));
}
void masaike(Mat& image)
{
int start_x = 300;
int start_y = 150;
int h = 200;
int w = 200;
int step = 5;
int flag = 0;
for (int x = start_x; x < start_x + h; x += step)
{
for (int y = start_y; y < start_y + w; y += step)
{
draw_rect(image, x, y, step, flag);
flag = (flag + 1)%3;
}
}
}
void show_time(Mat &image)
{
time_t now = time(0);
tm* ltm = gmtime(&now);
string hour = to_string(ltm->tm_hour);
string min = to_string(ltm->tm_min);
string sec = to_string(ltm->tm_sec);
string text = hour + ":" + min + ":" + sec;
Point origin;
origin.x = 100;
origin.y = 350;
int font_face = FONT_HERSHEY_COMPLEX;
double font_scale = 2;
int thickness = 2;
putText(image, text, origin, font_face, font_scale, Scalar(0, 255, 255), thickness, 8, 0);
}
效果图:
然后谈一下我在VS中配置opencv时遇到了系统报错:“没有办法找到opencv_world460d.dll"的问题,我把报错的文件放到VS生成的ConsoleApplication1\x64\Debug下就好了,注意一定是ConsoleApplication1\x64下的Debug,在ConsoleApplication1\ConsoleApplication1\x64下面也有一个Debug,但是放到那个下面会有新的报错。
正确图例: