OpenCV 是一個跨平臺的計算機(jī)視覺庫, 支持多語言, 功能強(qiáng)大. 今天小白就帶大家一起攜手走進(jìn) OpenCV 的世界.
分水嶺算法 (Watershed Algorithm) 是一種圖像區(qū)域分割算法. 在分割的過程中, 分水嶺算法會把跟臨近像素間的相似性作為重要的根據(jù).
距離變換 (Distance Transform)通過計算圖像中非零像素點到最近像素的距離, 實現(xiàn)了像素與圖像區(qū)域的距離變換.
連通域 (Connected Components) 指的是圖像中具有相同像素且位置相鄰的前景像素點組成的圖像區(qū)域.
算法會根據(jù) markers 傳入的輪廓作為種子, 對圖像上其他的像素點根據(jù)分水嶺算法規(guī)則進(jìn)行判斷, 并對每個像素點的區(qū)域歸屬進(jìn)行劃定. 區(qū)域之間的分界處的值被賦值為 -1.
import numpy as np
import cv2
from matplotlib import pyplot as plt
def watershed(image):
"""分水嶺算法"""
# 卷積核
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (3, 3))
# 均值遷移濾波
blur = cv2.pyrMeanShiftFiltering(image, 10, 100)
# 轉(zhuǎn)換成灰度圖
image_gray = cv2.cvtColor(blur, cv2.COLOR_BGR2GRAY)
# 二值化
ret1, thresh1 = cv2.threshold(image_gray, 0, 255, cv2.THRESH_OTSU)
# 開運算
open = cv2.morphologyEx(thresh1, cv2.MORPH_OPEN, kernel, iterations=2)
# 膨脹
dilate = cv2.dilate(open, kernel, iterations=3)
# 距離變換
dist = cv2.distanceTransform(dilate, cv2.DIST_L2, 3)
dist = cv2.normalize(dist, 0, 1.0, cv2.NORM_MINMAX)
print(dist.max())
# 二值化
ret2, thresh2 = cv2.threshold(dist, dist.max() * 0.6, 255, cv2.THRESH_BINARY)
thresh2 = np.uint8(thresh2)
# 分水嶺計算
unknown = cv2.subtract(dilate, thresh2)
ret3, component = cv2.connectedComponents(thresh2)
print(ret3)
# 分水嶺計算
markers = component + 1
markers[unknown == 255] = 0
result = cv2.watershed(image, markers=markers)
image[result == -1] = [0, 0, 255]
# 圖片展示
image_show((image, blur, image_gray, thresh1, open, dilate), (dist, thresh2, unknown, component, markers, image))
return image
def image_show(graph1, graph2):
"""繪制圖片"""
# 圖像1
original, blur, gray, binary1, open, dilate = graph1
# 圖像2
dist, binary2, unknown, component, markers, result = graph2
f, ax = plt.subplots(3, 2, figsize=(12, 16))
# 繪制子圖
ax[0, 0].imshow(cv2.cvtColor(original, cv2.COLOR_BGR2RGB))
ax[0, 1].imshow(cv2.cvtColor(blur, cv2.COLOR_BGR2RGB))
ax[1, 0].imshow(gray, "gray")
ax[1, 1].imshow(binary1, "gray")
ax[2, 0].imshow(open, "gray")
ax[2, 1].imshow(dilate, "gray")
# 標(biāo)題
ax[0, 0].set_title("original")
ax[0, 1].set_title("image blur")
ax[1, 0].set_title("image gray")
ax[1, 1].set_title("image binary1")
ax[2, 0].set_title("image open")
ax[2, 1].set_title("image dilate")
plt.show()
f, ax = plt.subplots(3, 2, figsize=(12, 16))
# 繪制子圖
ax[0, 0].imshow(dist, "gray")
ax[0, 1].imshow(binary2, "gray")
ax[1, 0].imshow(unknown, "gray")
ax[1, 1].imshow(component, "gray")
ax[2, 0].imshow(markers, "gray")
ax[2, 1].imshow(cv2.cvtColor(result, cv2.COLOR_BGR2RGB))
# 標(biāo)題
ax[0, 0].set_title("image distance")
ax[0, 1].set_title("image binary2")
ax[1, 0].set_title("image unknown")
ax[1, 1].set_title("image component")
ax[2, 0].set_title("image markers")
ax[2, 1].set_title("result")
plt.show()
if __name__ == "__main__":
# 讀取圖片
image = cv2.imread("coin.jpg")
# 分水嶺算法
result = watershed(image)
# 保存結(jié)果
cv2.imwrite("result.jpg", result)
到此這篇關(guān)于OpenCV半小時掌握基本操作之分水嶺算法的文章就介紹到這了,更多相關(guān)OpenCV分水嶺算法內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!