将灰色背景转换为白色背景,而不干扰原始imag

2024-07-02 12:58:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我裁剪了一些有灰色背景的图像,需要将它们转换为白色背景以与参考图像进行比较。你知道吗

我实现了以下代码来转换:

import cv2
im_gray = cv2.imread('gray_bg.png', cv2.IMREAD_GRAYSCALE)
(thresh, im_bw) = cv2.threshold(im_gray, 255, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
cv2.imwrite('white_bg.png', im_bw)

输入: gray_bg.png

输出: white_bg.png

预期产量: ex_white_bg

如果你观察,我的输出图像有一些噪音在原始图像的边缘(我希望我说的没有错)。因此,在将我的输出与参考图像进行比较时,我没有得到所需的输出。有人能建议我怎么做吗?你知道吗

下面是我们编写的用于比较两幅图像的程序:

SourceImagePath = r'white_bg.png'
TemplateImagePath = r'ex_white_bg.png'
#def IconValidation(self,SourceImagePath,TemplateImagePath):
sourceImg=cv.imread(SourceImagePath)
templateImg=cv.imread(TemplateImagePath)
_,tempwidth,tempheight=templateImg.shape[::-1]
srcheight = np.size(sourceImg, 0)
srcwidth = np.size(sourceImg, 1)
if(srcwidth < tempwidth) and (srcheight < tempheight):
    print("comparison")

resultImg = cv.matchTemplate(sourceImg,templateImg,cv.TM_CCOEFF_NORMED)
matchVal = resultImg[0][0]
threshold=0.95
if(matchVal>threshold):
    print("passed")

else:
    print("failed")

Tags: 图像thresholdpngcv2cvbgprintwhite
2条回答

避免了颜色编码的变化,取得了最佳的效果。代码如下:

im_gray = cv2.imread('gray_bg.png', cv2.IMREAD_UNCHANGED)
b, g, r = cv2.split(im_gray)

t = [None] * 3
u = [None] * 3
for i, im in enumerate([b, g, r]):
    t[i], u[i] = cv2.threshold(im, 255, 255, cv2.THRESH_BINARY + cv2.THRESH_TRIANGLE)

dst = cv2.merge((*u,))
cv2.imwrite('white_bg.png', dst)

通过与原始值比较,它给出了99.99%等式。你知道吗

如果你真的需要它,你可以用cv2.cvtColor(src, cv2.COLOR_BGR2GRAY)把图像转换成灰度编码。你知道吗

结果vs需求:

Obtained imageWanted image

你看到的是混叠,而不是噪音。它的出现是因为硬阈值。你知道吗

您输入的图像确实有一些噪声,您可以通过放大看到(可能是由于某个阶段的有损压缩),但它没有混叠。你知道吗

enter image description here

通过应用1.4的增益(灰度约为180),可以将灰色背景变为白色,同时保持黑色。这将避免引入别名。你知道吗

enter image description here

相关问题 更多 >