I would like to improve the layer mask that I am creating in Python. Although my mask pretty much hits the targeted color, my main problem with it, is it is doing so in binary, the pixel is either pure white or pure black. I’m unable to extrapolate the intensity of the color. I want to achieve something like how Photoshop does it wherein there are mid-tones of grey on the mask.
Here is the current attempt:
import cv2
image = cv2.imread('grade_0.jpg')
lower = np.array([0,0,0])
upper = np.array([12,255,255])
mask = cv2.inRange(cv2.cvtColor(image, cv2.COLOR_BGR2HSV), lower, upper)
mask = 255 - mask
# mask = cv2.bitwise_not(mask) #inverting black and white
output = cv2.bitwise_and(image, image, mask = mask)
cv2.imshow("output", output)
cv2.imshow("mask", mask)
cv2.waitKey()
Here are the plain images.
3
Answers
So let me throw in an answer, it might not be a great answer but i did try to somehow go in that direction
My approach involves creating a mask for every hue value in a given hue range, after that the mask is then combined but with an assigned grey value depending on its position in the input range
I believe applying quantization to your image might achieve the desired effect similar to color range as seen in Adobe Photoshop. Below is the code snippet that I’ve used for posterization, inspired by a solution on Stack Overflow (Adobe Photoshop-style posterization and OpenCV). This approach utilizes quantization to reduce the number of colors, effectively targetting color on the image:
This method should provide the effect you’re looking for. Here are the results of the image processing applied to the provided picture.
N = 7
Gray Scale = True, N = 4
I apologize – my OpenCV is broken at the moment. But here is another method that I will implement in Imagemagick.
Input:
magick sample.jpg -sigmoidal-contrast 20,50% x.png
magick x.png -black-threshold 20% -white-threshold 80% -fill black -opaque white -colorspace gray result.png
The sigmoidal-contrast function is:
and has a transfer curve (input to output) shape of:
Here is the linear equivalent process, which just skips the sigmoidal contrast. I change the threshold values to compensate some for the lack of the sigmoidal contrast. So it is just a low threshold followed by a high threshold followed by changing white to black, followed by convert to grayscale.