简体   繁体   中英

OpenCV Python how to keep one color as is converting an image to Grayscale

锥体的图像

How do I make it so everything in the image is in gray-scale except the orange cone. Using opencv python.

You can achieve your goal by using bitwise_and() function and thresholding . Steps:

  • generate mask for the required region.(here thresholding is used but other methods can also be used)
  • extract required regions using bitwise_and (image & mask).
  • Add 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 threshoding value)
# I have used 200 as thershoding 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 `biteise_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:

masked orange image

蒙面的橙色图像

masked gray image

在此处输入图像描述

output image

在此处输入图像描述

Here is an alternate way to do that in Python/OpenCV.

  • Read the input
  • Threshold on color using cv2.inRange()
  • Apply morphology to clean it up and fill in holes as a mask
  • Create a grayscale version of the input
  • Merge the input and grayscale versions using the mask via np.where()
  • Save the results

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:

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM