我正在尝试使用OpenCV从图像中删除背景。大多数操作都成功完成,但是某些图片无法正确处理。任何帮助或建议,将不胜感激。
我的代码:
import os
import numpy
import cv2
import os
import glob
img_dir = r"C:\Users\kaan\Documents\Plant_Seedlings_Classification-master\Plant_Seedlings_Classification-master\data\osmancik"
data_path = os.path.join(img_dir,'*g')
files = glob.glob(data_path)
data = []
for f1 in files:
img = cv2.imread(f1)
img = cv2.resize(img, (640, 480))
data.append(img)
data2 = []
arr = numpy.array(data2)
for pict in data:
gray_img = cv2.cvtColor(pict, cv2.COLOR_BGR2GRAY)
_, thresh = cv2.threshold(gray_img, 127, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)
img_contours = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)[-2]
img_contours = sorted(img_contours, key=cv2.contourArea)
for i in img_contours:
if cv2.contourArea(i) > 100:
break
mask = np.zeros(img.shape[:2], np.uint8)
cv2.drawContours(mask, [i],-1, 255, -1)
new_img = cv2.bitwise_and(pict, pict, mask=mask)
name=randomString()+".jpg"
path = r"C:\Users\kaan\Documents\Plant_Seedlings_Classification-master\Plant_Seedlings_Classification-master\segmentated\osmancik2"
cv2.imwrite(os.path.join(path , name), new_img)
图片:这是一个很好的例子:
这是一个不好的例子:
最佳答案
使用HSV过滤。
参见页面获取代码https://pythonprogramming.net/color-filter-python-opencv-tutorial/
关于python - 使用Open CV删除背景并不精确,并且某些图片无法正确处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64171106/