您的位置:首页 > 运维架构

基于opencv检测斑马鱼重心

2015-07-01 17:37 246 查看
// stdafx.h : 标准系统包含文件的包含文件,

// 或是经常使用但不常更改的

// 特定于项目的包含文件

//

#pragma once

#include "targetver.h"

#include <stdio.h>

#include <tchar.h>

// TODO: 在此处引用程序需要的其他头文件

#include<iostream>

#include<string>

#include<opencv2/core/core.hpp>

#include<opencv2/imgproc/imgproc.hpp>

#include<opencv2/highgui/highgui.hpp>

using namespace std;

using namespace cv;

// zebrafish.cpp : 定义控制台应用程序的入口点。

//

#include "stdafx.h"

int _tmain(int argc, _TCHAR* argv[])

{

Mat img1,img2,img3,img4;

img1=imread("E:\\visual studio 2010\\zebrafish\\zebrafish.jpg");//读入RGB图像

imshow("zebrafish_rgb",img1);//显示RGB图像

cvtColor(img1,img2,7);//RGB to GRAY

imshow("zebrafish_gray",img2);//显示灰度图像

threshold(img2,img3,157,255,0);//灰度图像二值化

imshow("zebrafish_bin",img3);//显示二值图像

dilate(img3,img4, Mat(3,3,CV_8U), Point(-1,-1), 1);//做膨胀处理

imshow("zebrafish_dilate",img4);

double area = 0;
//面积

int max = 0;
//最大面积

int count = 0;
//面积符合要求的区域计数

vector<vector<Point> > contours;

vector<Vec4i> hierarchy;

Mat img5=255-img4;

imshow("zebrafish_reve",img5);//图像反转

// 寻找轮廓

findContours( img5, contours, hierarchy, CV_RETR_TREE, CV_CHAIN_APPROX_SIMPLE, Point(0, 0) );

// 绘出轮廓

Mat img6= Mat::zeros( img5.size(), CV_8UC1 );

for( int i = 0; i<contours.size(); i++ )

{

area = contourArea(contours[i]);//依次求每个区域的面积

if (area>max)

{

max=area;

count=i;

}

}

drawContours( img6, contours, count,255,-1,8);

//imshow( "Contours", img6 );

int s=img6.at<unsigned char>(0,0);

long x=0;

long y=0;

int num=0;

//计算连通域的重心

int w=img6.cols;

int h=img6.rows;

int m,n;

for(m=0;m<h;m++)

{

for(n=0;n<w;n++)

{

if(img6.at<unsigned char>(m,n)==255)

{

x=x+m;

y=y+n;

num=num+1;

}

}

}

x=x/num;

y=y/num;

img6.row(x)=0;

img6.col(y)=0;

//在img6上绘出坐标点

Point point=Point(y,x);

char st[4];

int arr[2];

arr[0]=y;

arr[1]=x;

sprintf(st,"(%d,%d)",arr[0],arr[1]);

//String str(st);

putText(img6,st,point,1,1.0,1,1,8,false);

imshow( "Contours", img6 );

waitKey(0);

return 0;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: