首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >使用openCV删除部分边框

使用openCV删除部分边框
EN

Stack Overflow用户
提问于 2018-08-10 04:18:56
回答 1查看 3.3K关注 0票数 0

我正在使用OpenCV查找图像中的表格数据,以便我可以对其使用光学字符识别。到目前为止,我已经能够在图像中找到表,找到表中的列,然后找到每列中的每个单元格。它工作得很好,但我遇到了细胞壁卡在我的图像中的问题,我无法可靠地移除它们。This is one example that I'm having difficulty with.This would be another example.

我已经尝试了几种方法来获得更好的图像。我最幸运的是找到了等高线。

代码语言:javascript
运行
复制
img2gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

ret, mask = cv2.threshold(img2gray, 180, 255, cv2.THRESH_BINARY)
image_final = cv2.bitwise_and(img2gray, img2gray, mask=mask)
ret, new_img = cv2.threshold(image_final, 180, 255, cv2.THRESH_BINARY_INV)

kernel = cv2.getStructuringElement(cv2.MORPH_CROSS, (5, 3))

# dilate , more the iteration more the dilation
dilated = cv2.dilate(new_img, kernel, iterations=3)
cv2.imwrite('../test_images/find_contours_dilated.png', dilated)

我一直在尝试内核大小和扩张迭代,并发现这是最好的配置。

我使用的另一种方法是PIL,但只有在整个图像的边界是一致的情况下才是真正好的,但在我的例子中却不是。

代码语言:javascript
运行
复制
copy = Image.fromarray(img)
try:
    bg = Image.new(copy.mode, copy.size, copy.getpixel((0, 0)))
except:
    return None
diff = ImageChops.difference(copy, bg)
diff = ImageChops.add(diff, diff, 2.0, -100)
bbox = diff.getbbox()
if bbox:
    return np.array(copy.crop(bbox))

我还尝试了其他一些想法,但都没有让我走得太远。任何帮助都将不胜感激。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-08-11 20:46:57

你可以试着找到等高线,然后把它们“画出来”。这意味着你可以用cv2.rectangle在图像的边框上绘制一个与“墙”相连的边框(这将结合所有的轮廓-墙)。最大的两个轮廓线将是您的墙的外线和内线,您可以绘制白色的轮廓来删除边界。然后再次应用阈值来消除其余的噪声。干杯!

示例:

代码语言:javascript
运行
复制
import cv2
import numpy as np

# Read the image
img = cv2.imread('borders2.png')

# Get image shape
h, w, channels = img.shape

# Draw a rectangle on the border to combine the wall to one contour
cv2.rectangle(img,(0,0),(w,h),(0,0,0),2)

# Convert to grayscale
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

# Apply binary threshold
_, threshold = cv2.threshold(gray, 180, 255, cv2.THRESH_BINARY_INV)

# Search for contours and sort them by size
_, contours, hierarchy = cv2.findContours(threshold,cv2.RETR_TREE,cv2.CHAIN_APPROX_NONE)
area = sorted(contours, key=cv2.contourArea, reverse=True)

# Draw it out with white color from biggest to second biggest contour
cv2.drawContours(img, ((contours[0]),(contours[1])), -1, (255,255,255), -1)

# Apply binary threshold again to the new image to remove little noises
_, img = cv2.threshold(img, 180, 255, cv2.THRESH_BINARY)

# Display results
cv2.imshow('img', img)

结果:

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51775170

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档