基于OpenCV實(shí)現(xiàn)圖像分割
本文實(shí)例為大家分享了基于OpenCV實(shí)現(xiàn)圖像分割的具體代碼,供大家參考,具體內(nèi)容如下
1、圖像閾值化
源代碼:
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include <iostream>
using namespace std;
using namespace cv;
int thresholds=50;
int model=2;
Mat image,srcimage;
void track(int ,void *)
{
Mat result;
threshold(srcimage,result,thresholds,255,CV_THRESH_BINARY);
//imshow("原圖",result);
if(model==0)
{
threshold(srcimage,result,thresholds,255,CV_THRESH_BINARY);
imshow("分割",result);
}
if(model==1)
{
threshold(srcimage,result,thresholds,255,THRESH_BINARY_INV);
imshow("分割",result);
}
if(model==2)
{
threshold(srcimage,result,thresholds,255,THRESH_TRUNC);
imshow("分割",result);
}
if(model==3)
{
threshold(srcimage,result,thresholds,255,THRESH_TOZERO);
imshow("分割",result);
}
if(model==4)
{
threshold(srcimage,result,thresholds,255,THRESH_TOZERO_INV);
imshow("分割",result);
}
}
int main()
{
image=imread("2.2.tif");
if(!image.data)
{
return 0;
}
cvtColor(image,srcimage,CV_BGR2GRAY);
namedWindow("分割",WINDOW_AUTOSIZE);
cv::createTrackbar("閾a值:","分割",&thresholds,255,track);
cv::createTrackbar("模式:","分割",&model,4,track);
track(thresholds,0);
track(model,0);
waitKey(0);
return 0;
}
實(shí)現(xiàn)結(jié)果:

2、閾值處理
//閾值處理
#include "opencv2/core/core.hpp"
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
using namespace cv;
using namespace std;
int main()
{
printf("鍵盤(pán)按鍵ESC--退出程序");
Mat g_srcImage = imread("1.tif",0);
if(!g_srcImage.data)
{
printf("讀取圖片失敗");
}
imshow("原始圖",g_srcImage);
//大津法閾值分割顯示
/*大津法,簡(jiǎn)稱(chēng)OTSU.它是按圖像的灰度特性,將圖像分成背景
和目標(biāo)2部分。背景和目標(biāo)之間的類(lèi)間方差越大,說(shuō)明構(gòu)成圖像
的2部分的差別越大,當(dāng)部分目標(biāo)錯(cuò)分為背景或部分背景錯(cuò)分為
目標(biāo)都會(huì)導(dǎo)致2部分差別變小。*/
Mat OtsuImage;
threshold(g_srcImage,OtsuImage,0,255,THRESH_OTSU);//0不起作用,可為任意閾值
imshow("OtsuImage",OtsuImage);
//自適應(yīng)分割并顯示
Mat AdaptImage;
//THRESH_BINARY_INV:參數(shù)二值化取反
adaptiveThreshold(g_srcImage,AdaptImage,255,0,THRESH_BINARY_INV,7,8);
imshow("AdaptImage",AdaptImage);
while(1)
{
int key;
key = waitKey(20);
if((char)key == 27)
{ break; }
}
}
效果圖:

3、拉普拉斯檢測(cè)
//Laplacian檢測(cè)
#include "opencv2/core/core.hpp"
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
using namespace cv;
using namespace std;
/*,在只關(guān)心邊緣的位置而不考慮其周?chē)南笏鼗叶炔钪禃r(shí)比較合適。
Laplace 算子對(duì)孤立象素的響應(yīng)要比對(duì)邊緣或線(xiàn)的響應(yīng)要更強(qiáng)烈,因此
只適用于無(wú)噪聲圖象。存在噪聲情況下,使用 Laplacian 算子檢測(cè)邊
緣之前需要先進(jìn)行低通濾波。*/
int main()
{
Mat src,src_gray,dst,abs_dst;
src = imread("1.jpg");
imshow("原始圖像",src);
//高斯濾波
GaussianBlur(src,src,Size(3,3),0,0,BORDER_DEFAULT);
//轉(zhuǎn)化為灰度圖,輸入只能為單通道
cvtColor(src,src_gray,CV_BGR2GRAY);
Laplacian(src_gray,dst,CV_16S,3,1,0,BORDER_DEFAULT);
convertScaleAbs(dst,abs_dst);
imshow("效果圖Laplace變換",abs_dst);
waitKey();
return 0;
}
效果圖:

