一、什麼是OpenCV circle函數
OpenCV是一個基於BSD許可(開源)發行的跨平台的計算機視覺庫,包含了非常多的圖像處理和計算機視覺算法。OpenCV circle函數是OpenCV庫中用來繪製圓形的函數,其API如下:
void circle(InputOutputArray img, Point center, int radius, const Scalar& color, int thickness=1, int lineType=LINE_8, int shift=0)
其中,各個參數的含義如下:
- img:需要繪製圓形的圖像
- center:圓形的中心點坐標
- radius:圓形的半徑
- color:圓形的顏色
- thickness:圓形的線條粗細
- lineType:圓形線條的類型
- shift:圓形線條位置的小數位數
二、如何在圖片中繪製圓形
在OpenCV中繪製圓形有兩種方式,一種是將圓形繪製在原圖上,另一種是將圓形繪製在新的空白圖片上。
三、在原圖上繪製圓形
在原圖上繪製圓形的主要步驟如下:
- 讀取一張圖片,使用circle函數繪製圓形
- 顯示繪製後的圖片
具體代碼如下:
#include <opencv2/opencv.hpp>
using namespace cv;
int main()
{
Mat img = imread("test.jpg");
circle(img, Point(img.cols / 2, img.rows / 2), 50, Scalar(0, 0, 255), 2);
imshow("img", img);
waitKey(0);
return 0;
}
四、在空白圖片上繪製圓形
在空白圖片上繪製圓形的主要步驟如下:
- 創建一張空白的圖片,使用circle函數繪製圓形
- 顯示繪製後的圖片
具體代碼如下:
#include <opencv2/opencv.hpp>
using namespace cv;
int main()
{
Mat img = Mat::zeros(Size(500, 500), CV_8UC3);
circle(img, Point(img.cols / 2, img.rows / 2), 50, Scalar(0, 0, 255), 2);
imshow("img", img);
waitKey(0);
return 0;
}
五、如何繪製多個圓形
需要繪製多個圓形時,只需要多次使用circle函數即可。
具體代碼如下:
#include <opencv2/opencv.hpp>
using namespace cv;
int main()
{
Mat img = imread("test.jpg");
circle(img, Point(100, 100), 50, Scalar(0, 0, 255), 2);
circle(img, Point(200, 200), 50, Scalar(0, 255, 0), 2);
circle(img, Point(300, 300), 50, Scalar(255, 0, 0), 2);
imshow("img", img);
waitKey(0);
return 0;
}
六、實際案例:在視頻中實時檢測並標註圓形
在實際應用中,需要實時檢測並標註一些目標,比如檢測一個運動的球並畫出其軌跡。具體步驟如下:
- 打開攝像頭,讀取視頻流
- 對每一幀圖像進行處理,使用circle函數檢測並繪製目標圓形
- 顯示處理後的每一幀圖像
具體代碼如下:
#include <opencv2/opencv.hpp>
using namespace cv;
int main()
{
VideoCapture cap(0);
if (!cap.isOpened())
{
std::cout << "Cannot open camera!" << std::endl;
return -1;
}
namedWindow("img", WINDOW_AUTOSIZE);
int last_x = -1, last_y = -1;
while (true)
{
Mat frame;
cap >> frame;
if (frame.empty()) break;
Mat gray, canny;
cvtColor(frame, gray, COLOR_BGR2GRAY);
Canny(gray, canny, 50, 150, 3);
std::vector<Vec3f> circles;
HoughCircles(canny, circles, HOUGH_GRADIENT, 1, canny.rows / 8, 150, 30, 0, 0);
if (!circles.empty())
{
for (const auto& circle : circles)
{
int x = (int)circle[0];
int y = (int)circle[1];
int radius = (int)circle[2];
circle(frame, Point(x, y), radius, Scalar(0, 0, 255), 2);
if (last_x != -1 && last_y != -1)
line(frame, Point(x, y), Point(last_x, last_y), Scalar(0, 255, 0), 2);
last_x = x;
last_y = y;
}
}
else
{
last_x = -1;
last_y = -1;
}
imshow("img", frame);
if (waitKey(30) == 'q') break;
}
return 0;
}
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/254479.html