opencv 學習(3)幾何圖形的簡單識別
阿新 • • 發佈:2018-12-10
找到圖形的’極點‘,然後根據圖形的幾何關係便可以得到結果。程式碼如下。(如有錯誤還請指出)
/******************************************************************** ** 文 件 名:幾何圖形的簡單判斷 ** 創 建 人:yk ** 最後修改時間:2018年9月1日 *********************************************************************/ #include "stdafx.h" #include <iostream> #include <stdio.h> #include "opencv2/core.hpp" #include "opencv2/core/utility.hpp" #include "opencv2/core/ocl.hpp" #include "opencv2/imgcodecs.hpp" #include "opencv2/highgui.hpp" void YKrectangle(Mat &image, Point Start, Point End, int flog) { if (flog == 0) { for (int i = Start.y; i <= End.y; i++) { for (int j = Start.x; j <= End.x; j++) { image.at<Vec3b>(i, j)[0] = 0; image.at<Vec3b>(i, j)[1] = 255; image.at<Vec3b>(i, j)[2] = 0; } } } else if (flog == 1) { for (int i = Start.y; i <= End.y; i++) { for (int j = Start.x; j <= End.x; j++) { if (i == Start.y || i == End.y || j == Start.x || j == End.x) { image.at<Vec3b>(i, j)[0] = i; image.at<Vec3b>(i, j)[1] = j; image.at<Vec3b>(i, j)[2] = (i + j) / 2; } } } } } int main() { int x = 0, y = 0, x1 = 0, y1 = 0; Mat img = imread("G:\\yk\\Desktop\\檔案\\aI\\opencv\\opencv圖\\3.bmp", 0); Mat img2 = imread("G:\\yk\\Desktop\\檔案\\aI\\opencv\\opencv圖\\3.bmp", 0);; Mat img1 = Mat::zeros(img.rows, img.cols, CV_8UC3); vector<vector<Point>>conts; vector<Vec4i>hicouts; threshold(img, img, 100, 254, 1); blur(img, img, Size(3, 3)); imshow("3", img2); img = ~img; imshow("1", img); for (int i = 0; i < img2.rows; i++)//畫到原圖上 { for (int j = 0; j < img2.cols; j++) { if ((int)img2.at<uchar>(i, j) > 0) { img2.at<uchar>(i, j) = 255; } } } for (int i = 0; i < img.rows; i++)//畫到原圖上 { for (int j = 0; j < img.cols; j++) { img1.at<Vec3b>(i, j)[0] = img.at<uchar>(i, j); img1.at<Vec3b>(i, j)[1] = img.at<uchar>(i, j); img1.at<Vec3b>(i, j)[2] = img.at<uchar>(i, j); //cout << (int)img.at<uchar>(i, j) << endl; } } Canny(img, img, 30, 70); findContours(img, conts, hicouts, CV_RETR_TREE, CHAIN_APPROX_SIMPLE); for (int i = 0; i < conts.size(); i++) { int temp = conts[i][0].x, temp1 = conts[i][0].y, temp2 = conts[i][0].x, temp3 = conts[i][0].y; for (int j = 0; j < conts[i].size(); j++) { if (conts[i][j].x < temp) { temp = conts[i][j].x; } if (conts[i][j].y < temp1) { temp1 = conts[i][j].y; } if (conts[i][j].x > temp2) { temp2 = conts[i][j].x; } if (conts[i][j].y > temp3) { temp3 = conts[i][j].y; } } //cout << (int)img.at<uchar>(temp - 10, temp1 - 10) << endl; if (fabs((temp3 - temp1) - (temp2 - temp)) < 5) { Scalar color(0, 255, 0); drawContours(img1, conts, i, color, -1, 8, hicouts); } else if ((int)img2.at<uchar>(temp + 50, temp1 + 3) == 0) { Scalar color(255, 0, 0); drawContours(img1, conts, i, color, -1, 8, hicouts); } else { Scalar color(0, 0, 255); drawContours(img1, conts, i, color, -1, 8, hicouts); } Point start(temp - 5, temp1 - 5), end(temp2 + 5, temp3 + 5); YKrectangle(img1, start, end, 1); } imshow("s", img1); imwrite("G:\\yk\\Desktop\\檔案\\aI\\opencv\\opencv圖\\3result.bmp", img1); waitKey(0); }