python - 从白色背景中提取前景图像
问题描述
我有以下图像,这是一张带有 4 张图像的扫描打印纸。我在同一张纸上打印了 4 张图像以节省打印资源:
但是,现在我需要逐个提取图像,并为每个图像创建一个单独的图像文件。有没有使用 Python、Matlab 或任何其他编程语言的简单方法?
解决方案
这是在 Python/OpenCV 中执行此操作的一种方法。但它要求图片两侧的颜色与背景颜色有足够的差异。如果是这样,您可以对图像进行阈值处理,然后获取轮廓并使用它们的边界框来裁剪每个图像。
- 读取输入
- 基于背景颜色的阈值
- 反转阈值,使背景为黑色
- 应用形态学打开和关闭以填充图片区域并去除噪声
- 获取外部轮廓
- 对于每个轮廓,获取其边界框并裁剪输入图像并将其保存到磁盘
输入:
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()
形态清洗后的阈值图像:
裁剪图像:
推荐阅读
- c++ - 简化依赖于参数的类型转换
- ios - OAuthSwift:如何使用隐式授权流设置 OAuth 2.0 的令牌到期日期?
- node.js - 如何加快电子应用程序的启动时间?
- python - Python xlsxwriter,导出到网络驱动器
- python - 使用 selenium 从 url 列表中下载多个 pdf
- wordpress - 使用 WordPress REST API 为用户分配角色
- javascript - Ramda JS 如何使用 2 个 json 文件映射特定值
- javascript - 在颜色选择器中获取背景颜色
- c# - 在服务器端的 Blazor 下使用 SignInManager.SignInAsync(.......) 时,它会引发异常
- python - Luigi 处理具有多个依赖任务的缺失任务