【问题标题】:Remove borders from image using Python OpenCV使用 Python OpenCV 从图像中删除边框
【发布时间】:2020-03-07 04:16:17
【问题描述】:

我有如下边框的图像。我可以使用 OpenCV 或 python 来去除图像中这样的边框吗?

我使用以下代码进行裁剪,但没有成功。

copy = Image.fromarray(img_final_bin)
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))

【问题讨论】:

  • 这应该通过使用轮廓来解决。

标签: python image opencv image-processing computer-vision


【解决方案1】:

这是一种使用阈值处理 + 轮廓过滤的方法。这个想法是阈值以获得二值图像。从这里我们找到轮廓并使用最大面积阈值进行过滤。我们将通过此过滤器的所有轮廓绘制到空白掩码上,然后执行按位运算以移除边框。这是移除边框的结果

import cv2
import numpy as np

image = cv2.imread('1.png')
mask = np.zeros(image.shape, dtype=np.uint8)
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)[1]

cnts = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if len(cnts) == 2 else cnts[1]
for c in cnts:
    area = cv2.contourArea(c)
    if area < 10000:
        cv2.drawContours(mask, [c], -1, (255,255,255), -1)

mask = cv2.cvtColor(mask, cv2.COLOR_BGR2GRAY)
result = cv2.bitwise_and(image,image,mask=mask)
result[mask==0] = (255,255,255)

cv2.imwrite('result.png', result)
cv2.waitKey()

【讨论】:

  • 我收到错误 - result[mask==0] = (255,255,255) MemoryError: Unable to allocate array with shape (57322428,) and data type int32
  • 我想在图像中保留线条。您共享的上述代码有效,但删除或擦除了图像内的一些线条。 @nathancy
  • 你可以尝试调整轮廓区域只去掉大的外边框
【解决方案2】:

您也可以使用 Werk24 的 API 来阅读技术图纸:www.werk24.io


from werk24 import W24TechreadClient, W24AskCanvasThumbnail

async with W24TechreadClient.make_from_env() as session:
    response = await session.read_drawing(document_bytes,[W24AskCanvasThumbnail()])

它还允许您提取度量等。请参阅: Fully read

我在 Werk24 工作。

【讨论】:

  • 当链接到您自己的网站或内容(或您附属的内容)时,您must disclose your affiliation in the answer 以免被视为垃圾邮件。根据 Stack Exchange 政策,在您的用户名中包含与 URL 相同的文本或在您的个人资料中提及它不被视为充分披露。
猜你喜欢
  • 2018-11-16
  • 2017-10-28
  • 1970-01-01
  • 2015-06-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-09-05
相关资源
最近更新 更多