4、canny算法的邊緣檢測(cè)
源代碼
#include "opencv2/core/core.hpp"
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
using namespace cv;
using namespace std;
/*如果某一像素位置的幅值超過(guò)高閾值,該像素被保留為邊緣像素。如果某
一像素位置的幅值小于低閾值,該像素被排除。如果某一像素位置的幅值在
兩個(gè)閾值之間,該像素僅僅在連接到一個(gè)高于高閾值的像素時(shí)被保留。 */
int main()
{
Mat picture2=imread("1.jpg");
Mat new_picture2;
Mat picture2_1=picture2.clone();
Mat gray_picture2 , edge , new_edge;
imshow("【原始圖】Canny邊緣檢測(cè)" , picture2);
Canny(picture2_1 , new_picture2 ,150 , 100 ,3 );
imshow("【效果圖】Canny邊緣檢測(cè)", new_picture2 );
Mat dstImage,grayImage;
//dstImage與srcImage同大小類(lèi)型
dstImage.create(picture2_1.size() , picture2_1.type());
cvtColor(picture2_1,gray_picture2,CV_BGR2GRAY);//轉(zhuǎn)化為灰度圖
blur(gray_picture2 , edge , Size(3,3));//用3x3的內(nèi)核降噪
Canny(edge,edge,3,9,3);
dstImage = Scalar::all(0);//將dst內(nèi)所有元素設(shè)置為0
//使用canny算子的邊緣圖edge作為掩碼,將原圖拷貝到dst中
picture2_1.copyTo(dstImage,edge);
imshow("效果圖Canny邊緣檢測(cè)2",dstImage);
waitKey();
}
效果圖:

5、圖像的分水嶺算法
源代碼:
#include "opencv2/core/core.hpp"
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include <iostream>
using namespace cv;
using namespace std;
#define WINDOW_NAME1 "顯示/操作窗口"
#define WINDOW_NAME2 "分水嶺算法效果圖"
Mat g_maskImage,g_srcImage;
Point prevPt(-1,-1);
static void ShowHelpText();
static void on_Mouse(int event,int x,int y,int flags,void*);
//輸出一些幫助信息
static void ShowHelpText()
{
printf("當(dāng)前使用的版本為:"CV_VERSION);
printf("\n");
printf("分水嶺算法---點(diǎn)中圖片進(jìn)行鼠標(biāo)或按鍵操作\n");
printf("請(qǐng)先用鼠標(biāo)在圖片窗口中標(biāo)記出大致的區(qū)域,\n然后再按鍵【1】或者【space】啟動(dòng)算法");
printf("\n按鍵操作說(shuō)明:\n"
"鍵盤(pán)按鍵【1】或者【space】--運(yùn)行的分水嶺分割算法\n"
"鍵盤(pán)按鍵【2】--回復(fù)原始圖片\n"
"鍵盤(pán)按鍵【ESC】--退出程序\n");
}
static void on_Mouse(int event,int x,int y,int flags,void*)
{
if(x<0||x>=g_srcImage.cols||y<0||y>=g_srcImage.rows)
return;
if(event == CV_EVENT_LBUTTONUP||!(flags & CV_EVENT_FLAG_LBUTTON))
prevPt = Point(-1,-1);
else if(event == CV_EVENT_LBUTTONDOWN)
prevPt= Point(x,y);
else if(event == CV_EVENT_MOUSEMOVE && (flags & CV_EVENT_FLAG_LBUTTON))
{
Point pt(x,y);
if(prevPt.x<0)
prevPt = pt;
line(g_maskImage,prevPt,pt,Scalar::all(255),5,8,0);
line(g_srcImage,prevPt,pt,Scalar::all(255),5,8,0);
prevPt = pt;
imshow(WINDOW_NAME1,g_srcImage);
}
}
int main(int argc,char** argv)
{
system("color A5");
ShowHelpText();
g_srcImage = imread("1.jpg",1);
imshow(WINDOW_NAME1,g_srcImage);
Mat srcImage,grayImage;
g_srcImage.copyTo(srcImage);
cvtColor(g_srcImage,g_maskImage,CV_BGR2GRAY);
cvtColor(g_maskImage,grayImage,CV_GRAY2BGR);//灰度圖轉(zhuǎn)BGR3通道,但每通道的值都是原先單通道的值,所以也是顯示灰色的
g_maskImage = Scalar::all(0);//黑
setMouseCallback(WINDOW_NAME1,on_Mouse,0);
while(1)
{
int c = waitKey(0);
if((char)c == 27)
break;
if((char)c == '2')
{
g_maskImage = Scalar::all(0);//黑
srcImage.copyTo(g_srcImage);
imshow("image",g_srcImage);
}
if((char)c == '1'||(char)c == ' ')
{
int i,j,compCount = 0;
vector<vector<Point>> contours;//定義輪廓
vector<Vec4i> hierarchy;//定義輪廓的層次
findContours(g_maskImage,contours,hierarchy,RETR_CCOMP,CHAIN_APPROX_SIMPLE);
if(contours.empty())
continue;
Mat maskImage(g_maskImage.size(),CV_32S);
maskImage = Scalar::all(0);
for(int index = 0;index >= 0;index = hierarchy[index][0],compCount++)
drawContours(maskImage,contours,index,Scalar::all(compCount+1),-1,8,hierarchy,INT_MAX);
if(compCount == 0)
continue;
vector<Vec3b> colorTab;
for(i=0;i<compCount;i++)
{
int b = theRNG().uniform(0,255);
int g = theRNG().uniform(0,255);
int r = theRNG().uniform(0,255);
colorTab.push_back(Vec3b((uchar)b,(uchar)g,(uchar)r));
}
//計(jì)算處理時(shí)間并輸出到窗口中
double dTime = (double)getTickCount();
watershed(srcImage,maskImage);
dTime = (double)getTickCount()-dTime;
printf("\t處理時(shí)間=%gms\n",dTime*1000./getTickFrequency());
//雙層循環(huán),將分水嶺圖像遍歷存入watershedImage中
Mat watershedImage(maskImage.size(),CV_8UC3);
for(i=0;i<maskImage.rows;i++)
for(j=0;j<maskImage.cols;j++)
{
int index = maskImage.at<int>(i,j);
if(index == -1)
watershedImage.at<Vec3b>(i,j) = Vec3b(255,255,255);
else if(index<=0||index>compCount)
watershedImage.at<Vec3b>(i,j) = Vec3b(0,0,0);
else
watershedImage.at<Vec3b>(i,j) = colorTab[index-1];
}
//混合灰度圖和分水嶺效果圖并顯示最終的窗口
watershedImage = watershedImage*0.5+grayImage*0.5;
imshow(WINDOW_NAME2,watershedImage);
}
}
waitKey();
return 0;
}
效果圖:

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
C/C++ assert()函數(shù)用法案例總結(jié)
這篇文章主要介紹了C/C++ assert()函數(shù)用法案例總結(jié),本篇文章通過(guò)簡(jiǎn)要的案例,講解了該項(xiàng)技術(shù)的了解與使用,以下就是詳細(xì)內(nèi)容,需要的朋友可以參考下2021-09-09
解析C++中四種強(qiáng)制類(lèi)型轉(zhuǎn)換的區(qū)別詳解
本篇文章是對(duì)C++中四種強(qiáng)制類(lèi)型轉(zhuǎn)換的區(qū)別進(jìn)行了詳細(xì)的分析介紹,需要的朋友參考下2013-05-05
C++實(shí)現(xiàn)查找中位數(shù)的O(N)算法和Kmin算法
這篇文章主要介紹了C++實(shí)現(xiàn)查找中位數(shù)的O(N)算法和Kmin算法,對(duì)于C++程序算法設(shè)計(jì)有一定的借鑒價(jià)值,需要的朋友可以參考下2014-09-09
C++修煉之構(gòu)造函數(shù)與析構(gòu)函數(shù)
本章節(jié)我們將學(xué)習(xí)類(lèi)的6個(gè)默認(rèn)成員函數(shù)中的構(gòu)造函數(shù)與析構(gòu)函數(shù),并對(duì)比C語(yǔ)言階段的內(nèi)容來(lái)學(xué)習(xí)它們的各自的特性,感興趣的同學(xué)可以參考閱讀2023-03-03
c語(yǔ)言實(shí)現(xiàn)找最大值最小值位置查找
這篇文章主要介紹了c語(yǔ)言實(shí)現(xiàn)找最大值最小值位置查找,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2021-02-02
C語(yǔ)言結(jié)構(gòu)體中內(nèi)存對(duì)齊的問(wèn)題理解
內(nèi)存對(duì)齊”應(yīng)該是編譯器的“管轄范圍”。編譯器為程序中的每個(gè)“數(shù)據(jù)單元”安排在適當(dāng)?shù)奈恢蒙?。但是C語(yǔ)言的一個(gè)特點(diǎn)就是太靈活,太強(qiáng)大,它允許你干預(yù)“內(nèi)存對(duì)齊”。如果你想了解更加底層的秘密,“內(nèi)存對(duì)齊”對(duì)你就不應(yīng)該再模糊了2022-02-02

