在让tesseract操作之前,您需要将整个图像变为黑白。
读取图像
import cv2
im_gray = cv2.imread('your_image_here', cv2.IMREAD_GRAYSCALE)
(thresh, im_bw) = cv2.threshold(im_gray, 128, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU)
thresh = 127
im_bw = cv2.threshold(im_gray, thresh, 255, cv2.THRESH_BINARY)[1]
写入磁盘
cv2.imwrite('bw_image.png', im_bw)
您可以通过简单的转换将灰色像素转换为白色像素。 如果您不想使用OpenCV且您的图像是单通道(灰度)NumPy数组:
threshold = 60 # try something between 30 and 150
vect_func = np.vectorize(lambda x: 0 if x == threshold else 255)
black_white_img = vect_func(gray_scale_image)
cv2.threshold(im_gray, THRESH=0, 255, cv2.THRESH_OTSU)
- Milad Shaker