我正在處理數字影像。每個影像都包含一個數字和一些不需要的輪廓。

這種噪聲或輪廓可以是線條或小點的形式。我的任務是去除這些輪廓。所以我決定使用以下演算法
查找所有輪廓
按面積降序對等高線進行排序
遍歷從索引 2 到最后的輪廓
創建一個 boundingRect 并用 255 填充影像的該部分
cv2.findContours(image, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) contours = sorted(contours, key = cv2.contourArea, reverse = True) for c in contours[2:]: (x, y, w, h) = cv2.boundingRect(c) image[y:y h, x:x w] = 255
現在的問題是,如果第一個影像 boundingRect 回傳 (14,14,150,150) ,它也覆寫了數字。現在我的問題是,有沒有更好的替代 boundingRect 以便只能替換輪廓區域。
輸出影像如下:

原始影像檔案如下

uj5u.com熱心網友回復:
我可以通過以下步驟實作所需的輸出:
反轉影像的顏色(或在查找輪廓時將檢索方法更改為 RETR_INTERNAL)。白色像素的值為 1,黑色像素的值為 0,因此 RETR_EXTERNAL 操作無法檢測到黑色輪廓。
像你一樣根據面積對輪廓進行排序
從第二大輪廓開始用白色填充輪廓。
代碼:
# Images I copied from here were not single channel, so convert to single channel to be able to find contours.
img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# Copy the original image to draw on it later on
img_copy = img.copy()
# Invert the color if using RETR_EXTERNAL
img = cv2.bitwise_not(img)
# Note that findContours function returns hierarchy as well as the contours in OpenCV4.x, in OpenCV3.x it used to return 3 values.
contours, hierarchy = cv2.findContours(img, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
# Sort the contours descending according to their area
contours = sorted(contours, key =lambda x: cv2.contourArea(x), reverse = True)
# Fill the detected contours starting from second largest
for c in contours[1:]:
print(c)
img_copy = cv2.fillPoly(img_copy, [c], color=(255,255,255))
輸出:(視窗之間的黑條是我的背景)

轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/452765.html
