CPP----opencv练习

用0-1二进制表示图像
在这里插入图片描述

将灰度图划分为2(8)=256个等级*

在这里插入图片描述
加入颜色三通道
在这里插入图片描述
利用opencv查看图片,视频,摄像头

#include <iostream>
#include <opencv2/highgui.hpp>
#include <opencv2/imgcodecs.hpp>
#include <opencv2/imgproc.hpp>

using namespace cv;
using namespace std;

/  Images  //

//void main() {
//  string path = "Resources/test.png";
//  Mat img = imread(path);
//  imshow("Image", img);
//  waitKey(0);
//}


/  Videos  //
 /*void main() {

	string path = "Resources/test_video.mp4";
	VideoCapture cap(path);
	Mat img;

	while (true) {

		cap.read(img);
		imshow("Image", img);
		waitKey(20);
	}
 }*/

/  Webcam  //

 void main() {
	VideoCapture cap(0);
	Mat img;
	while (true) {
		cap.read(img);
		imshow("Image", img);
		waitKey(1);
	}
 }

对图像进行灰度化,模糊化,边缘,膨胀,腐蚀操作

#include <opencv2/imgcodecs.hpp>
#include <opencv2/highgui.hpp>
#include <opencv2/imgproc.hpp>
#include <iostream>
using namespace cv;
using namespace std;
void main() {
  std::string path = "Resources/test.png";
  Mat img = imread(path);
  Mat imgGray,imgBlur,imgCanny, imgDil, imgErode;
  cvtColor(img, imgGray, COLOR_BGR2GRAY);
  GaussianBlur(img, imgBlur, Size(3, 3), 3, 0);
  Canny(imgBlur, imgCanny, 25, 75);

  Mat kernel = getStructuringElement(MORPH_RECT, Size(3, 3));
  dilate(imgCanny, imgDil, kernel);
  erode(imgDil, imgErode, kernel);
  imshow("Image", img);
  imshow("Image Gray", imgGray);
  imshow("Image Blur", imgBlur);
  imshow("Image Canny", imgCanny);
  imshow("Image dilate", imgDil);
  imshow("Image erode", imgErode);
  waitKey(0);
}

对图像进行缩放,裁剪操作

#include <opencv2/imgcodecs.hpp>
#include <opencv2/highgui.hpp>
#include <opencv2/imgproc.hpp>
#include <iostream>

using namespace std;
using namespace cv;

void main() {
  string path = "Resources/test.png";
  Mat img = imread(path);
  Mat imgResize,imgCrop;

  cout << img.size() << endl;
  resize(img, imgResize, Size(640, 640));
  resize(img, imgResize, Size(), 0.5, 0.5);
  Rect roi(100, 100, 300, 250);
  imgCrop = img(roi);
  imshow("img", img);
  imshow("img resize", imgResize);
  imshow("img crop", imgCrop);
  waitKey(0);
}

效果图如下:
在这里插入图片描述

生成画布并画圆矩形,直线,文字等

#include <iostream>
#include <opencv2/highgui.hpp>
#include <opencv2/imgcodecs.hpp>
#include <opencv2/imgproc.hpp>

using namespace std;
using namespace cv;

void main() {
  Mat img(512, 512, CV_8UC3, Scalar(255, 255, 255));
  circle(img, Point(256, 256), 155, Scalar(0, 69, 255));
  circle(img, Point(256, 256), 155, Scalar(0, 69, 255), 10);
  circle(img, Point(256, 256), 155, Scalar(0, 69, 255), FILLED);
  rectangle(img, Point(168, 168), Point(256, 256), Scalar(223, 0, 45), 2);
  line(img, Point(150, 150), Point(300, 300), Scalar(224, 56, 255), 3);
  putText(img, "this is opencv", Point(150, 150), FONT_HERSHEY_COMPLEX, 0.75,
          Scalar(0, 0, 0), 2);
  imshow("img", img);
  waitKey(0);
}

效果图如下:
在这里插入图片描述
透视变换与仿射变换

#include <iostream>
#include <opencv2/highgui.hpp>
#include <opencv2/imgcodecs.hpp>
#include <opencv2/imgproc.hpp>

using namespace std;
using namespace cv;

float w=250, h=350;

