我如何从这张图片中删除背景,只想要图片中的生菜?

时间:2018-11-23 21:32:14

标签: python opencv image-processing scikit-image edge-detection

image of lettuce

只是想保留生菜,我有数百张这样的图像,并且会比较生菜的大小,所以首先我尝试了canny边缘检测,但似乎没有用,任何想法都应该如何移动

3 个答案:

答案 0 :(得分:1)

一种可能的方法是使用“图形分割”方法(cv :: ximgproc :: segmentation :: GraphSegmentation),将其应用于转换为HSV或HSL的图像,其中将V或L平面设置为常数照明变平。

答案 1 :(得分:0)

只要修复照明(下面列出的方法1),您就可以摆脱阈值限制,否则,您可能需要结合连接的组件和假设的简单分类器方法(例如,聚类技术,方法2)在植物的位置或颜色上将检测到的类别分配给植物。

from scipy.misc import imread
import matplotlib.pyplot as plt
import matplotlib.patches as patches
%matplotlib inline
import matplotlib
import numpy as np

# read the image
img = imread('9v5wv.png')

# show the image
fig,ax = plt.subplots(1)
ax.imshow(img)
ax.grid('off')

# show the r,g,b channels separately.
for n,d in enumerate([('r',0),('g',1),('b',2)]):
  k,v = d
  plt.figure(n)
  plt.subplot(131)
  plt.imshow(arr[:,:,v],cmap='gray')
  plt.grid('off')
  plt.title(k)
  plt.subplot(133)
  _=plt.hist(arr[:,:,v].ravel(),bins=100)


# method 1, rgb thresholding will not work when lighting changes
arr = img

r_filter = lambda x: x[:,:,0] < 100
g_filter = lambda x: x[:,:,1] > 80
b_filter = lambda x: x[:,:,2] < 200
mask=np.logical_and(np.logical_and(r_filter(arr),g_filter(arr)),b_filter(arr))


plt.imshow(mask,cmap='gray')
plt.grid('off')

enter image description here

# method 2, kmeans clustering
from sklearn.cluster import KMeans
arr = matplotlib.colors.rgb_to_hsv(img[:,:,0:3])
# ignore v per Yves Daoust
data = np.array(arr[:,:,0:2])
x,y,z = data.shape
X = np.reshape(data,(x*y,z))
kmeans = KMeans(n_clusters=6, random_state=420).fit(X)
mask = np.reshape(kmeans.labels_,(x,y,))

plt.imshow(mask==0,cmap='gray')
plt.grid('off')

enter image description here

答案 2 :(得分:0)

您可以将RGB图像转换为HSV图像并分割绿色区域。

import cv2
import numpy as np

frame=cv2.imread('a.png')
hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)

lower = np.array([50,50,50])
upper = np.array([70,255,255])

mask = cv2.inRange(hsv, lower, upper)
res = cv2.bitwise_and(frame,frame, mask= mask)

cv2.imshow('frame',frame)
cv2.imshow('res',res)
cv2.waitKey(0)
cv2.destroyAllWindows()

The final output