简体   繁体   中英

Remove borders from image using Python OpenCV

I have images with Borders like the below. Can I use OpenCV or python to remove the borders like this in images?

I used the following code to crop, but it didn't work.

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))

图 1

图 2

Here's an approach using thresholding + contour filtering. The idea is to threshold to obtain a binary image. From here we find contours and filter using a maximum area threshold. We draw all contours that pass this filter onto a blank mask then perform bitwise operations to remove the border. Here's the result with the removed border

在此处输入图像描述

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()

You could also use Werk24's API for reading Technical Drawings: www.werk24.io


from werk24 import W24TechreadClient, W24AskCanvasThumbnail

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

It also allows you to extract the measures etc. See: Fully read

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM