OpenCV 內建了 cvPyrSegmentation,用金字塔方法完成圖像分割。參數看起來抽象,理解兩個門檻的分工之後就清楚多了。
void cvPyrSegmentation(IplImage* src, IplImage* dst,
CvMemStorage* storage, CvSeq** comp,
int level, double threshold1, double threshold2);
金字塔建立到 level 指定的層數為止。若 p(c(a), c(b)) < threshold1,則第 i 層的像素 a 與它在上一層的父像素 b 之間建立連接,這些互連的像素構成「連接部件」。
接著把連接部件聚成簇:若 p(c(A), c(B)) < threshold2,則分割 A 與 B 屬於同一簇。最終我們拿到的分割結果,就是這些簇。
距離函數的定義依通道數而定。單通道時:
p(c1, c2) = |c1 - c2|
三通道(紅綠藍)時:
p(c1, c2) = 0.3·(c1r - c2r) + 0.59·(c1g - c2g) + 0.11·(c1b - c2b)
也就是說,彩色圖像的比較是加權到亮度上的。每個簇可以包含多個連接部件,輸入與輸出的 src、dst 都必須是 8 位元、單通道或三通道,且尺寸相同。
網路上常有人搞混這兩個參數,其實對照上面的說明就很清楚:
threshold1 決定像素層級的連通性——在 a、b 等像素之間找出連通域,也就是連接部件 A、B。threshold2 決定部件層級的歸屬——判斷兩個連通部件是否屬於同一簇,簇就是最終的分割結果。因此 threshold1 控制「細節黏合程度」,threshold2 控制「區域合併程度」。實務上 threshold1 通常給得較大(例如 255),threshold2 給得較小(例如 30),先保住邊緣再合併。
void ON_SEGMENT(int a)
{
cvPyrSegmentation(images0, images1, storage, &comp,
level, threshold1 + 1, threshold2 + 1);
cvShowImage("Segmentation", images1);
}
void CCVMFCView::OnPyrSegmentation()
{
images[0] = cvCloneImage(workImg);
cvFlip(images[0]);
cvNamedWindow("Segmentation", 1);
storage = cvCreateMemStorage(block_size);
// 尺寸需對 2^level 對齊,否則金字塔會出錯
images[0]->width &= -(1 << level);
images[0]->height &= -(1 << level);
images0 = cvCloneImage(images[0]);
images1 = cvCloneImage(images[0]);
// 對彩色圖像進行分割
l = 1;
threshold1 = 255;
threshold2 = 30;
sthreshold1 = cvCreateTrackbar("Threshold1", "Segmentation",
&threshold1, 255, ON_SEGMENT);
sthreshold2 = cvCreateTrackbar("Threshold2", "Segmentation",
&threshold2, 255, ON_SEGMENT);
ON_SEGMENT(1);
cvWaitKey(0);
cvDestroyWindow("Segmentation");
cvFlip(images1);
images1->width = workImg->width;
images1->height = workImg->height;
cvReleaseMemStorage(&storage);
cvReleaseImage(&images[0]);
cvReleaseImage(&images0);
m_dibFlag = imageReplace(images1, &workImg);
m_ImageType = 1;
Invalidate();
}
特別注意那兩行位元運算:金字塔每下降一層尺寸減半,因此輸入尺寸必須能被 2 的 level 次方整除,用 &= -(1 << level) 把尾碼直接抹掉是最省事的做法,處理完再還原成原始尺寸。