Kaan Çağhan
Kaan Çağhan

Reputation: 93

Removing background with Open CV is not precise and some of pictures could not be done properly

I am trying to remove background from images using OpenCV. Majority of operations are succesfull but some pictures cant be processed properly. Any help or suggestion will be appreciated. my code:

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)

Image:

Image Sample

This is a good example:

This is a good example

This is a bad example:

This is a bad example

Upvotes: 0

Views: 63

Answers (1)

Fadi Abu Raid
Fadi Abu Raid

Reputation: 841

Use HSV filtering.

  1. Change image colors from BGR to HSV (Hue Saturation Value).
  2. Filter a certain range of saturation and hue.

Refer to this page for code https://pythonprogramming.net/color-filter-python-opencv-tutorial/

Upvotes: 2

Related Questions