我正在尝试使用带有 opencv 和 c++ 的 Tesseract 库对包含数字和字符的图像进行 OCR。在调用 tesseract 库之前,我曾经用 opencv 对图像进行灰度化
cvtColor(roiImg,roiImg,CV_BGR2GRAY);
这是
这张图片的 OCR 结果并非 100% 准确。
然后用 python 的 pillow 库测试了相同的图像。使用以下方法对原始图像进行灰度化。
gray = image.convert('L')
这是
后者提到的灰度图像给出了 100% 准确的结果。
我在互联网上搜索后提到 opencv BGR2Gray 和 pillow img.convert 方法都使用相同的亮度变换算法。
两个不同的OCR结果是什么原因?
提前致谢
最佳答案
Pillow对于彩色图像只能读取 3x8 位像素。
这里有一个快速测试,看看两个库如何舍入值:
OpenCV代码:
cv::Mat img(2, 1, CV_8UC3), img_gray; img.at<cv::Vec3b>(0, 0) = cv::Vec3b(248, 249, 249); //BGR img.at<cv::Vec3b>(1, 0) = cv::Vec3b(249, 248, 248); //BGR cv::cvtColor(img, img_gray, cv::COLOR_BGR2GRAY); std::cout << "img:\n" << img << std::endl; std::cout << "img_gray:\n" << img_gray << std::endl; float val1 = 249*0.299f + 249*0.587f + 248*0.114f; //RGB float val2 = 248*0.299f + 248*0.587f + 249*0.114f; //RGB std::cout << "val1=" << val1 << std::endl; std::cout << "val2=" << val2 << std::endl;
img:
[248, 249, 249;
249, 248, 248]
img_gray:
[249;
248]
val1=248.886
val2=248.114
Python代码:
rgbArray = np.zeros((2,1,3), 'uint8') rgbArray[0,0,0] = 249 #R rgbArray[0,0,1] = 249 #G rgbArray[0,0,2] = 248 #B rgbArray[1,0,0] = 248 #R rgbArray[1,0,1] = 248 #G rgbArray[1,0,2] = 249 #B img = Image.fromarray(rgbArray) imgGray = img.convert('L') print("rgbArray:\n", rgbArray) print("imgGray:\n", np.asarray(imgGray)) print("np.asarray(imgGray).dtype: ", np.asarray(imgGray).dtype)
rgbArray:
[[[249 249 248]]
[[248 248 249]]]
imgGray:
[[248]
[248]]
np.asarray(imgGray).dtype: uint8
关于c++ - opencv BGR2GRAY 和 Pillow 转换函数之间的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41996634/