python - 如何从文档中删除所有肖像图片
问题描述
我正在对文档图像进行 OCR。我想检测所有图片并从文档图像中删除。我想在文档图像中保留表格。一旦我检测到图片,我将删除然后想要 OCR。我试图找到轮廓试图检测所有更大的区域。不幸的是,它也检测到表格。还如何删除在文档图像中保留其他数据的对象。我正在使用 opencv 和 python
这是我的代码
import os
from PIL import Image
import pytesseract
img = cv2.imread('block2.jpg' , 0)
mask = np.ones(img.shape[:2], dtype="uint8") * 255
ret,thresh1 = cv2.threshold(img,127,255,0)
contours, sd = cv2.findContours(thresh1,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)
areacontainer = []
for cnt in contours:
area = cv2.contourArea(cnt)
areacontainer.append(area)
avgArea = sum(areacontainer)/len(areacontainer)
[enter code here][1]
for c in contours:# average area heuristics
if cv2.contourArea(c)>6*avgArea:
cv2.drawContours(mask, [c], -1, 0, -1)
binary = cv2.bitwise_and(img, img, mask=mask) # subtracting
cv2.imwrite("bin.jpg" , binary)
cv2.imwrite("mask.jpg" , mask)
解决方案
这是一种方法:
- 将图像转换为灰度和高斯模糊
- 执行精明的边缘检测
- 执行形态学操作以平滑图像
- 使用最小/最大阈值区域查找轮廓和过滤
- 删除纵向图像
这是检测到的以绿色突出显示的肖像
现在我们有了边界框 ROI,我们可以通过用白色填充图片来有效地移除图片。这是结果
import cv2
image = cv2.imread('1.jpg')
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
blur = cv2.GaussianBlur(gray, (3,3), 0)
canny = cv2.Canny(blur, 120, 255, 1)
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (3,3))
close = cv2.morphologyEx(canny, cv2.MORPH_CLOSE, kernel, iterations=2)
cnts = cv2.findContours(close, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if len(cnts) == 2 else cnts[1]
for c in cnts:
area = cv2.contourArea(c)
if area > 15000 and area < 35000:
x,y,w,h = cv2.boundingRect(c)
cv2.rectangle(image, (x, y), (x + w, y + h), (255,255,255), -1)
cv2.imshow('image', image)
cv2.waitKey()
推荐阅读
- javascript - pdf.js 的问题不下载文件和打印
- reactjs - 无法在其他表单域上输入
- java - Spring boot security Authentication [This localhost page can't be found: HTTP ERROR 404] 错误
- reactjs - 如何修复 React:字符串与预期的模式错误不匹配
- angular - Angular TestBed.inject
- .net - 如何使用谷歌身份验证在.net核心中刷新令牌或增加到期时间
- hive - 复制 impala 表的最佳方法
- python - Python进程没有延迟启动
- wordpress - Gatsby:如何将多个上下文 ID 传递给单个查询?
- elasticsearch - 我可以更改 Kibana 开发工具中的默认缩进空格吗?