5

I have an image and I need to make everything black except for the color green and what ever color is inside there. How do I make all black except for green and what ever color is inside green?

I have converted the color image from RGB to BGR and converted BGR to HSV. I have created lower and upper for green Masked the image according to the boundaries but when I show the image everything else is black except for green. The color inside the green rectangle doesn't show up.

[enter image description here]

hsv = cv2.cvtColor(img,cv2.COLOR_BGR2HSV)
lower = np.array([69,206,177], dtype = "uint8")
upper = np.array([69,206,177], dtype = "uint8")

green_mask = cv2.inRange(hsv,lower,upper)
green= cv2.bitwise_and(hsv,hsv,mask=green_mask )

cv2.imshow("Show colors in green ",green)


cv2.waitKey(0)
cv2.destroyAllWindows()
nathancy
  • 42,661
  • 14
  • 115
  • 137
praa
  • 147
  • 1
  • 8
  • 2
    Get the outer contour for that region and make it filled. Then use that as a mask (ROI) invert it and blacken everything but where the inverted mask is white. See https://likegeeks.com/python-image-processing/#Remove-Background-from-an-image. Suggestion: try a Google or StackOverflow search before asking questions here. – fmw42 Sep 15 '19 at 02:58
  • [OpenCV: setting all pixels of specific BGR value to another BGR value](https://stackoverflow.com/questions/11433604/opencv-setting-all-pixels-of-specific-bgr-value-to-another-bgr-value) This is a duplicate – Santhosh Dhaipule Chandrakanth Sep 15 '19 at 06:36
  • Possible duplicate of [OpenCV: setting all pixels of specific BGR value to another BGR value](https://stackoverflow.com/questions/11433604/opencv-setting-all-pixels-of-specific-bgr-value-to-another-bgr-value) – Santhosh Dhaipule Chandrakanth Sep 15 '19 at 06:36

1 Answers1

4

Here's a simple approach:

  • Convert image to grayscale
  • Color threshold to isolate green
  • Find contours and fill in mask
  • Bitwise-and to get result

After converting to grayscale we color threshold to get a mask of only green pixels within the minimum/maximum range

enter image description here

Next we find contours and fill in the mask to keep everything inside using cv2.fillPoly()

enter image description here

Now we cv2.bitwise_and() to get our result

enter image description here

import numpy as np
import cv2

image = cv2.imread('1.png')
original = image.copy()
image = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
lower = np.array([35, 0, 0], dtype="uint8")
upper = np.array([131, 255, 185], dtype="uint8")
mask = cv2.inRange(image, lower, upper)

cnts = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if len(cnts) == 2 else cnts[1]
cv2.fillPoly(mask, cnts, (255,255,255))
result = cv2.bitwise_and(original,original,mask=mask)

cv2.imshow('mask', mask)
cv2.imshow('result', result)
cv2.waitKey()
nathancy
  • 42,661
  • 14
  • 115
  • 137