细化OpenCV遮罩边缘

时间:2019-01-31 15:26:04

标签: python opencv

我正在扫描旧照片,我想自动化从扫描仪的(嘈杂的)纯白色背景中提取照片的过程,以便获得透明的照片。该程序的这一部分现在可以使用,但是我对此还有一个小问题。

现在可以准确地检测(并提取)照片,但是它会在整个照片周围的背景上留下一个小的且清晰的黑色边框。我曾尝试对透明蒙版应用高斯模糊,但这不会消除黑度(这会使照片的边框看起来“被弄脏”了。)

这是我提取照片并生成透明蒙版的代码:

# Load the scan, and convert it to RGBA.
original = cv2.imread('input.jpg')
original = cv2.cvtColor(original, cv2.COLOR_BGR2BGRA)

# Make the scan grayscale, and apply a blur.
image = cv2.cvtColor(original, cv2.COLOR_BGR2GRAY)
image = cv2.GaussianBlur(image, (25, 25), 0)

# Binarize the scan.
retval, threshold = cv2.threshold(image, 50, 255, cv2.THRESH_BINARY)

# Find the contour of the object.
contours, hierarchy = cv2.findContours(threshold, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

largestContourArea = -1
largestContour = -1

for contour in contours:
    area = cv2.contourArea(contour)

    if area > largestContourArea:
        largestContourArea = area
        largestContour = contour

# Generate the transparency mask.
mask = numpy.zeros(original.shape, numpy.uint8)

cv2.drawContours(mask, [ largestContour ], -1, (255, 255, 255, 255), -1)

# Apply the transparency mask.
original = cv2.multiply(mask.astype(float) / 255.0, original.astype(float))

cv2.imwrite('output.png', original)

我使用示例扫描在上面有sample scanresult of the code。如您所见,照片周围有一个黑色的小边框,我想删除它。

1 个答案:

答案 0 :(得分:0)

通过使用erode方法,您可以缩小轮廓(mask),有效去除黑色边缘。

由于此方法支持就地操作,因此代码如下所示:cv2.erode(mask, mask, kernel),其中kernel是使用cv2.getStructuringElement获取的内核。通过处理内核和迭代计数,您可以控制缩小的数量。

此页面详细介绍了所有内容,并提供了不错的示例:https://docs.opencv.org/2.4/doc/tutorials/imgproc/erosion_dilatation/erosion_dilatation.html