void main() {
    string path = "Resources/cards.jpg";
    Mat img = imread(path);
    Mat imgWarp,matrix;


    Point2f src[4] = {{529, 142}, {771, 190}, {405, 395}, {674, 457}};
    Point2f dst[4] = {{0.0f, 0.0f}, {w, 0.0f}, {0.0f, h}, {w, h}};
    for (int i = 0; i < 4; i++) {
      circle(img, src[i], 10, Scalar(0, 0, 255), FILLED);
    }
    matrix = getPerspectiveTransform(src, dst);
    warpPerspective(img, imgWarp, matrix, Point(w, h));

    for (int i = 0; i < 4; i++) {
      circle(img, src[i], 10, Scalar(0, 0, 255), FILLED);
    }


    imshow("img", img);
    imshow("img Warp", imgWarp);
    waitKey(0);
  }

效果图如下:
在这里插入图片描述颜色检测

#include <iostream>
#include <opencv2/highgui.hpp>
#include <opencv2/imgcodecs.hpp>
#include <opencv2/imgproc.hpp>
using namespace std;
using namespace cv;
Mat imgHSV, mask;
int hmin = 0, smin = 110, vmin = 153;
int hmax = 19, smax = 240, vmax = 255; 

// color detection
void main() {
  //string path = "Resources/lambo.png";
  string path = "Resources/shapes.png";
  Mat img = imread(path);

  cvtColor(img, imgHSV, COLOR_BGR2HSV);
  namedWindow("Trackbars", (640, 200));
  createTrackbar("Hue Min", "Trackbars", &hmin, 179);
  createTrackbar("Hue Max", "Trackbars", &hmax, 179);
  createTrackbar("Sat Min", "Trackbars", &smin, 255);
  createTrackbar("Sat Max", "Trackbars", &smax, 255);
  createTrackbar("Val Min", "Trackbars", &vmin, 255);
  createTrackbar("Val Max", "Trackbars", &vmax, 255);

  while (true) {
    Scalar lower(hmin, smin, vmin);
    Scalar upper(hmax, smax, vmax);
    inRange(imgHSV, lower, upper, mask);
    imshow("img", img);
    imshow("img hsv", imghsv);
    imshow("img mask", mask);
    waitKey(1);  
  }
}

在这里插入图片描述

寻找边界

#include <iostream>
#include <opencv2/highgui.hpp>
#include <opencv2/imgcodecs.hpp>
#include <opencv2/imgproc.hpp>

using namespace std;
using namespace cv;

Mat imgGray, imgBlur, imgCanny, imgDil, imgErode;

void getContours(Mat imgDil, Mat img) {
  vector<vector<Point>> contours;
  vector<Vec4i> hierarchy;
  findContours(imgDil, contours, hierarchy, RETR_EXTERNAL, CHAIN_APPROX_SIMPLE);
  // drawContours(img, contours, -1, Scalar(255, 0, 255), 2);
  for (int i = 0; i < contours.size(); i++) {
    int area = contourArea(contours[i]);
    cout << area << endl;

    vector<vector<Point>> conPoly(contours.size());
    vector<Rect> boundRect(contours.size());
    string objectType;

    if (area > 1000) {
      float peri = arcLength(contours[i], true);
      approxPolyDP(contours[i], conPoly[i], 0.02 * peri, true);

      cout << conPoly[i].size() << endl;
      boundRect[i] = boundingRect(conPoly[i]);

      int objCor = (int)conPoly[i].size();
	  if (objCor == 3) { objectType = "Tri";}
	  else if (objCor == 4) 
	  {
            float aspRatio =
                (float)boundRect[i].width / (float)boundRect[i].height;
            cout << aspRatio << endl;
            if (aspRatio > 0.95 && aspRatio < 1.05) {
              objectType = "Square";
            } else{objectType = "Rect";}
	  }
	  else if (objCor >  4) { objectType = "Circle";}

	  drawContours(img, contours, -1, Scalar(255, 0, 255), 2);
      rectangle(img, boundRect[i].tl(), boundRect[i].br(),Scalar(0, 255, 0), 5);
      putText(img, objectType,{boundRect[i].x, boundRect[i].y - 5}, FONT_HERSHEY_PLAIN, 1,Scalar(0, 69, 255), 1);
    }
  }
}

void main() {
  string path = "Resources/shapes.png";
  Mat img = imread(path);

  cvtColor(img, imgGray, COLOR_BGR2GRAY);
  GaussianBlur(imgGray, imgBlur, Size(3, 3), 3, 0);
  Canny(imgBlur, imgCanny, 25, 75);
  Mat kernel = getStructuringElement(MORPH_RECT, Size(3, 3));
  dilate(imgCanny, imgDil, kernel);

  getContours(imgDil, img);

  imshow("img", img);
  // imshow("img resize", imgGray);
  // imshow("img crop", imgBlur);
  // imshow("img crop", imgCanny);
  // imshow("img crop", imgDil);
  waitKey(0);
}

