Reputation: 79
How do I make it so everything in the image is in gray-scale except the orange cone. Using opencv python.
Upvotes: 1
Views: 7191
Reputation: 1515
You can achieve your goal by using the bitwise_and()
function and the threshold()
function.
Steps:
mask
for the required region.(here thresholding
is used but other methods can also be used)regions
using bitwise_and
(image & mask).masked regions
to get output.Here's sample code:
import cv2
import numpy as np
img = cv2.imread('input.jpg')
# creating mask using thresholding over `red` channel (use better use histogram to get thresholding value)
# I have used 200 as thresholding value it can be different for different images
ret, mask = cv2.threshold(img[:, :,2], 200, 255, cv2.THRESH_BINARY)
mask3 = np.zeros_like(img)
mask3[:, :, 0] = mask
mask3[:, :, 1] = mask
mask3[:, :, 2] = mask
# extracting `orange` region using `bitewise_and`
orange = cv2.bitwise_and(img, mask3)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
img = cv2.cvtColor(gray, cv2.COLOR_GRAY2BGR)
# extracting non-orange region
gray = cv2.bitwise_and(img, 255 - mask3)
# orange masked output
out = gray + orange
cv2.imwrite('orange.png', orange)
cv2.imwrite('gray.png', gray)
cv2.imwrite("output.png", out)
Results:
Upvotes: 3
Reputation: 53089
Here is an alternate way to do that in Python/OpenCV.
Input:
import cv2
import numpy as np
img = cv2.imread("orange_cone.jpg")
# threshold on orange
lower = (0,60,200)
upper = (110,160,255)
thresh = cv2.inRange(img, lower, upper)
# apply morphology and make 3 channels as mask
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5,5))
mask = cv2.morphologyEx(thresh, cv2.MORPH_CLOSE, kernel)
mask = cv2.morphologyEx(mask, cv2.MORPH_OPEN, kernel)
mask = cv2.merge([mask,mask,mask])
# create 3-channel grayscale version
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
gray = cv2.cvtColor(gray, cv2.COLOR_GRAY2BGR)
# blend img with gray using mask
result = np.where(mask==255, img, gray)
# save images
cv2.imwrite('orange_cone_thresh.jpg', thresh)
cv2.imwrite('orange_cone_mask.jpg', mask)
cv2.imwrite('orange_cone_result.jpg', result)
# Display images
cv2.imshow("thresh", thresh)
cv2.imshow("mask", mask)
cv2.imshow("result", result)
cv2.waitKey(0)
Threshold image:
Mask image:
Merged result:
Upvotes: 2