影象分割的主要函式總結
影象分割可以理解為:提取影象的感興趣區域,可以分為兩部分:
第一步:獲取mask區域:defgenerateMask(img):
def generateMask(img): blured_img = getBlurImage(img) #①對影象進行高斯平滑濾波 filtered_img = getFilterImage(blured_img) #②對影象進行通用的2D濾波 opening_img = getOpeningImage(filtered_img) #③對影象進行開運算 closing_img = getClosingImage(opening_img) #④對影象進行閉運算 canny_edge_img = autoCannyEdgeDetection(closing_img) #⑤使用cv2.canny進行邊緣檢測 contours, contour_img = getContourImage(canny_edge_img) #⑥使用cv2.findContours尋找邊緣輪廓 binary_line_img = drawLines(contour_img, contours) # ⑦繪製最小輪廓 dilation_img = getDilationImage(binary_line_img) #⑧對最小輪廓影象進行膨脹處理 return dilation_img
附函式:
①:對影象進行高斯平滑濾波
def getBlurImage(img):
blur = cv2.GaussianBlur(img, (5, 5), 0)
return blur
②:對影象進行通用的2D濾波
def getFilterImage(img):
kernel = np.ones((5, 5), np.float32) / 25
filtered = cv2.filter2D(img, -1, kernel)
return filtered
③:對影象進行開運算
def getOpeningImage(img): kernel = np.ones((35,35),np.uint8) opening = cv2.morphologyEx(img, cv2.MORPH_OPEN, kernel) return opening
④:對影象進行閉運算
def getClosingImage(img):
kernel = np.ones((35,35),np.uint8)
closing = cv2.morphologyEx(img, cv2.MORPH_CLOSE, kernel)
return closing
⑤:使用cv2.canny進行邊緣檢測
def autoCannyEdgeDetection(img, sigma = 0.7): v = np.median(img) lower = int(max(0, (1.0 - sigma) * v)) upper = int(min(255, (1.0 + sigma) * v)) edged = cv2.Canny(img, 245, 255) return edged
⑥:使用cv2.findContours尋找邊緣輪廓
def getContourImage(img):
im2, contours, hierarchy = cv2.findContours(img,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
mask = np.zeros(img.shape, np.uint8)
cv2.drawContours(mask, contours, -1, (255,255,255), 5)
return contours, mask
⑦:繪製最小輪廓
def drawLines(img, contours):
cnt = contours[0]
(x,y),radius = cv2.minEnclosingCircle(cnt)
center = (int(x),int(y))
mask = np.zeros(img.shape, np.uint8)
cnt_points = []
for cnt in contours:
for pts in cnt:
cnt_points.append(pts[0])
cnt_points = np.array(cnt_points)
for i in range(len(cnt_points)):
cv2.line(mask,center,(cnt_points[i,0], cnt_points[i,1]),(255,255,255),5)
return mask
⑧:對最小輪廓影象進行膨脹處理
def getDilationImage(img):
kernel = np.ones((50,50),np.uint8)
dilation = cv2.dilate(img, kernel, iterations = 1)
return dilation
第二步:獲取ROI區域:defextractRegion(img, mask):
其中,第二步的操作就是對img與mask進行的影象與運算。
def extractRegion(img, mask):
processed_img = cv2.bitwise_and(img, img, mask = mask)
return processed_img
補充:影象算數與邏輯運算
1、add---影象矩陣相加:def add(src1, src2, dst=None, mask=None, dtype=None) #影象的畫素值增大
PS:src1:影象矩陣1,src2:影象矩陣2,dst:預設選項,mask:預設選項,dtype:預設選項。
2、subtract---影象矩陣相減:defsubtract(src1, src2, dst=None, mask=None, dtype=None)#影象的畫素值減小
3、bitwise_and—影象與運算:defbitwise_and(src1, src2, dst=None, mask=None)#求兩影象的交集
4、bitwise_or—影象或運算:defbitwise_or(src1, src2, dst=None, mask=None) #求兩影象的並集
5、bitwise_xor—影象異或運算:defbitwise_xor(src1, src2, dst=None, mask=None) #求兩影象的並集-交集
6、bitwise_not—影象非運算:defbitwise_not(src1, src2, dst=None, mask=None) #求影象的反(畫素值的對調:意思就是原先的0換為1,原先的1換為0)