在这里插入图片描述追踪人脸

#include <iostream>
#include <opencv2/highgui.hpp>
#include <opencv2/imgcodecs.hpp>
#include <opencv2/imgproc.hpp>
#include <opencv2/objdetect.hpp>

using namespace std;
using namespace cv;


void main() {
  string path = "Resources/test.png";
  Mat img = imread(path);

  CascadeClassifier faceCascade;
  faceCascade.load("Resources/haarcascade_frontalface_default.xml");

  if (faceCascade.empty()) {
    cout << "XML file not loaded" << endl;
  }
  vector<Rect> faces;
  faceCascade.detectMultiScale(img, faces, 1.1, 10);
  for (int i = 0; i < faces.size(); i++) {
    rectangle(img, faces[i].tl(), faces[i].br(), Scalar(255, 0, 255), 3);
  }
  imshow("image", img);
  waitKey(0);
}

在这里插入图片描述
摄像头寻色
使用CV_BGR2HSV函数时,所得的H、S、V值范围分别是[0,180),[0,255),[0,255)
在这里插入图片描述

#include <iostream>
#include <opencv2/highgui.hpp>
#include <opencv2/imgcodecs.hpp>
#include <opencv2/imgproc.hpp>
using namespace cv;
using namespace std;

int main() {
  VideoCapture cap(0);
  Mat img;
  Mat imgHSV, mask, imgColor;
  int hmin = 0, smin = 0, vmin = 0;
  int hmax = 179, smax = 255, vmax = 255;

  namedWindow("Trackbars", (640, 200));  // Create Window
  createTrackbar("Hue Min", "Trackbars", &hmin, 179);
  createTrackbar("Hue Max", "Trackbars", &hmax, 179);
  createTrackbar("Sat Min", "Trackbars", &smin, 255);
  createTrackbar("Sat Max", "Trackbars", &smax, 255);
  createTrackbar("Val Min", "Trackbars", &vmin, 255);
  createTrackbar("Val Max", "Trackbars", &vmax, 255);

  while (true) {
      cap.read(img);
      cvtColor(img, imgHSV, COLOR_BGR2HSV);

      Scalar lower(hmin, smin, vmin);
      Scalar upper(hmax, smax, vmax);

      inRange(imgHSV, lower, upper, mask);
       hmin, smin, vmin, hmax, smax, vmax;
       cout << hmin << "," << smin << "," << vmin << "," << hmax << "," << smax
           << "," << vmax << endl;
      imshow("Image", img);
      imshow("Mask", mask);
      waitKey(1);
    }
  }

效果图
在这里插入图片描述
寻找标签

#include <iostream>
#include <opencv2/highgui.hpp>
#include <opencv2/imgcodecs.hpp>
#include <opencv2/imgproc.hpp>

using namespace cv;
using namespace std;

///  Project 2 - Document Scanner  //

Mat imgOriginal, imgGray, imgBlur, imgCanny, imgThre, imgDil, imgErode, imgWarp,
    imgCrop;
vector<Point> initialPoints, docPoints;
float w = 420, h = 596;

Mat preProcessing(Mat img) {
  cvtColor(img, imgGray, COLOR_BGR2GRAY);
  GaussianBlur(imgGray, imgBlur, Size(3, 3), 3, 0);
  Canny(imgBlur, imgCanny, 25, 75);
  Mat kernel = getStructuringElement(MORPH_RECT, Size(3, 3));
  dilate(imgCanny, imgDil, kernel);
  // erode(imgDil, imgErode, kernel);
  return imgDil;
}

vector<Point> getContours(Mat image) {
  vector<vector<Point>> contours;
  vector<Vec4i> hierarchy;

  findContours(image, contours, hierarchy, RETR_EXTERNAL, CHAIN_APPROX_SIMPLE);
  // drawContours(img, contours, -1, Scalar(255, 0, 255), 2);
  vector<vector<Point>> conPoly(contours.size());
  vector<Rect> boundRect(contours.size());

  vector<Point> biggest;
  int maxArea = 0;

  for (int i = 0; i < contours.size(); i++) {
    int area = contourArea(contours[i]);
    // cout << area << endl;

    string objectType;

    if (area > 1000) {
      float peri = arcLength(contours[i], true);
      approxPolyDP(contours[i], conPoly[i], 0.02 * peri, true);

      if (area > maxArea && conPoly[i].size() == 4) {
        // drawContours(imgOriginal, conPoly, i, Scalar(255, 0, 255), 5);
        biggest = {conPoly[i][0], conPoly[i][1], conPoly[i][2], conPoly[i][3]};
        maxArea = area;
      }
      // drawContours(imgOriginal, conPoly, i, Scalar(255, 0, 255), 2);
      // rectangle(imgOriginal, boundRect[i].tl(), boundRect[i].br(), Scalar(0,
      // 255, 0), 5);
    }
  }
  return biggest;
}

