Python 影像處理膨脹腐蝕 getStructuringElement、cv2.dilate、cv2.erode

說明

這邊當作一個小筆記,參考別人的程式中影像處理的幾個常見應用,去除影像中的躁點常常看見別人使用膨脹和腐蝕的技巧,在python 應用 opencv 的套件,以下針對我在程式裡遇到的 幾個 function 簡單說明。

操作流程

Code

def remove_text(img):
    origin = img.copy()
    cv2.namedWindow('result', cv2.WINDOW_NORMAL)
    cv2.resizeWindow("result", 640, 480)
    cv2.imshow("result", origin)
    # 按下任意鍵則關閉所有視窗
    cv2.waitKey(0)
    cv2.destroyAllWindows()

    dilated = cv2.dilate(img, cv2.getStructuringElement(cv2.MORPH_RECT, (31,31))) # 膨脹白色範圍變大




    contours, hierarchy = cv2.findContours(dilated, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) # 找邊緣

    text_cnts = []
    for i in range(len(contours)):
        mask = np.zeros_like(origin)
        cv2.drawContours(mask, contours, i, 255, -1)



        (y, x) = np.where(mask == 255)#有被 mask 標記起來的都列進去 y  x

        (topy, topx) = (np.min(y), np.min(x))      #把有 mask 為白色的找出最大最小,代表四個點
        (bottomy, bottomx) = (np.max(y), np.max(x))
        crop = origin[topy:bottomy + 1, topx:bottomx + 1]
        crop = cv2.erode(crop, cv2.getStructuringElement(cv2.MORPH_RECT, (31, 31)))

        if sum(crop.ravel()) == 0:
            text_cnts.append(i)

    for i in text_cnts:
        k=cv2.drawContours(origin, contours, i, (100,100
                                                 , 0), -1)

        # 顯示圖片
        cv2.namedWindow('k', cv2.WINDOW_NORMAL)
        cv2.resizeWindow("k", 640, 480)
        cv2.imshow("k", k)
        # 按下任意鍵則關閉所有視窗
        cv2.waitKey(0)
        cv2.destroyAllWindows()

    return k

說明

參考

關鍵字

  • Python 形態學
  • Python 閉運算
  • Python 膨脹腐蝕

留言