python-3.x - 从图像中裁剪矩形纸
问题描述
来自讨论:从图像 中准确裁剪文档纸
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
我能够得到想要的结果,但不能得到矩形图像。我在这里附上,这是我在裁剪图像后得到的。我想要一张纸的矩形图像。请帮我解决一下这个。
提前致谢
解决方案
我可以看到的第一个问题是阈值不够低,因此纸张的底部没有正确捕获(它太暗而无法被阈值捕获)
据我所知,第二个问题是能够使正方形适合图像。您需要做的是包装透视图。
为此,您可以在PyImageSearch 的这篇精彩文章中找到更多信息
推荐阅读
- forms - Google Apps 脚本错误:无法读取 null 的属性“appendRow”
- r - R中插入符号中神经网络(nnet)的超参数调整
- android - 我如何在 webview android 中进行多个文件上传
- android - 有什么方法可以取消自定义 DialogFragment?
- node.js - NodeJS SetInterval 与 Async/Await
- linux - 在 docker build 的步骤之间丢失 postgres 数据文件
- javascript - 在 document.formname.inputname.value 中使用 JavaScript var
- node.js - 从服务器获取未知 url 的安全隐患
- c++ - 我该如何解决我的代码中没有声明问题?
- excel - 突出显示相同日期的重复项