Python 使用 Tesseract 和 OpenCV 识别图像中 'NAR' 字符并获取坐标
以下是使用 Tesseract 和 cv2 技术来读取图像中包含'NAR'字符的坐标,并输出坐标值的示例代码:
import cv2
import pytesseract
# 读取图像
image = cv2.imread('image.jpg')
# 将图像转为灰度图像
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# 使用Tesseract进行OCR识别
text = pytesseract.image_to_string(gray)
# 寻找包含'NAR'的字符的坐标
coords = []
h, w = image.shape[:2]
for text in text.split():
if 'NAR' in text:
result = cv2.findContours(gray.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
contours, _ = result if len(result) == 2 else result[1:]
for contour in contours:
(x, y, w, h) = cv2.boundingRect(contour)
if w > 10 and h > 10: # 过滤掉过小的边界框
coords.append((x, y, x + w, y + h))
# 显示坐标值
for (x1, y1, x2, y2) in coords:
cv2.rectangle(image, (x1, y1), (x2, y2), (0, 255, 0), 2)
cv2.putText(image, f'{x1},{y1}', (x1, y1 - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.9, (0, 255, 0), 2)
# 显示图像
cv2.imshow('Image', image)
cv2.waitKey(0)
cv2.destroyAllWindows()
请确保已经安装了opencv-python和pytesseract库,并将图像文件命名为image.jpg并放在当前工作目录下。运行代码后,将会显示包含'NAR'字符的边界框,并在每个边界框上方显示坐标值。
原文地址: https://www.cveoy.top/t/topic/o0Pg 著作权归作者所有。请勿转载和采集!