簡體   English   中英

通過Python從圖像中提取橢圓形食物盤

[英]Extract ellipse shape food plate from image through Python

食物盤

這個想法是提取橢圓形的板。
我嘗試了 OpenCV 的HoughCircles方法,但它只適用於完美的圓。
我也試過hough_ellipse從方法skimage但它花費的時間太長或我實現了錯誤的方式。
是否可以使用 OpenCV 模塊檢測橢圓形狀?

還有哪些其他解決方案?

食物盤:
在此處輸入圖片說明

提取板塊的主要關鍵是使用cv2.adaptiveThreshold ,但還有幾個階段:

  • 轉換為灰度並應用具有相對較大高斯的自適應閾值。
  • 查找連接的組件(簇)。
    找到最大的集群,並僅使用最大的集群創建新圖像。
  • 使用“開放”形態學操作去除一些偽影。
  • 用白色像素填充板(使用 floodFill)。
  • 尋找輪廓,得到面積最大的輪廓。
  • 以最大尺寸繪制輪廓以創建蒙版。
    在原始圖像上應用蒙版。

通過形狀找到橢圓的魯棒性要低得多......

這是代碼:

import numpy as np
import cv2
import imutils

img = cv2.imread('food_plate.jpg')

# Convert to Grayscale
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

# Apply adaptive threshold with gaussian size 51x51
thresh_gray = cv2.adaptiveThreshold(gray, 255, adaptiveMethod=cv2.ADAPTIVE_THRESH_GAUSSIAN_C, thresholdType=cv2.THRESH_BINARY, blockSize=51, C=0)

#cv2.imwrite('thresh_gray.png', thresh_gray)

# Find connected components (clusters)
nlabel,labels,stats,centroids = cv2.connectedComponentsWithStats(thresh_gray, connectivity=8)

# Find second largest cluster (the cluster is the background):
max_size = np.max(stats[1:, cv2.CC_STAT_AREA])
max_size_idx = np.where(stats[:, cv2.CC_STAT_AREA] == max_size)[0][0]

mask = np.zeros_like(thresh_gray)

# Draw the cluster on mask
mask[labels == max_size_idx] = 255

# Use "open" morphological operation for removing some artifacts
mask = cv2.morphologyEx(mask, cv2.MORPH_OPEN, cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5,5)))

#cv2.imwrite('mask.png', mask)

# Fill the plate with white pixels
cv2.floodFill(mask, None, tuple(centroids[max_size_idx].astype(int)), newVal=255, loDiff=1, upDiff=1)

#cv2.imwrite('mask.png', mask)

# Find contours, and get the contour with maximum area
cnts = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
cnts = imutils.grab_contours(cnts)

c = max(cnts, key=cv2.contourArea)

# Draw contours with maximum size on new mask
mask2 = np.zeros_like(mask)
cv2.drawContours(mask2, [c], -1, 255, -1)

#cv2.imwrite('mask2.png', mask2)

img[(mask2==0)] = 0

# Save result
cv2.imwrite('img.jpg', img)

結果:
在此處輸入圖片說明

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM