一、實驗目的
? 培養利用圖像處理技術解決實際問題的能力。
? 培養利用圖像處理技術綜合設計實現的能力。
? 掌握在Python環境下解決實際問題的能力。
? 熟練掌握使用cv2庫對圖像進行處理
? 熟練掌握使用區域生長法提取圖片中感興趣的區域
二、實驗內容
本次實驗內容為:綜合應用-區域生長算法提取感興趣區域
通過手動設置初始種子點,利用區域生長算法得到腦部區域,這在醫學領域可以輔助醫生進行醫療診斷。
案例描述:
區域生長算法常用于提取圖像中的感興趣目標區域,為后續圖像分析做準備。
本案例采用區域生長算法提取醫學圖像中的人的腦部區域。
案例數據:數據為1張人腦圖片brain.jpg。
? 案例步驟參考:
(1)導入包;
(2)讀入圖片srclmg(單通道灰度圖);
(3)構造一個跟原圖等大小的零值標記矩陣a;
(4)手動選取初始種子和生長閾值;
(5)運行區域生長算法,得到前景目標標記矩陣a;
(6)由前景目標標記矩陣a跟原圖點乘得到感興趣區域并顯示結果。
三、完整實驗程序、結果與分析
代碼:
import cv2
import numpy as np
import matplotlib.pyplot as plt
from collections import deque# 讀取圖像為灰度圖
srclmg = cv2.imread("D:/tuxiang/brain.jpg", cv2.IMREAD_GRAYSCALE)
if srclmg is None:print("Error: Image not found.")exit()# 顯示圖像并選擇種子點(使用阻塞模式)
plt.imshow(srclmg, cmap='gray')
plt.title('Click on the seed point and close window to continue')
seed_points = plt.ginput(1, timeout=0) # 必須點擊1次
plt.close()# 驗證是否獲取到有效種子點
if len(seed_points) < 1:print("Error: No seed point selected!")exit()# 轉換坐標并初始化參數
x_seed = int(round(seed_points[0][0]))
y_seed = int(round(seed_points[0][1]))
seed = (y_seed, x_seed) # OpenCV坐標格式 (行, 列)
threshold = 10 # 明確定義閾值參數 <-- 修正關鍵點# 創建標記矩陣
h, w = srclmg.shape
a = np.zeros_like(srclmg, dtype=np.uint8)# 初始化隊列并添加種子點
queue = deque([seed])
a[seed] = 255# 定義8鄰域偏移量
neighbors = [(-1, -1), (-1, 0), (-1, 1),(0, -1), (0, 1),(1, -1), (1, 0), (1, 1)]# 區域生長算法
while queue:i, j = queue.popleft()for di, dj in neighbors:ni, nj = i + di, j + djif 0 <= ni < h and 0 <= nj < w and a[ni, nj] == 0:# 使用正確的變量名thresholdif abs(int(srclmg[ni, nj]) - int(srclmg[i, j])) <= threshold:a[ni, nj] = 255queue.append((ni, nj))# 提取感興趣區域并顯示結果
result = cv2.bitwise_and(srclmg, srclmg, mask=a)plt.figure(figsize=(12, 6))
plt.subplot(1, 2, 1)
plt.imshow(srclmg, cmap='gray')
plt.title('Original Image')plt.subplot(1, 2, 2)
plt.imshow(result, cmap='gray')
plt.title('Segmented Brain Region')
plt.show()
結果:
四、本次作業中出現的問題及心得
通過本次實驗,我深刻認識到算法實現中細節把控與參數調優的重要性。