3

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

在此处输入图像描述

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

在此处输入图像描述

我试图得到白色矩形的轮廓,但我得到了这个结果:

在此处输入图像描述

有人知道如何做得更好吗?

这是我的代码:/

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

1 回答 1

2

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

在此处输入图像描述

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()
于 2020-01-20T23:15:53.463 回答