【问题标题】:Remove the background from a picture using python使用python从图片中删除背景
【发布时间】:2021-11-29 14:38:57
【问题描述】:

我正在尝试删除一组茶叶图像的背景。

我在 StackOverflow 本身中尝试了这些代码,但它们不适用于我的图像。

如何删除叶子周围的整个背景并只保留单个叶子。

这是图像集的一个样本。

【问题讨论】:

  • 这种情况下的“背景”是什么?您链接的方法是如何失效的?
  • 我需要移除叶子周围的整个背景。上面提到的方法并没有删除叶子周围的整个背景
  • 那么,你认为除了单叶之外的所有东西都是背景?
  • 是的,没错
  • 那么在我看来,您的第一个链接中的方法应该工作得很好。您可能需要先遮盖整个白卡区域(包括叶子),以免茎与多叶背景相连。

标签: python opencv machine-learning computer-vision


【解决方案1】:
# Read image 
img = cv2.imread('leaf.jpg')

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

# Find edges
thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_OTSU + cv2.THRESH_BINARY)[1]

# Find contour
contours = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
contours = contours[0] if len(contours) == 2 else contours[1]
# Sort contour by area
contours = sorted(contours, key=cv2.contourArea, reverse=True)

# Find the bounding box and crop image to get ROI 
for cnt in contours:
    x,y,w,h = cv2.boundingRect(cnt)
    ROI = img[y:y+h, x:x+w]
    break

# Define lower and upper threshold for background
lower = np.array([128, 128, 128])
upper = np.array([255, 255, 255])

# Create mask to only select black
thresh = cv2.inRange(ROI, lower, upper)

# Apply morphology
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (3,3))
morph = cv2.morphologyEx(thresh, cv2.MORPH_CLOSE, kernel)

# invert morph image to get background as black
mask = 255 - morph

# apply mask to image
result = cv2.bitwise_and(ROI, ROI, mask=mask)

plt.imshow(result)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-02-06
    • 2020-12-11
    • 2012-12-19
    • 2021-06-05
    • 2014-02-08
    • 2020-12-05
    • 1970-01-01
    • 2012-03-05
    相关资源
    最近更新 更多