时间:2022-07-14 08:18:01 | 栏目:Python代码 | 点击:次
最近在学习OpenCV,本文主要介绍了OpenCV 绘制同心圆的示例代码,分享给大家,具体如下:
// 绘制同心圆 void DrawConcentricCircle(cv::Mat mask, const cv::Point2i ¢er, int radius1,int radius2, const cv::Scalar &color, int thickness,int linetype) { // 创建画布 cv::Mat canvas = cv::Mat::zeros(mask.size(), CV_8UC1); // 计算内径和外径 int inradius = min(radius1, radius2); int outradius = max(radius1, radius2); // 分情况讨论 // 当thickness大于0时,绘制的是两个圆型线条组成的同心圆,不需填充 if (thickness > 0) { cv::circle(mask, center, outradius, color, thickness, linetype); cv::circle(mask, center, inradius, color, thickness, linetype); } // 当thickness小于0,一般为-1,绘制的是填充同心圆,内圆不能有填充色 else { cv::circle(canvas, center, outradius, cv::Scalar(255), -1, linetype); cv::circle(canvas, center, inradius, cv::Scalar(0), -1, linetype); int row = mask.rows; int col = mask.cols; for (int i = 0; i < row; ++i) { for (int j = 0; j < col; ++j) { uchar *m = canvas.ptr<uchar>(i); if (m[j] == 255) { mask.at<Vec3b>(i, j)[0] = static_cast<uchar>(color[0]); mask.at<Vec3b>(i, j)[1] = static_cast<uchar>(color[1]); mask.at<Vec3b>(i, j)[2] = static_cast<uchar>(color[2]); } } } } }
#include <iostream> #include <opencv2/opencv.hpp> #include <stdio.h> using namespace std; using namespace cv; void DrawConcentricCircle(cv::Mat mask, const cv::Point2i ¢er, int radius1, int radius2, const cv::Scalar &color, int thickness, int linetype); int main() { cv::Mat src = imread("test.jpg"); cv::Mat result = src.clone(); DrawConcentricCircle(result, cv::Point(result.cols / 2, result.rows / 2), 300, 500, cv::Scalar(255, 255, 0),-10, 16); imshow("original", src); imshow("result", result); waitKey(0); system("pause"); return 0; } // 绘制同心圆 void DrawConcentricCircle(cv::Mat mask, const cv::Point2i ¢er, int radius1,int radius2, const cv::Scalar &color, int thickness,int linetype) { // 创建画布 cv::Mat canvas = cv::Mat::zeros(mask.size(), CV_8UC1); // 计算内径和外径 int inradius = min(radius1, radius2); int outradius = max(radius1, radius2); // 分情况讨论 // 当thickness大于0时,绘制的是两个圆型线条组成的同心圆,不需填充 if (thickness > 0) { cv::circle(mask, center, outradius, color, thickness, linetype); cv::circle(mask, center, inradius, color, thickness, linetype); } // 当thickness小于0,一般为-1,绘制的是填充同心圆,内圆不能有填充色 else { cv::circle(canvas, center, outradius, cv::Scalar(255), -1, linetype); cv::circle(canvas, center, inradius, cv::Scalar(0), -1, linetype); int row = mask.rows; int col = mask.cols; for (int i = 0; i < row; ++i) { for (int j = 0; j < col; ++j) { uchar *m = canvas.ptr<uchar>(i); if (m[j] == 255) { mask.at<Vec3b>(i, j)[0] = static_cast<uchar>(color[0]); mask.at<Vec3b>(i, j)[1] = static_cast<uchar>(color[1]); mask.at<Vec3b>(i, j)[2] = static_cast<uchar>(color[2]); } } } } }
测试效果
图1 原图
图2 绘制同心圆
绘制同心圆就是两个圆组合,但又不完全是,因为要考虑填充的情况,同心圆填充后应该是两个圆之间的区域填充,而不是填充为一整个圆,如图3所示。
图3 填充效果