Reputation: 147
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.
[]
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()
Upvotes: 5
Views: 9397
Reputation: 46600
Here's a simple approach:
After converting to grayscale we color threshold to get a mask of only green pixels within the minimum/maximum range
Next we find contours and fill in the mask to keep everything inside using cv2.fillPoly()
Now we cv2.bitwise_and()
to get our result
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()
Upvotes: 4