opencv - 将对象缩小为像素

Wan*_*ong 5 c++ opencv image-processing computer-vision

我正在处理如图1所示的图像,它由一系列点组成,需要转换成图2.

图1原始图像

图1原始图像
图2想要的图像

图2想要的图像

为了完成转换,首先我检测edge每个点,然后进行操作dilation.选择合适的参数后,结果令人满意,如图3所示.

图3扩张后的图像

图3扩张后的图像

我在MATLAB之前处理过相同的图像.当将对象(图3中)缩小为像素时,功能bwmorph(Img,'shrink',Inf)起作用,结果正好是图2所示的结果.那么如何在opencv中获得相同的想要的图像?似乎没有类似的shrink功能.

这是我找到边缘和扩张操作的代码:

#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/highgui/highgui.hpp"
#include <stdlib.h>
#include <stdio.h>
#include <cv.h>
#include <highgui.h>
using namespace cv;

// Global variables
Mat src, dilation_dst;
int dilation_size = 2;

int main(int argc, char *argv[])
{
    IplImage* img = cvLoadImage("c:\\001a.bmp", 0);                 // 001a.bmp is Fig.1                              

    // Perform canny edge detection
    cvCanny(img, img, 33, 100, 3);

    // IplImage to Mat
    Mat imgMat(img);
    src = img;

    // Create windows
    namedWindow("Dilation Demo", CV_WINDOW_AUTOSIZE);

    Mat element = getStructuringElement(2,                          // dilation_type = MORPH_ELLIPSE
                  Size(2*dilation_size + 1, 2*dilation_size + 1),
                  Point(dilation_size, dilation_size));

    // Apply the dilation operation
    dilate(src, dilation_dst, element);
    imwrite("c:\\001a_dilate.bmp", dilation_dst);
    imshow("Dilation Demo", dilation_dst);

    waitKey(0);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

bac*_*aci 4

1-找到图像中的所有轮廓。

2-利用时刻找到他们的重心。例子:

/// Get moments
vector<Moments> mu(contours.size() );
for( int i = 0; i < contours.size(); i++ )
{ mu[i] = moments( contours[i], false ); }

/// Get the mass centers:
vector<Point2f> mc( contours.size() );
for( int i = 0; i < contours.size(); i++ )
{ mc[i] = Point2f( mu[i].m10/mu[i].m00 , mu[i].m01/mu[i].m00 ); }
Run Code Online (Sandbox Code Playgroud)

3-创建零(黑色)图像并在其上写下所有中心点。

4-请注意,您将有来自边界轮廓的额外一两个点。也许您可以根据轮廓区域应用一些预过滤,因为边界是一个具有大面积的大连接轮廓。