欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

OpenCV之圆形切割和矩形切割的实现

程序员文章站 2022-06-24 20:26:00
圆分割 今天继续昨天的对角分割,想到了分割出来一个圆形区域。于是就很简单的实现了一下。思想还是利用数学公式判断点是否在圆内还是圆外。 #include #include...

圆分割

今天继续昨天的对角分割,想到了分割出来一个圆形区域。于是就很简单的实现了一下。思想还是利用数学公式判断点是否在圆内还是圆外。

#include
#include
#include
#include

using namespace cv;
using namespace std;

int main(int argc,char* argv[])
{
    Mat image = imread("1.jpg");
    Mat image1(image.rows, image.cols, image.type(), Scalar(180, 120, 50));
    Mat image2(image.rows, image.cols, image.type(), Scalar(180, 120, 50));
    Point center(image.cols/2,image.rows/2);
    int radius = 200;

    circle(image, center, radius, Scalar(0, 200, 100), 2, 8, 0);

    for (int x = 0; x < image.cols; x++)
    {
        for (int y = 0; y < image.rows; y++)
        {
            int temp = ((x - center.x) * (x - center.x) + (y - center.y) *(y - center.y));
            if (temp < (radius * radius)) // 圆内
            {
                image1.at(Point(x, y))[0] = image.at(Point(x, y))[0];
                image1.at(Point(x, y))[1] = image.at(Point(x, y))[1];
                image1.at(Point(x, y))[2] = image.at(Point(x, y))[2];
            }
            else //圆外
            {
                image2.at(Point(x, y))[0] = image.at(Point(x, y))[0];
                image2.at(Point(x, y))[1] = image.at(Point(x, y))[1];
                image2.at(Point(x, y))[2] = image.at(Point(x, y))[2];
            }
        }
    }

    imshow("image1", image1);
    imshow("image2", image2);

    while (uchar(waitKey() != 'q')) {}
    return 0;

}

注意Point center(image.rows/2,image.cols/2)和Point center(image.cols/2,image.rows/2)的区别。后者才是中心点。

矩形分割

#include
#include
#include
#include

using namespace cv;
using namespace std;

int main(int argc,char* argv[])
{
    Mat image = imread("miao.jpg");
    Mat image1(image.rows, image.cols, image.type(), Scalar(180, 120, 50));
    Mat image2(image.rows, image.cols, image.type(), Scalar(180, 120, 50));

    Point point1(140,40);
    Point point2(470, 340);
    for (int x = 0; x < image.cols; x++)
    {
        for (int y = 0; y < image.rows; y++)
        {

            if (point1.x <= x && x<=point2.x && point1.y<=y && y<=point2.y)
            {
                image1.at(Point(x, y))[0] = image.at(Point(x, y))[0];
                image1.at(Point(x, y))[1] = image.at(Point(x, y))[1];
                image1.at(Point(x, y))[2] = image.at(Point(x, y))[2];
            }
            else
            {
                image2.at(Point(x, y))[0] = image.at(Point(x, y))[0];
                image2.at(Point(x, y))[1] = image.at(Point(x, y))[1];
                image2.at(Point(x, y))[2] = image.at(Point(x, y))[2];
            }
        }
    }
    namedWindow("image1", 0);
    namedWindow("image2", 0);
    imshow("image", image);
    imshow("image1", image1);
    imshow("image2", image2);

    while (uchar(waitKey() != 'q')) {}
    return 0;

}