通过Python从图像中提取椭圆形食物板

时间:2020-03-18 20:24:11

标签: python opencv image-processing computer-vision object-detection

Food Plate

想法是提取椭圆形的盘子。
我尝试了OpenCV的T方法,但仅适用于完美圆。
我还尝试了balanceC.setCellFactory(c -> new TableCell<>() { @Override protected void updateItem(Double balance, boolean empty) { super.updateItem(balance, empty); if (balance == null || empty) { setText(null); } else { setText(String.format("%.2f", balance.doubleValue()); } } }); 中的HoughCircles方法,但是它花费的时间太长,或者我以错误的方式实现了该方法。
使用OpenCV模块可以检测椭圆形状吗?

还有哪些其他解决方案?

餐盘:
enter image description here

1 个答案:

答案 0 :(得分:0)

提取印版的主键是使用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)

结果:
enter image description here

相关问题