c++ - opencv BGR2GRAY 和 Pillow 转换函数之间的区别

标签 c++ opencv image-processing pillow

我正在尝试使用带有 opencv 和 c++ 的 Tesseract 库对包含数字和字符的图像进行 OCR。在调用 tesseract 库之前,我曾经用 opencv 对图像进行灰度化

cvtColor(roiImg,roiImg,CV_BGR2GRAY);

这是 Gray scale image i received with python

这张图片的 OCR 结果并非 100% 准确。

然后用 python 的 pillow 库测试了相同的图像。使用以下方法对原始图像进行灰度化。

gray = image.convert('L')

这是 Gray Scale image i received with pillow library

后者提到的灰度图像给出了 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/

相关文章:

python - 如何使用带有图像的边界框进行多标签图像训练?

c++ - Openvms C++ - 如何将值传递给环境

c++ - 将值插入已发布的图像?

c++ - Visual Studio 在我从项目中删除的文件上抛出错误

c++ - OPENCV waitKey() 方法返回类型

matlab - MATLAB 函数 imread 和 imwrite 是否属于图像处理工具包?

c++ - 在独立的 Xcode playground 中运行 c 或 c++ 代码

python - 无法在 mac 上的 python 中使用 opencv 读取 xvid 视频

Python OpenCV 在其他应用程序之上打开窗口

opencv - 复杂背景的段性特征