我正在尝试获取专辑封面的轮廓,但边缘检测器(Canny、Laplace)拾取了太多噪音。我不完全理解图像遮罩的工作原理,并且想在图像上放置白色遮罩,这样我只能看到黑色像素
我应用了 GaussianBlur 5x5 并将图像转换为 hsv 值。我有一系列黑色值,我已将其过滤掉。
# imported image and processing (shorthand here)
image = cv2.imread(args["image"])
blur = cv2.GaussianBlur(image, (5,5), 0)
blur_hsv = cv2.cvtColor(blur, cv2.COLOR_BGR2HSV)
# set regions of color
boundaries = [
# black
([0,0,0],[180, 255, 40])
#pink
#([151, 80, 50], [174, 255, 255])
]
# loop over the boundaries
for (lower, upper) in boundaries:
# create NumPy arrays from the boundaries
lower = np.array(lower, dtype = "uint8")
upper = np.array(upper, dtype = "uint8")
# find the colors within the specified boundaries and apply
mask = cv2.inRange(blur_hsv, lower, upper)
output = cv2.bitwise_and(image, image, mask = mask)
# show the images
cv2.imshow("images", np.hstack([image, output]))
Run Code Online (Sandbox Code Playgroud)
我希望最终输出有一些区别,但窗口只是黑色的。如何创建不同颜色的蒙版?
编辑:
不是确切的图像,而是一个示例 左:原始;右:已处理
根据我的理解,您想要获得一个所有彩色像素(非黑色)都是白色的蒙版。当我们使用 时,我们给它一个下/上阈值,以白色cv2.inRange()
返回边界内的所有像素。然后,当我们将蒙版和原始图像一起使用时,得到的图像将是蒙版和原始图像均为白色的区域。本质上,任何白色像素都是我们想要保留的区域。cv2.bitwise_and()
您当前的输出显示原始图片中像素位于下限/上限阈值之间的所有区域。但如果您的目标是显示所有非黑色像素,那么您可以简单地反转蒙版。这是一个可视化:
这是您当前的蒙版,并将原始图像中阈值内的所有像素表示为白色。
我们可以简单地翻转面具或使用cv2.bitwise_not()
以获得您想要的面具。这个新的蒙版将不在下限/上限阈值内的所有彩色像素表示为白色。因此,这个掩模是所有彩色像素。
final_mask = 255 - mask
Run Code Online (Sandbox Code Playgroud)
请记住,我们想要保留的任何像素,我们应该将其设置为白色,而我们想要丢弃的任何像素,我们应该将其设置为黑色。因此,如果我们将cv2.bitwise_and()
这个新蒙版与原始图像一起使用,我们会得到这个
import cv2
import numpy as np
image = cv2.imread('1.png')
blur = cv2.GaussianBlur(image, (5,5), 0)
blur_hsv = cv2.cvtColor(blur, cv2.COLOR_BGR2HSV)
# create NumPy arrays from the boundaries
lower = np.array([0,0,0], dtype = "uint8")
upper = np.array([180,255,40], dtype = "uint8")
# find the colors within the specified boundaries and apply
mask = cv2.inRange(blur_hsv, lower, upper)
mask = 255 - mask
output = cv2.bitwise_and(image, image, mask = mask)
# show the images
cv2.imshow("output", output)
cv2.imshow("mask", mask)
cv2.waitKey()
Run Code Online (Sandbox Code Playgroud)