如何使用OpenCV从图像中提取感兴趣的ID文档区域?

问题描述 投票:2回答:1

我试图分割此图像,因为我只需要获取文档。

enter image description here

应用一些过滤器,我得到了这个结果:

enter image description here

我正在尝试获取白色矩形的轮廓,但得到以下结果:

enter image description here

任何人都知道如何做得更好?

这是我的代码:/

import cv2

image = cv2.imread('roberto.jpg')

image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)

_, binary = cv2.threshold(gray, 225, 255, cv2.THRESH_BINARY_INV)
cv2.imshow('test', binary)
cv2.waitKey(0)

contours, hierarchy = cv2.findContours(binary, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)[-2:]
idx = 0 
for cnt in contours:
    idx += 1
    x,y,w,h = cv2.boundingRect(cnt)
    roi=binary[y:y+h,x:x+w]
    cv2.rectangle(image,(x,y),(x+w,y+h),(200,0,0),2)
cv2.imshow('img',image)
cv2.waitKey(0) 
python image opencv image-processing computer-vision
1个回答
1
投票

[您快到了,您只需要使用x,y,w,h获得cv2.boundingRect边界矩形坐标,然后就可以使用Numpy切片来提取/保存ROI。结果是

enter image description here

import cv2

# Load image, grayscale, threshold
image = cv2.imread('1.jpg')
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
blur = cv2.GaussianBlur(gray, (3,3), 0)
thresh = cv2.threshold(gray, 225, 255, cv2.THRESH_BINARY_INV)[1]

# Get bounding box and extract ROI
x,y,w,h = cv2.boundingRect(thresh)
ROI = image[y:y+h, x:x+w]

cv2.imshow('thresh', thresh)
cv2.imshow('ROI', ROI)
cv2.waitKey()
© www.soinside.com 2019 - 2024. All rights reserved.