python - 如何在python中删除图像的背景

标签 python image opencv image-processing background

我有一个包含全宽人类图像的数据集我想删除这些图像中的所有背景,只留下全宽的人,
我的问题:
有没有这样做的python代码?
我是否需要每次指定人对象的坐标?
enter image description here

最佳答案

这是使用 Python/OpenCV 的一种方法。

  • 阅读输入
  • 转为灰色
  • 阈值和反转作为掩码
  • 可选择应用形态学清理任何多余的 Blob
  • 边缘抗锯齿
  • 将输入的副本转换为 BGRA 并将掩码插入为 alpha channel
  • 保存结果

  • 输入:
    enter image description here
    import cv2
    import numpy as np
    
    # load image
    img = cv2.imread('person.png')
    
    # convert to graky
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    
    # threshold input image as mask
    mask = cv2.threshold(gray, 250, 255, cv2.THRESH_BINARY)[1]
    
    # negate mask
    mask = 255 - mask
    
    # apply morphology to remove isolated extraneous noise
    # use borderconstant of black since foreground touches the edges
    kernel = np.ones((3,3), np.uint8)
    mask = cv2.morphologyEx(mask, cv2.MORPH_OPEN, kernel)
    mask = cv2.morphologyEx(mask, cv2.MORPH_CLOSE, kernel)
    
    # anti-alias the mask -- blur then stretch
    # blur alpha channel
    mask = cv2.GaussianBlur(mask, (0,0), sigmaX=2, sigmaY=2, borderType = cv2.BORDER_DEFAULT)
    
    # linear stretch so that 127.5 goes to 0, but 255 stays 255
    mask = (2*(mask.astype(np.float32))-255.0).clip(0,255).astype(np.uint8)
    
    # put mask into alpha channel
    result = img.copy()
    result = cv2.cvtColor(result, cv2.COLOR_BGR2BGRA)
    result[:, :, 3] = mask
    
    # save resulting masked image
    cv2.imwrite('person_transp_bckgrnd.png', result)
    
    # display result, though it won't show transparency
    cv2.imshow("INPUT", img)
    cv2.imshow("GRAY", gray)
    cv2.imshow("MASK", mask)
    cv2.imshow("RESULT", result)
    cv2.waitKey(0)
    cv2.destroyAllWindows()
    

    透明结果:
    enter image description here

    关于python - 如何在python中删除图像的背景,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63001988/

    相关文章:

    python OptionParser.has_option 错误

    c++ - OpenCV C++ 模板匹配/关联

    c++ - 如何消除直线

    c++ - 如何通过opencv计算提取轮廓的曲率?

    python 安装程序在激活的 virtualenv 之外安装

    python - 带有 Python 2 和 Python3 内核的 Jupyter notebook

    image - 如何在 OpenCV 中计算一个点的 3D 坐标

    python - OpenCv Python 颜色检测

    python - 如何使用 scipy 编辑稀疏矩阵中的单元格?

    ios - 是否真的有必要为 iOS 应用程序提供所有不同的应用程序图标大小?