[英]OpenCV Python: find contours/edges/rectangle in an image
我正在使用Python2.7.12和OpenCV 3.0.0-rc1
我正在研究文本识别项目。
这就是我现在得到的。 在findContour之后的原始iamge,第34行
如您所见,图像包含很多“框”,其中包含文本。
我的方法是找到这些盒子,将它们切成单独的图像,然后将它们输入TesseractOCR。
该程序将整个图像视为一个轮廓。 我如何在里面找到较小的一个?
或者,如果您有其他选择,欢迎
码:
import cv2
def threshold(im, method):
# make it grayscale
im_gray = cv2.cvtColor(im, cv2.COLOR_RGB2GRAY)
if method == 'fixed':
threshed_im = cv2.threshold(im_gray, 128, 255, cv2.THRESH_BINARY)
elif method == 'mean':
threshed_im = cv2.adaptiveThreshold(im_gray, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, 5, 10)
elif method == 'gaussian':
threshed_im = cv2.adaptiveThreshold(im_gray, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 5, 7)
else:
return None
return threshed_im
image = cv2.imread('demo4.jpg')
# threshold it
thresh = threshold(image, 'mean')
# find contours
_, cnts, hierarchy = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
print len(cnts)
cv2.drawContours(image, cnts, -1, (0, 255, 0), 20)
cv2.imshow('contours', image)
cv2.waitKey()
cv2.drawContours(thresh, cnts, -1, (0, 255, 0), 20)
cv2.imshow('contours', thresh)
cv2.waitKey()
`
因为指定了cv2.RETR_EXTERNAL
所以您只会得到最外面的轮廓。 要获取图像的所有轮廓,应调用如下方法:
cv2.findContours(thresh.copy(), cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
查看OpenCV文档以了解该功能如何工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.