学习OpenCV3 第八章练习

1.编写程序完成:(1)从视频读取图像帧 (2)将结果转化为灰度图 (3)对该图像完成Canny边缘检测

#include <iostream>
#include <opencv2/opencv.hpp>
using namespace std; using namespace cv; int main() { VideoCapture capture("./videos/Tunak.mp4"); double width = capture.get(CAP_PROP_FRAME_WIDTH); double height = capture.get(CAP_PROP_FRAME_HEIGHT); Mat show(height,width*3,CV_8UC3); Rect rect1(0, 0,width, height); Rect rect2(width, 0, width, height); Rect rect3(width*2, 0, width, height); Mat mat1 = show(rect1); Mat mat2 = show(rect2); Mat mat3 = show(rect3); int frameCount=capture.get(CAP_PROP_FRAME_COUNT); namedWindow("show", WINDOW_NORMAL); Point origin(15, 15); Scalar color(0, 0, 255); for (int i = 0; i < frameCount; i++) { Mat temp; capture >>temp; temp.copyTo(mat1); cvtColor(temp, temp, COLOR_RGB2GRAY); cvtColor(temp, temp, COLOR_GRAY2RGB); temp.copyTo(mat2); Canny(mat1, temp, 10, 100, 3, true); cvtColor(temp, temp, COLOR_GRAY2RGB); temp.copyTo(mat3); putText(mat3, "CANNY", origin, FONT_HERSHEY_COMPLEX_SMALL, 1.0, color, 2, 8, false); imshow("show", show); waitKey(33); } return 0; }

总结:在使用cvtColor方法将RGB图转化为灰度图时,得到的结果为单通道,没办法显示在三通道的图片中,所以还要再进行一次转化。

效果图:

2.编写程序读取并显示一张图片。当用户鼠标点击图片时,读取当前鼠标对应位置的像素值和坐标。

#include <iostream>
#include <opencv2/opencv.hpp>

using namespace std;
using namespace cv;

class Para{
public:
    Mat dest;
};

void TestCallBack(int event, int x, int y, int flags, void* param);

int main()
{
    Mat img = imread("./videos/1.jpg");
    Para param;
    img.copyTo(param.dest);
    namedWindow("show", WINDOW_AUTOSIZE);
    imshow("show", img);
    setMouseCallback("show", TestCallBack, &param);
    waitKey(0);
    destroyWindow("show");
    return 0;
}

void TestCallBack(int event,int x,int y,int flags, void* param) {
    Para* p = (Para*)param;
    String s;

    if (event == EVENT_LBUTTONDOWN) {
        s.append("P:("); s.append(to_string(x)); s.append(","); s.append(to_string(y)); s.append(")"); s.append(" C:");
        s.append("("); s.append(to_string(p->dest.at<Vec3b>(y, x)[0])); s.append(","); s.append(to_string(p->dest.at<Vec3b>(y, x)[1])); s.append(",");
        s.append(to_string(p->dest.at<Vec3b>(y, x)[2])); s.append(")");
       putText(p->dest,s , Point(x,y), FONT_HERSHEY_COMPLEX_SMALL, 1, Scalar(0, 0, 255), 2, 8, false);
       imshow("show", p->dest);
    }
}

总结:(1)需要用到下一章的setMouseCallback方法。

    (2)Mat::at(Point(x,y))=Mat::at(y,x)。最开始由于没有能够调换顺序导致运行时不定期抛异常。

效果图:

灯是白色的,东哥的头发是黑色的,bingo。

参考资料:

(1)有关坐标变化的原因:https://blog.csdn.net/wangxuwen2/article/details/52443978

(2)有关setMouseCallback的详细用法(重点关注param参数的使用):https://blog.csdn.net/wuxulong123/article/details/105299610/

(3)有关RGB和灰度图的变化:https://www.zhihu.com/question/266684723

 

posted @ 2020-09-21 18:14  1北风_之神1  阅读(128)  评论(0)    收藏  举报