来自讨论:Crop exactly document paper from image
我正在尝试从图像中获取白皮书,并且正在使用以下代码,但它们并未完全切成矩形。
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
我能够获得所需的结果,但不能得到矩形图像。
在这里,我附加了,这是裁剪图像之后得到的。
我想要一张纸的矩形图像。
请帮我解决一下这个。
提前致谢
最佳答案
我看到的第一个问题是阈值不够低,因此纸张的底部无法正确捕获(太暗而无法被阈值捕获)
据我了解,第二个问题是能够使正方形适合图像。您需要做的是包装透 View 。
为此,您可以在this amazing post of PyImageSearch中找到更多信息。
关于python-3.x - 从图像中裁剪矩形纸,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60717338/