我如何从这张图片中删除背景,只想从图片中删除莴苣?

2024-03-29 14:39:32 发布

您现在位置:Python中文网/ 问答频道 /正文

image of lettuce

只是想保留莴苣,我有几百个这样的图像,会比较莴苣的大小,所以开始我尝试了精明的边缘检测,但似乎不起作用,任何想法应该如何推进这一点


Tags: 图像边缘莴苣
3条回答

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

只要你修复了你的光照(下面列出的方法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

您可以将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

相关问题 更多 >