【发布时间】:2019-10-26 17:19:48
【问题描述】:
我有多个不同背景的图片,
我需要忽略背景并从我的图像中提取数字。例如:
经过测试,我有这个结果:
因为背景色,提取文字非常困难..
我正在使用此代码:
image = cv2.imread('AA.png')
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
thresh = cv2.threshold(gray, 165, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)[1]
# Invert image and perform morphological operations
inverted = 255 - thresh
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (15,3))
close = cv2.morphologyEx(inverted, cv2.MORPH_CLOSE, kernel, iterations=1)
# Find contours and filter using aspect ratio and area
cnts = cv2.findContours(close, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if len(cnts) == 2 else cnts[1]
for c in cnts:
area = cv2.contourArea(c)
peri = cv2.arcLength(c, True)
approx = cv2.approxPolyDP(c, 0.01 * peri, True)
x,y,w,h = cv2.boundingRect(approx)
aspect_ratio = w / float(h)
if (aspect_ratio >= 2.5 or area < 75):
cv2.drawContours(thresh, [c], -1, (255,255,255), -1)
# Blur and perform text extraction
thresh = cv2.GaussianBlur(thresh, (3,3), 0)
data = pytesseract.image_to_string(thresh, lang='eng',config='tessedit_char_whitelist=0123456789 --psm 6')
print(data)
cv2.imshow('close', close)
cv2.imshow('thresh', thresh)
cv2.waitKey()
即使背景颜色发生变化,我如何才能准确地从该图像中提取数字?
修改后的编辑结果:
【问题讨论】:
-
你的阈值不是很好。删除
gray[gray < 100] = 255。在 165 处尝试 cv2.threshold。然后获取轮廓并移除太小的轮廓。然后将 thresh 图像反转为 (255 - thresh),使字母在白色背景上显示为黑色。 -
@fmw42,你说得对,灰色,我已经用你在最后一张图片上的参数更新了我的第一篇文章,我丢失了图片顶部的文本数字“1”,我该如何解决?跨度>
标签: python opencv image-processing image-recognition python-tesseract