void drawPoints(vector<Point> points, Scalar color) {
  for (int i = 0; i < points.size(); i++) {
    circle(imgOriginal, points[i], 10, color, FILLED);
    putText(imgOriginal, to_string(i), points[i], FONT_HERSHEY_PLAIN, 4, color,
            4);
  }
}

vector<Point> reorder(vector<Point> points) {
  vector<Point> newPoints;
  vector<int> sumPoints, subPoints;

  for (int i = 0; i < 4; i++) {
    sumPoints.push_back(points[i].x + points[i].y);
    subPoints.push_back(points[i].x - points[i].y);
  }

  newPoints.push_back(points[min_element(sumPoints.begin(), sumPoints.end()) -
                             sumPoints.begin()]);  // 0
  newPoints.push_back(points[max_element(subPoints.begin(), subPoints.end()) -
                             subPoints.begin()]);  // 1
  newPoints.push_back(points[min_element(subPoints.begin(), subPoints.end()) -
                             subPoints.begin()]);  // 2
  newPoints.push_back(points[max_element(sumPoints.begin(), sumPoints.end()) -
                             sumPoints.begin()]);  // 3

  return newPoints;
}

Mat getWarp(Mat img, vector<Point> points, float w, float h) {
  Point2f src[4] = {points[0], points[1], points[2], points[3]};
  Point2f dst[4] = {{0.0f, 0.0f}, {w, 0.0f}, {0.0f, h}, {w, h}};

  Mat matrix = getPerspectiveTransform(src, dst);
  warpPerspective(img, imgWarp, matrix, Point(w, h));

  return imgWarp;
}

void main() {
  string path = "Resources/paper.jpg";
  imgOriginal = imread(path);
  // resize(imgOriginal, imgOriginal, Size(), 0.5, 0.5);

  // Preprpcessing - Step 1
  imgThre = preProcessing(imgOriginal);

  // Get Contours - Biggest  - Step 2
  initialPoints = getContours(imgThre);
  // drawPoints(initialPoints, Scalar(0, 0, 255));
  docPoints = reorder(initialPoints);
  // drawPoints(docPoints, Scalar(0, 255, 0));

  // Warp - Step 3
  imgWarp = getWarp(imgOriginal, docPoints, w, h);

  // Crop - Step 4
  int cropVal = 5;
  Rect roi(cropVal, cropVal, w - (2 * cropVal), h - (2 * cropVal));
  imgCrop = imgWarp(roi);

  imshow("Image", imgOriginal);
  // imshow("Image Dilation", imgThre);
  // imshow("Image Warp", imgWarp);
  imshow("Image Crop", imgCrop);
  waitKey(0);
}

在这里插入图片描述
识别车牌

#include <iostream>
#include <opencv2/highgui.hpp>
#include <opencv2/imgcodecs.hpp>
#include <opencv2/imgproc.hpp>
#include <opencv2/objdetect.hpp>

using namespace cv;
using namespace std;

///  Project 3 - License Plate Detector //

void main() {
  Mat img;
  VideoCapture cap(0);

  CascadeClassifier plateCascade;
  plateCascade.load("Resources/haarcascade_russian_plate_number.xml");

  if (plateCascade.empty()) {
    cout << "XML file not loaded" << endl;
  }

  vector<Rect> plates;

  while (true) {
    cap.read(img);
    //string path = "Resources/car2.jpg";
    //Mat img = imread(path);
    plateCascade.detectMultiScale(img, plates, 1.1, 10);

    for (int i = 0; i < plates.size(); i++) {
      Mat imgCrop = img(plates[i]);
      // imshow(to_string(i), imgCrop);
      imwrite("Resources/Plates/" + to_string(i) + ".png", imgCrop);
      rectangle(img, plates[i].tl(), plates[i].br(), Scalar(255, 0, 255), 3);
    }

    imshow("Image", img);
    waitKey(1);
  }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值