如何改进颜色图层蒙版以获得中间色调?

问题描述 投票:0回答:1

我想改进我在 Python 中创建的图层蒙版。虽然我的蒙版几乎达到了目标颜色,但我的主要问题是它是以二进制形式进行的,像素要么是纯白色,要么是纯黑色。我无法推断颜色的强度。我想要实现像 Photoshop 那样的效果,其中蒙版上有灰色的中间色调。

这是当前的尝试: 导入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()

这是简单的图像。

python numpy opencv image-processing alpha
1个回答
0
投票

试试这个,这是代码的改进版本:

import cv2
import numpy as np

# Read the image
image = cv2.imread('grade_0.jpg')

# Define the lower and upper bounds for the targeted color
lower = np.array([0, 0, 0])
upper = np.array([12, 255, 255])

# Generate a mask using HSV color space
hsv_image = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
mask = cv2.inRange(hsv_image, lower, upper)

# Convert the mask to grayscale
gray_mask = cv2.cvtColor(mask, cv2.COLOR_GRAY2BGR)

# Apply adaptive thresholding to introduce grayscale tones
gray_mask = cv2.cvtColor(gray_mask, cv2.COLOR_BGR2GRAY)
adaptive_threshold = cv2.adaptiveThreshold(gray_mask, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, 11, 2)

# Invert the adaptive threshold to match the desired mask
inverted_threshold = cv2.bitwise_not(adaptive_threshold)

# Apply the mask to the original image
output = cv2.bitwise_and(image, image, mask=inverted_threshold)

# Display the output
cv2.imshow("Output", output)
cv2.waitKey(0)
cv2.destroyAllWindows()

这会将初始二进制掩模转换为灰度图像。

应用自适应阈值处理,根据局部图像特征生成中间灰度色调。

并反转阈值图像以确保感兴趣的区域被正确掩盖。 最后,将修改后的蒙版应用到原始图像上。

此方法应生成具有灰度色调的图层蒙版,反映图像中目标颜色的强度,类似于 Photoshop 中看到的行为。

希望这有帮助。

© www.soinside.com 2019 - 2024. All rights reserved.