OpenCV:使用 Trimap 图像

4
我找到了这个狗和猫的图像数据集:牛津-IIIIT宠物数据集。每张图片都有一个像素级别的前景-背景分割(trimap)图像。
在网上搜索后,我发现trimap是一种具有三种颜色的图像(一种用于背景,一种用于前景,一种用于未分类区域),但这里的图像全是黑色的。
这是错误的还是正确的?但最重要的是,我想知道如果给定一张正常的图像,如何使用它来得到一个带有猫或狗的黑色背景新图像。
谢谢。
2个回答

8

由于它们仅包含0-255范围内介于0-2之间的像素值,因此trimap看起来是黑色的,其中:

  • 1表示“宠物”
  • 2表示“背景”
  • 3表示“边框”

以文本形式查看像素:

identify -verbose Abyssinian_1trimap.png  | more

输出

  Histogram:
     22938: (  1,  1,  1) #010101 gray(1)
    198766: (  2,  2,  2) #020202 gray(2)
     18296: (  3,  3,  3) #030303 gray(3)

如果你对修剪映射进行对比拉伸,那么可以看得更好。我在这里使用的是 Abyssinian1 图像:

convert Abyssinian_1trimap.png -auto-level trimap.jpg

enter image description here

如果您将拍摄的照片与修剪地图相结合,其中所有 1 像素是白色的,所有 2 像素是黑色的,所有 3 像素是白色的,并使用 darken 混合模式进行混合,则可得到您想要的效果:
convert Abyssinian_1.jpg \( Abyssinian_1trimap.png -fill white -opaque "rgb(1,1,1)" -opaque "rgb(3,3,3)" -fill black -opaque "rgb(2,2,2)" \) -compose darken -composite pet.png

enter image description here

如果您想要边框和宠物,请这样做:
convert Abyssinian_1.jpg \( Abyssinian_1trimap.png -fill white -opaque "rgb(1,1,1)" -opaque "rgb(3,3,3)" -fill black -opaque "rgb(2,2,2)" \) -compose darken -composite pet.png

enter image description here

您也可以尝试模糊遮罩以软化边缘:

convert Abyssinian_1.jpg \( Abyssinian_1trimap.png -fill white -opaque "rgb(1,1,1)" -fill black -opaque "rgb(3,3,3)" -opaque "rgb(2,2,2)" -blur 0x8  \) -compose darken -composite pet.png

enter image description here

抱歉,我使用了 ImageMagick 进行操作,因为我发现它更容易使用,并且它已经安装在大多数 Linux 发行版上,同时也适用于 macOS 和 Windows。对于 OpenCV,原理是相同的。

谢谢。我应该如何更改您的最后一个命令,以便在边框(像素3)中扩展图像? - RossFe
对不起,你是什么意思? - Mark Setchell
我希望猫的图像更加精细,就好像我只想从原始图像中去除背景一样。在最终的图像中,只有修剪地图的灰色部分(如上所示)应该变成黑色(不是修剪地图的灰色和白色部分)。 - RossFe

1

我也曾经为此苦苦挣扎,直到最后终于弄明白了。要在Python中加载和显示这些文件,您需要使用以下方法:

import io
import os
import tensorflow as tf
import PIL
import matplotlib.pyplot as plt
import numpy as np

with tf.gfile.GFile("Abyssinian_1.png", 'rb') as fid:
    encoded_mask_png = fid.read()
encoded_png_io = io.BytesIO(encoded_mask_png)
mask = PIL.Image.open(encoded_png_io)            
plt.imshow( np.array(mask) / 2 * 255 )

1
对于TF 2,您需要将tf.gfile更改为tf.io.gfile。对于macOS,您需要添加plt.show()。否则它可以正常工作 :) 感谢分享。 - decades
3/2 * 255 大于 255。 (np.array(mask)-1)/2*255 可以吗? - lanhao945

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接