首页 > 解决方案 > 从图像中裁剪矩形纸

问题描述

来自讨论:从图像 中准确裁剪文档纸

def crop_image(image):
image = cv2.imread(image)

# convert to grayscale image
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

# threshold
thresh = cv2.threshold(gray, 190, 255, cv2.THRESH_BINARY)[1]

# apply morphology
kernel = np.ones((7, 7), np.uint8)
morph = cv2.morphologyEx(thresh, cv2.MORPH_CLOSE, kernel)
kernel = np.ones((9, 9), np.uint8)
morph = cv2.morphologyEx(morph, cv2.MORPH_ERODE, kernel)


# Get Largest contour
contours = cv2.findContours(morph, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
contours = contours[0] if len(contours) == 2 else contours[1]
area_thresh = 0
for cnt in contours:
    area = cv2.contourArea(cnt)
    if area > area_thresh:
        area_thresh = area
        big_contour = cnt

# get bounding box
x, y, w, h = cv2.boundingRect(big_contour)

# draw filled contour on black background
mask = np.zeros_like(gray)
mask = cv2.merge([mask, mask, mask])
cv2.drawContours(mask, [big_contour], -1, (255, 255, 255), cv2.FILLED)

# apply mask to input
result = image.copy()
result = cv2.bitwise_and(result, mask)

# crop result
img_result = result[y:y+h, x:x+w]
filename = generate_filename()
cv2.imwrite(filename, img_result)
logger.info('Successfully saved cropped file : %s' % filename)
return img_result, filename

我能够得到想要的结果,但不能得到矩形图像。我在这里附上最初拍摄的照片,这是我在裁剪图像后得到的裁剪图像。我想要一张纸的矩形图像。请帮我解决一下这个。

提前致谢

标签: python-3.xopencvmachine-learningimage-processingcomputer-vision

解决方案


我可以看到的第一个问题是阈值不够低,因此纸张的底部没有正确捕获(它太暗而无法被阈值捕获)

据我所知,第二个问题是能够使正方形适合图像。您需要做的是包装透视图。

为此,您可以在PyImageSearch 的这篇精彩文章中找到更多信息


推荐阅读