opencv 分水嶺演算法

2021-06-20 08:23:15 字數 2370 閱讀 5130

分水嶺演算法是一種簡單的影象分割演算法,具體是人為規定兩點(以兩點為例),然後把這兩點看做低谷,向裡面注水,不停地蔓延,直到兩點形成的湖交界。

opencv自帶了這個程式。摘抄如下,其中我做了一些修改。

**:

//本程式的目的是測試分水嶺演算法

#include #include #include #include using namespace cv;

using namespace std;

mat marker_mask;

mat markers;

mat img0, img, img_gray, wshed;

point prev_pt(-1,-1);

mat nowhite(mat seg)

} }//右補左

for (int i = seg.rows-1; i> -1; i--)

}} //上補下

for (int i = 1; i< seg.rows; i++)

}} //下補上

for (int i = seg.rows-2; i> -1; i--)

}} return seg_result;

}void onmouse( int event, int x, int y, int flags, void* )

if( event == cv_event_rbuttonup || !(flags & cv_event_flag_rbutton) )

prev_pt = point(-1,-1);

else if( event == cv_event_rbuttondown )

prev_pt = point(x,y);

else if( event == cv_event_mousemove && (flags & cv_event_flag_rbutton) ) }

int main( int argc, char** argv )

cout << "hot keys: \n"

"\tesc - quit the program\n"

"\tr - restore the original image\n"

"\tw or space - run watershed algorithm\n"

"\t\t(before running it, roughly mark the areas on the image)\n"

"\t (before that, roughly outline several markers on the image)\n";

namedwindow( "image", 1 );

img0.copyto(img);

cvtcolor(img, marker_mask, cv_bgr2gray);

cvtcolor(marker_mask, img_gray, cv_gray2bgr);

marker_mask = scalar::all(0);

imshow( "image", img );

setmousecallback( "image", onmouse, 0 );

for(;;)

if( (char)c == 'w' || (char)c == ' ' )

for( i = 0; i < marker_mask.rows; i++ )

for( j = 0; j < marker_mask.cols; j++ )

}//double t = (double)gettickcount();

watershed( img0, markers );

//t = (double)gettickcount() - t;

//printf( "execution time = %gms\n", t*1000./gettickfrequency() );

wshed = mat(markers.size(), cv_8uc3);

// paint the watershed image

for( i = 0; i < markers.rows; i++ )

for( j = 0; j < markers.cols; j++ )

wshed = nowhite(wshed);

imshow( "watershed transform", wshed );

mat wshed_show = wshed*0.5 + img_gray*0.5;

imshow("show", wshed_show);

imwrite((outfolder+name+"_result.png").data(), wshed);

} }return 0;

}

opencv本來的版本會在交界處有一條白線,我修改的去掉了。

opencv實現分水嶺演算法

分水嶺演算法原理 iplimage marker mask 0 iplimage markers 0 iplimage img0 0,img 0,img gray 0,wshed 0 iplimage img gray 0,wshed 0 cvpoint prev pt void on mouse ...

OpenCV的分水嶺演算法

本文使用python實現 import cv2 as cv import numpy as np def watershed demo src print src.shape blurred cv.pyrmeanshiftfiltering src,10,100 去雜訊 gray cv.cvtcol...

OpenCV之分水嶺演算法

在許多實際的應用中,我們需要分割影象,但是無法從背景影象中獲得有用資訊。但是分水嶺演算法在這方面往往非常有效,它可以將影象中的邊緣轉化為 山脈 將均勻區域轉化為 山谷 這樣有助於分割目標。分水嶺演算法是一種記憶拓撲理論的數學形態學的分割方法,其基本思想是把影象看作測地學上的拓撲地貌,影象中每點畫素的...