catalogue
1, Image reading and display
2, Image preprocessing
Principle and algorithm of Gaussian blur
Canny edge detection
3, Image clipping
4, Draw shapes and add text
5, Perspective transformation
6, Color detection
7, Shape detection and contour detection
8, Face recognition
1, Image reading and display
#include<opencv2/imgcodecs.hpp> #include<opencv2/highgui.hpp> #include<opencv2/imgproc.hpp> #include<iostream> using namespace cv; using namespace std; int main() { string path = "Resources/lambo.png";//Pathname of the picture Mat img = imread(path);//Assign a value to the image variable img after loading the image //if (path.empty()) { cout << "file not loaded" << endl; } //Check whether the file is open, and execute the print statement when it is not open //namedWindow("Image", WINDOW_FREERATIO);// Create an adjustable window called image imshow("Image", img);//Create a window to display the image img waitKey(0);//Constantly refresh images return 0; } waitKey()The function refreshes the image continuously with a frequency of delay,Unit is ms. delay When it is 0, this frame is always displayed. delay If it is not 0, the program waits after displaying a frame of image“ delay"ms The next frame of image is displayed.
2, Image preprocessing
#include <opencv2/imgcodecs.hpp> #include <opencv2/highgui.hpp> #include <opencv2/imgproc.hpp> #include <iostream> using namespace cv; using namespace std; void main() { string path = "Resources/test.png"; Mat img = imread(path); Mat imgGray,imgBlur,imgCanny,imgDil,imgErode; //Convert photos to grayscale cvtColor(img, imgGray, COLOR_BGR2GRAY); //Gaussian blur GaussianBlur(imgGray, imgBlur, Size(3, 3), 3, 0); //Canny edge detector usually does some fuzzy processing before using Canny edge detector Canny(imgBlur, imgCanny, 25, 75); //Create a kernel that can use bloat Mat kernel = getStructuringElement(MORPH_RECT, Size(3, 3)); //Image expansion dilate(imgCanny, imgDil, kernel); //Image erosion erode(imgDil, imgErode, kernel); //Result presentation imshow("Image", img); imshow("Image Gray", imgGray); imshow("Image Blur", imgBlur); imshow("Image Canny", imgCanny); imshow("Image Dilation", imgDil); imshow("Image Erode", imgErode); waitKey(0); }
Principle and algorithm of Gaussian blur
The first parameter is the image to be Gaussian blurred; The second parameter is the image output after processing; The third parameter is the size of Gaussian kernel. The first value is wide and the second value is high. The two values can be different, but they must be positive odd numbers; The fourth and fifth parameters are the standard deviation of the Gaussian kernel function in the X direction and Y direction respectively. If y is 0, the function will automatically set the value on y to be the same as X. if x and y are both 0, these two values will be calculated from the two values of the Gaussian kernel.
Canny edge detection
Canny(imgBlur, imgCanny, 25, 75);
The third and fourth parameters represent the bottom threshold and high threshold respectively, where the bottom threshold is often 1 / 2 or 1 / 3 of the high threshold
//Create a kernel that can use bloat Mat kernel = getStructuringElement(MORPH_RECT, Size(3, 3)); //Image expansion dilate(imgCanny, imgDil, kernel); //Image erosion erode(imgDil, imgErode, kernel); ```  ## 3, Image clipping ```c #include <opencv2/imgcodecs.hpp> #include <opencv2/highgui.hpp> #include <opencv2/imgproc.hpp> #include <iostream> using namespace cv; using namespace std; void main() { string path = "Resources/test.png"; Mat img = imread(path); Mat imgResize,imgCrop; //Resize image //cout << img. size() << endl;// View the size of the original image //resize(img, imgResize, Size(640, 480));// Scale by custom width and height resize(img, imgResize, Size(),0.5,0.5);//Scale //Image clipping Rect roi(200, 100, 300, 300); //The first two parameters are the distance between the X direction and the y direction from the upper left origin, and the last two parameters are the extended x and y lengths imgCrop = img(roi); imshow("Image", img); imshow("Image Resize", imgResize); imshow("Image Crop", imgCrop); waitKey(0); }
4, Draw shapes and add text
#include <opencv2/imgcodecs.hpp> #include <opencv2/highgui.hpp> #include <opencv2/imgproc.hpp> #include <iostream> using namespace cv; using namespace std; //Draw shapes and add text void main() { //Create a blank image Mat img(512, 512, CV_8UC3, Scalar(255, 255, 255)); //Draw circle //circle(img, Point(256, 256), 155, Scalar(0, 69, 255),10); circle(img, Point(256, 256), 155, Scalar(0, 69, 255),FILLED); //The function parameters are output to the image img, circle center, radius, color and thickness (FILLED indicates full) //draw rectangle rectangle(img, Point(130, 226), Point(382, 286), Scalar(255, 255, 255), FILLED); //The function parameters are output to the image img, the vertex coordinates of the upper left corner of the rectangle, the vertex coordinates of the lower right corner, color and thickness //Draw line segments line(img, Point(130, 296), Point(382, 296), Scalar(255, 255, 255), 2); //The function parameters are output to the image img, two endpoint coordinates, color and thickness //Add text putText(img, "Murtaza's Workshop", Point(137, 262), FONT_HERSHEY_DUPLEX, 0.75, Scalar(0, 69, 255), 2); //The function parameters are output to image img, text content, starting point, font, size, color and thickness imshow("Image", img); waitKey(0); }
5, Perspective transformation
#include <opencv2/imgcodecs.hpp> #include <opencv2/highgui.hpp> #include <opencv2/imgproc.hpp> #include <iostream> using namespace cv; using namespace std; float w = 250, h = 350; Mat matrix, imgWarp; // Perspective transformation void main() { string path = "Resources/cards.jpg"; Mat img = imread(path); 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} }; matrix = getPerspectiveTransform(src, dst);//Get perspective transformation matrix //src is the quadrilateral vertex coordinates of the source image, and dst is the quadrilateral vertex coordinates corresponding to the target image warpPerspective(img, imgWarp, matrix, Point(w, h)); //The parameters are input image, output image, perspective transformation matrix and image size for (int i = 0; i < 4; i++) { circle(img, src[i], 10, Scalar(0, 0, 255), FILLED); }//Mark the target vertex in the original image imshow("Image", img); imshow("Image Warp", imgWarp); waitKey(0); }
6, Color detection
[OpenCV] HSV color recognition - HSV basic color component range_ Taily Lao Duan's column - CSDN blog_ hsv
Color space conversion function cvtColor
#include <opencv2/imgcodecs.hpp> #include <opencv2/highgui.hpp> #include <opencv2/imgproc.hpp> #include <iostream> using namespace cv; using namespace std; Mat imgHSV,mask; int hmin = 0, smin = 0, vmin = 0; int hmax =179, smax = 255, vmax = 255; void main() { string path = "Resources/shapes.png"; Mat img = imread(path); cvtColor(img, imgHSV, COLOR_BGR2HSV); //HSV color space H (hue): 0 ~ 180 s (saturation): 0 ~ 255 V (brightness): 0 ~ 255 namedWindow("Trackbars", (640, 200));//Create a window named Trackbars with a size of 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); //The createTrackbar function creates a track bar, //The four parameters are the name of the track bar, the output window, a pointer to an integer to represent the current value and the maximum value that can be reached while (true) { //Detect the color we want and set a mask in the range of colors Scalar lower(hmin, smin, vmin);//Minimum value of HSV range Scalar upper(hmax, smax, vmax);//Maximum value of HSV range inRange(imgHSV, lower, upper, mask);//Input, low value, high value, output //inRange is to set the pixel value within the threshold interval to white (255), while the pixel value not within the threshold interval is set to black (0) imshow("Image", img); imshow("Image HSV", imgHSV); imshow("Image Mask", mask); waitKey(1); } }
7, Shape detection and contour detection
#include <opencv2/imgcodecs.hpp> #include <opencv2/highgui.hpp> #include <opencv2/imgproc.hpp> #include <iostream> using namespace cv; using namespace std; Mat imgGray, imgBlur, imgCanny, imgDil, imgErode; //Define a contour processing function void getContours(Mat imgDil,Mat img) { vector<vector<Point>> contours;//{ {Point(20,30),Point(50,60)},{}, {}} vector<Vec4i>hierarchy;//Four variables of type int are placed in the vector findContours(imgDil, 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()); for (int i = 0; i < contours.size(); i++) { int area = contourArea(contours[i]); cout << area << endl;//Area to be filtered correctly (noise filtering) string objectType; //Judge shape if (area>1000) { float peri = arcLength(contours[i], true); approxPolyDP(contours[i], conPoly[i], 0.02 * peri, true);//Find approximate value cout << conPoly[i].size() << endl; boundRect[i] = boundingRect(conPoly[i]);//Boundary rectangle int objCor = (int)conPoly[i].size(); if (objCor == 3) { objectType = "Tri"; } 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"; } } if (objCor > 4) { objectType = "Circle"; } drawContours(img, conPoly, i, Scalar(255, 0, 255), 2);//Draw count outline rectangle(img, boundRect[i].tl(), boundRect[i].br(), Scalar(0, 255, 0), 5);//Draw a rectangle //The name of the printed drawing putText(img, objectType, { boundRect[i].x,boundRect[i].y - 5 }, FONT_HERSHEY_PLAIN, 1, Scalar(0, 69, 255), 2); } } } void main() { string path = "Resources/shapes.png"; Mat img = imread(path); //Image preprocessing //1. Convert photos to grayscale cvtColor(img, imgGray, COLOR_BGR2GRAY); //2. Gaussian blur GaussianBlur(imgGray, imgBlur, Size(3, 3), 3, 0); //3.Canny edge detector Canny(imgBlur, imgCanny, 25, 75); //4. Create a kernel that can use expansion Mat kernel = getStructuringElement(MORPH_RECT, Size(3, 3)); //5. Image expansion dilate(imgCanny, imgDil, kernel); getContours(imgDil,img); imshow("Image", img); /*imshow("Image Gray", imgGray); imshow("Image Blur", imgBlur); imshow("Image Canny", imgCanny); imshow("Image Dilation", imgDil);*/ waitKey(0); }
reference resources:
Common data types of opencv (explanation of vector and contour)_ One rabbit blog - CSDN blog_ The data type of contours is
Detailed explanation of findcontours function parameters_ Makino's blog - CSDN blog_ findcontours function
8, Face recognition
#include <opencv2/imgcodecs.hpp> #include <opencv2/highgui.hpp> #include <opencv2/imgproc.hpp> #include <opencv2/objdetect.hpp> #include <iostream> using namespace cv; using namespace std; void main() { string path = "Resources/test.png"; Mat img = imread(path); CascadeClassifier faceCascade;//Create cascade classifier //Load training model faceCascade.load("Resources/haarcascade_frontalface_default.xml"); if(faceCascade.empty()){cout<<"XML file not loaded"<<endl; } //Check whether the file is open, and execute the print statement when it is not open vector<Rect>faces;//Create a vector for storing faces faceCascade.detectMultiScale(img, faces, 1.1, 10); //The detectMultiScale function can detect all faces in the picture, and save the coordinates and size of each face with vector //Draw a rectangular border of the face in the original image 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); }
reference resources:
Usage of cv::Rect rectangle class in openCV_ sinat_38102206 blog - CSDN blog_ cv rect
Introduction to OpenCV detectMultiScale() function parameters_ zhuyue_66-CSDN blog_ The meaning of the parameters of the detectmultiscale function
Result display:
Learning source: 4h starting C + + Opencv_ Beep beep beep_ bilibili
The article is reproduced in https://blog.csdn.net/qq_62330330/article/details/122800959 , is an excellent blogger (my classmate). He himself has agreed to reprint it