如何将笛卡尔坐标转换为FreeType中的图像坐标

时间:2013-09-21 03:48:18

标签: image opencv fonts coordinate freetype

最近,我用中文字符表示OCR,我想用 FreeType(2.3.5)来收集字符样本,这是我的代码:

FT_Library fontLibrary;
FT_Face fontFace;
int fontSize = 64;

// Initialize
FT_Init_FreeType(&fontLibrary);
FT_New_Face(fontLibrary, "C:\\Windows\\Fonts\\simhei.ttf", 0, &fontFace);

// Setup
FT_Select_Charmap(fontFace, FT_ENCODING_UNICODE);
FT_Set_Pixel_Sizes(fontFace, fontSize, 0);
FT_Load_Char(fontFace, 'H', FT_LOAD_RENDER);

// Retrieve data
FT_GlyphSlot & glyphSlot = fontFace->glyph;
FT_Bitmap charBitmap = glyphSlot->bitmap;
int charWidth = charBitmap.width;
int charHeight = charBitmap.rows;
unsigned char* charBuffer = charBitmap.buffer;

// Construct image
Mat fontImage(fontSize, fontSize, CV_8UC1);
fontImage = Scalar::all(0);
for (int y = 0; y < charHeight; y++)
{
    int row = fontSize - glyphSlot->bitmap_top + y;
    for (int x = 0; x < charWidth; x++)
    {
        int col = glyphSlot->bitmap_left + x;
        fontImage.at<uchar>(row, col) = charBuffer[y*charWidth + x];
    }
}

imshow("Font Image", fontImage);
waitKey(0);

// Uninitialize
FT_Done_Face(fontFace);
FT_Done_FreeType(fontLibrary);

问题是:字符在图像中心不对齐,字符图像的坐标看起来很奇怪,在本例中,'H'字符的坐标是(fontSize = 64):

bitmap_left = 3
bitmap_top = 44
bitmap.width = 26
bitmap.rows = 43

然后转换为图像的坐标:

ROI.left = bitmap_left = 3;
ROI.right = bitmap_left + bitmap.width = 29;
ROI.top = fontSize - bitmap_top = 20;
ROI.bottom = fontSize - bitmap_top + bitmap.rows = 63;

所以4方向的边距是:

ROI.leftMargin = 3;
ROI.rightMargin = 64 - 29 = 35;
ROI.topMargin = 20;
ROI.bottomMargin = 64 - 63 = 1;

它不是中心对齐!!!

1 个答案:

答案 0 :(得分:-1)

我自己解决问题,图像的左上角坐标存储在 glyphSlot 中,这是博客: 的 http://kang.blog.com/2013/09/21/how-to-convert-the-cartier-coordinate-to-image-coordinate-in-freetype/