# Import the necessary packages
import cv2
import numpy as np
def back_rm(filename):
# Load the image
img = cv2.imread(filename)
# Convert the image to grayscale
gr = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# Make a copy of the grayscale image
bg = gr.copy()
# Apply morphological transformations
for i in range(5):
kernel2 = cv2.getStructuringElement(cv2.MORPH_ELLIPSE,
(2 * i + 1, 2 * i + 1))
bg = cv2.morphologyEx(bg, cv2.MORPH_CLOSE, kernel2)
bg = cv2.morphologyEx(bg, cv2.MORPH_OPEN, kernel2)
# Subtract the grayscale image from its processed copy
dif = cv2.subtract(bg, gr)
# Apply thresholding
bw = cv2.threshold(dif, 0, 255, cv2.THRESH_BINARY_INV | cv2.THRESH_OTSU)[1]
dark = cv2.threshold(bg, 0, 255, cv2.THRESH_BINARY_INV | cv2.THRESH_OTSU)[1]
# Extract pixels in the dark region
darkpix = gr[np.where(dark > 0)]
# Threshold the dark region to get the darker pixels inside it
darkpix = cv2.threshold(darkpix, 0, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU)[1]
# Paste the extracted darker pixels in the watermark region
bw[np.where(dark > 0)] = darkpix.T
#Converting BGR to RGB
rgb_image = cv2.cvtColor(bw, cv2.COLOR_BGR2RGB)
cv2.imwrite('rgb_image.jpg', rgb_image)
back_rm('example2.jpg')
这段代码基本上是什么,它做的是从图像中删除水印.但我希望我的最终输出图像在RGB而不是黑色.例如,应保存最终图像'rgb_image. jpg'在RGB后,从图像中删除水印.但根据编写的代码,它仍然保存在黑色和白色的图像,即使我已经将其转换为RGB. an somon帮助?
enter image description here
enter image description here
1条答案
按热度按时间gmxoilav1#
你保存的是
bw
,它是一个二进制掩码,即一个满是0或255的图像。使用
cv2.cvtColor(bw, cv2.COLOR_BGR2RGB)
将此图像转换为RGB将仅在3个通道上创建黑色和白色值。相反,您应该使用此
bw
掩码来获取要从输入图像中保留的像素值(RGB)。下面是一个稍微简化的例子:
所述输入图像
创建您想要的蒙版,以目标像素的兴趣和删除水印
仅保留蒙版内像素的输入图像RGB值-否则将其更改为白色