我正在处理如图1所示的图像,它由一个点数组组成,需要转换为图2。
图1原图
图2想要的图
为了完成转换,我首先检测每个点的边缘
,然后进行膨胀
。选择合适的参数后,结果令人满意,如图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;
}
最佳答案
1- Find all the contours在你的形象中。
2- 使用 moments找到他们的质心。示例:
/// 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 ); }
3- 创建零(黑色)图像并在其上写下所有中心点。
4- 请注意,您将有额外的一两个点来自边界轮廓。也许您可以根据 contour areas 应用一些预过滤,因为边界是一个面积很大的大连接轮廓。
关于c++ - opencv - 将对象缩小到像素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17463923/