python - 从白色背景中提取前景图像

标签 python matlab opencv image-processing computer-vision

我有以下图像,它是扫描的打印纸,带有4张图像。我在同一张纸上打印了4张图像以节省打印资源:
Printed images that were scanned later
但是,现在我需要逐个图像提取图像,并为每个图像创建一个单独的图像文件。使用Python,Matlab或任何其他编程语言有没有简便的方法?

最佳答案

这是在Python / OpenCV中执行此操作的一种方法。但是,这要求图片侧面的颜色必须与背景颜色充分不同。如果是这样,则可以对图像进行阈值处理,然后获取轮廓并使用其边界框裁剪出每个图像。

  • 读取输入的
  • 基于背景色
  • 的阈值
  • 反转阈值,使背景为黑色
  • 打开和关闭形态以填充图片区域并消除噪声
  • 获取外部轮廓
  • 对于每个轮廓,获取其边界框并裁剪输入图像并将其保存到磁盘

  • 输入:
    enter image description here
    import cv2
    import numpy as np
    
    # read image
    img = cv2.imread('4faces.jpg')
    
    # threshold on background color
    lowerBound = (230,230,230)
    upperBound = (255,255,255)
    thresh = cv2.inRange(img, lowerBound, upperBound)
    
    # invert so background black
    thresh = 255 - thresh
    
    # apply morphology to ensure regions are filled and remove extraneous noise
    kernel = np.ones((7,7), np.uint8)
    thresh = cv2.morphologyEx(thresh, cv2.MORPH_OPEN, kernel)
    kernel = np.ones((11,11), np.uint8)
    thresh = cv2.morphologyEx(thresh, cv2.MORPH_CLOSE, kernel)
    
    # get contours
    contours = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
    contours = contours[0] if len(contours) == 2 else contours[1]
    
    # get bounding boxes and crop input
    i = 1
    for cntr in contours:
        # get bounding boxes
        x,y,w,h = cv2.boundingRect(cntr)
        crop = img[y:y+h, x:x+w]
        cv2.imwrite("4faces_crop_{0}.png".format(i), crop)
        i = i + 1
    
    
    # save threshold
    cv2.imwrite("4faces_thresh.png",thresh)
    
    # show thresh and result    
    cv2.imshow("thresh", thresh)
    cv2.waitKey(0)
    cv2.destroyAllWindows()
    

    形态清洗后的阈值图像:
    enter image description here
    裁剪的图片:
    enter image description here
    enter image description here
    enter image description here
    enter image description here

    关于python - 从白色背景中提取前景图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62720286/

    相关文章:

    python - 在 Python 中调整大图像大小的 CPU 效率最高的方法是什么

    python - 使用 python-vtk 将多个遗留 ASCII .vtk 文件组合成一个文件

    string - 解释 "str - ' 0'"字符串转整数时的用法。

    r - 大型稀疏矩阵的完整 SVD(仅需要特征值)

    c++ - 如何为 opencv 算法处理文件夹中的图像?

    python - fp =builtins.open(文件名, "rb")-错误

    python - 如何理解 Python 循环的 `else` 子句?

    matlab - Matlab 散点图中的 X 轴标记

    java - 安卓 OpenCV : No resource identifier found for attribute 'camera_id' in package

    c++ - OpenCV 2.4 putText()与Scalar的理解