How to remove the background of an object using OpenCV (Python)

845 views Asked by At

I need to remove the green color from the background and leave only the wheat grains in black background. Any suggestion will be appreciated? Here is how image looks like:

a

1

There are 1 answers

1
Scott On BEST ANSWER

You mean this? :

import cv2
import numpy as np

img = cv2.imread("image.jpg")
hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)

mask = cv2.inRange(hsv, (0, 0, 0), (75, 255, 255))
imask = mask > 0
green = np.zeros_like(img, np.uint8)
green[imask] = img[imask]

cv2.imwrite("result.png", green)

Output enter image description here